aboutsummaryrefslogtreecommitdiffhomepage
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--.gitignore14
-rw-r--r--.gitmodules4
-rw-r--r--.travis.yml8
-rw-r--r--BUILD110
-rw-r--r--CHANGES.txt88
-rw-r--r--LICENSE12
-rw-r--r--Makefile.am148
-rw-r--r--Protobuf.podspec2
-rw-r--r--README.md27
-rw-r--r--WORKSPACE27
-rw-r--r--appveyor.bat18
-rw-r--r--appveyor.yml41
-rwxr-xr-xautogen.sh18
-rw-r--r--benchmarks/Makefile.am474
-rw-r--r--benchmarks/README.md56
-rw-r--r--benchmarks/cpp/cpp_benchmark.cc (renamed from benchmarks/cpp_benchmark.cc)4
-rw-r--r--benchmarks/datasets/google_message1/proto2/benchmark_message1_proto2.proto (renamed from benchmarks/datasets/google_message1/benchmark_message1_proto2.proto)0
-rw-r--r--benchmarks/datasets/google_message1/proto2/dataset.google_message1_proto2.pb (renamed from benchmarks/datasets/google_message1/dataset.google_message1_proto2.pb)bin289 -> 289 bytes
-rw-r--r--benchmarks/datasets/google_message1/proto3/benchmark_message1_proto3.proto (renamed from benchmarks/datasets/google_message1/benchmark_message1_proto3.proto)0
-rw-r--r--benchmarks/datasets/google_message1/proto3/dataset.google_message1_proto3.pb (renamed from benchmarks/datasets/google_message1/dataset.google_message1_proto3.pb)bin289 -> 289 bytes
-rw-r--r--benchmarks/go/go_benchmark_test.go124
-rw-r--r--[-rwxr-xr-x]benchmarks/java/pom.xml5
-rwxr-xr-xbenchmarks/java/src/main/java/com/google/protobuf/ProtoBench.java178
-rw-r--r--[-rwxr-xr-x]benchmarks/java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java79
-rw-r--r--benchmarks/python/__init__.py0
-rwxr-xr-xbenchmarks/python/py_benchmark.py (renamed from benchmarks/py_benchmark.py)74
-rw-r--r--benchmarks/python/python_benchmark_messages.cc (renamed from benchmarks/python_benchmark_messages.cc)4
-rw-r--r--benchmarks/util/__init__.py0
-rwxr-xr-xbenchmarks/util/big_query_utils.py189
-rw-r--r--benchmarks/util/data_proto2_to_proto3_util.h64
-rw-r--r--benchmarks/util/gogo_data_scrubber.cc74
-rw-r--r--benchmarks/util/proto3_data_stripper.cc74
-rw-r--r--benchmarks/util/protoc-gen-gogoproto.cc103
-rw-r--r--benchmarks/util/protoc-gen-proto2_to_proto3.cc115
-rwxr-xr-xbenchmarks/util/run_and_upload.py292
-rw-r--r--benchmarks/util/schema_proto2_to_proto3_util.h194
-rw-r--r--cmake/CMakeLists.txt30
-rw-r--r--cmake/README.md42
-rw-r--r--cmake/extract_includes.bat.in32
-rw-r--r--cmake/install.cmake14
-rw-r--r--cmake/libprotobuf-lite.cmake12
-rw-r--r--cmake/libprotobuf.cmake8
-rw-r--r--cmake/libprotoc.cmake66
-rw-r--r--cmake/protobuf-config.cmake.in22
-rw-r--r--cmake/protoc.cmake11
-rw-r--r--cmake/tests.cmake34
-rw-r--r--cmake/version.rc.in45
-rw-r--r--configure.ac15
-rw-r--r--conformance/conformance_cpp.cc1
-rw-r--r--conformance/conformance_test.cc22
-rw-r--r--conformance/conformance_test.h3
-rw-r--r--conformance/conformance_test_runner.cc3
-rw-r--r--conformance/failure_list_ruby.txt2
-rw-r--r--csharp/Google.Protobuf.Tools.nuspec4
-rw-r--r--csharp/Google.Protobuf.Tools.targets11
-rw-r--r--csharp/README.md12
-rw-r--r--csharp/build_packages.bat2
-rwxr-xr-xcsharp/buildall.sh2
-rw-r--r--csharp/src/AddressBook/Addressbook.cs2
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf.Test/ByteStringTest.cs0
-rw-r--r--csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs83
-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/Google.Protobuf.Test.csproj8
-rw-r--r--csharp/src/Google.Protobuf.Test/JsonParserTest.cs16
-rw-r--r--csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs2
-rw-r--r--csharp/src/Google.Protobuf.Test/TestProtos/TestMessagesProto3.cs20
-rw-r--r--csharp/src/Google.Protobuf.Test/TestProtos/UnittestCustomOptionsProto3.cs6
-rw-r--r--csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs2
-rw-r--r--csharp/src/Google.Protobuf.Test/TestProtos/UnittestProto3.cs24
-rw-r--r--csharp/src/Google.Protobuf.Test/TestProtos/UnittestWellKnownTypes.cs20
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf/ByteString.cs0
-rw-r--r--csharp/src/Google.Protobuf/CodedInputStream.cs6
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf/Collections/RepeatedField.cs0
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf/Compatibility/MethodInfoExtensions.cs (renamed from csharp/src/Google.Protobuf.Test/Program.cs)25
-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.csproj8
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf/JsonFormatter.cs0
-rw-r--r--csharp/src/Google.Protobuf/JsonParser.cs5
-rw-r--r--csharp/src/Google.Protobuf/Reflection/Descriptor.cs201
-rw-r--r--csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs24
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs0
-rw-r--r--csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs2
-rw-r--r--csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs176
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Api.cs2
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs4
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs0
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Type.cs6
-rw-r--r--docs/performance.md304
-rw-r--r--docs/third_party.md6
-rw-r--r--examples/add_person_test.go4
-rwxr-xr-xgenerate_changelog.py5
-rw-r--r--gmock.BUILD28
-rw-r--r--java/README.md81
-rw-r--r--java/core/generate-test-sources-build.xml1
-rw-r--r--java/core/pom.xml3
-rw-r--r--java/core/src/main/java/com/google/protobuf/AbstractMessage.java10
-rw-r--r--java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java10
-rw-r--r--java/core/src/main/java/com/google/protobuf/BooleanArrayList.java16
-rw-r--r--java/core/src/main/java/com/google/protobuf/CodedInputStream.java6
-rw-r--r--java/core/src/main/java/com/google/protobuf/CodedOutputStream.java18
-rw-r--r--java/core/src/main/java/com/google/protobuf/DoubleArrayList.java16
-rw-r--r--java/core/src/main/java/com/google/protobuf/DynamicMessage.java18
-rw-r--r--java/core/src/main/java/com/google/protobuf/FloatArrayList.java16
-rw-r--r--java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java128
-rw-r--r--java/core/src/main/java/com/google/protobuf/IntArrayList.java16
-rw-r--r--java/core/src/main/java/com/google/protobuf/LongArrayList.java16
-rw-r--r--java/core/src/main/java/com/google/protobuf/MessageLiteToString.java96
-rw-r--r--java/core/src/main/java/com/google/protobuf/TextFormat.java51
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java24
-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.java10
-rw-r--r--java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java15
-rw-r--r--java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java43
-rw-r--r--java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java15
-rw-r--r--java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java15
-rw-r--r--java/core/src/test/java/com/google/protobuf/IntArrayListTest.java15
-rw-r--r--java/core/src/test/java/com/google/protobuf/LiteTest.java1453
-rw-r--r--java/core/src/test/java/com/google/protobuf/LongArrayListTest.java15
-rw-r--r--java/core/src/test/java/com/google/protobuf/MapForProto2Test.java18
-rw-r--r--java/core/src/test/java/com/google/protobuf/MapTest.java18
-rw-r--r--java/core/src/test/java/com/google/protobuf/TextFormatTest.java17
-rw-r--r--java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java21
-rw-r--r--java/core/src/test/java/com/google/protobuf/WireFormatTest.java21
-rw-r--r--java/core/src/test/proto/com/google/protobuf/map_lite_test.proto111
-rw-r--r--java/lite.md50
-rw-r--r--java/lite/generate-sources-build.xml20
-rw-r--r--java/lite/generate-test-sources-build.xml43
-rw-r--r--java/lite/pom.xml185
-rw-r--r--java/pom.xml5
-rw-r--r--java/util/pom.xml2
-rw-r--r--javanano/README.md401
-rw-r--r--javanano/pom.xml244
-rw-r--r--javanano/src/main/java/com/google/protobuf/nano/CodedInputByteBufferNano.java683
-rw-r--r--javanano/src/main/java/com/google/protobuf/nano/CodedOutputByteBufferNano.java1214
-rw-r--r--javanano/src/main/java/com/google/protobuf/nano/ExtendableMessageNano.java169
-rw-r--r--javanano/src/main/java/com/google/protobuf/nano/Extension.java706
-rw-r--r--javanano/src/main/java/com/google/protobuf/nano/FieldArray.java291
-rw-r--r--javanano/src/main/java/com/google/protobuf/nano/FieldData.java240
-rw-r--r--javanano/src/main/java/com/google/protobuf/nano/InternalNano.java547
-rw-r--r--javanano/src/main/java/com/google/protobuf/nano/InvalidProtocolBufferNanoException.java93
-rw-r--r--javanano/src/main/java/com/google/protobuf/nano/MapFactories.java67
-rw-r--r--javanano/src/main/java/com/google/protobuf/nano/MessageNano.java198
-rw-r--r--javanano/src/main/java/com/google/protobuf/nano/MessageNanoPrinter.java275
-rw-r--r--javanano/src/main/java/com/google/protobuf/nano/UnknownFieldData.java88
-rw-r--r--javanano/src/main/java/com/google/protobuf/nano/WireFormatNano.java124
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/NanoTest.java4471
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/map_test.proto70
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/unittest_accessors_nano.proto118
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/unittest_enum_validity_nano.proto28
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/unittest_extension_nano.proto37
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/unittest_extension_packed_nano.proto29
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/unittest_extension_repeated_nano.proto34
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/unittest_extension_singular_nano.proto34
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/unittest_has_nano.proto82
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/unittest_import_nano.proto48
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/unittest_nano.proto195
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/unittest_recursive_nano.proto49
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/unittest_reference_types_nano.proto116
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_packables_nano.proto95
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/unittest_simple_nano.proto54
-rw-r--r--jenkins/README.md6
-rwxr-xr-xjenkins/build_and_run_docker.sh57
-rw-r--r--jenkins/buildcmds/README.md6
-rwxr-xr-xjenkins/buildcmds/pull_request.sh16
-rwxr-xr-xjenkins/buildcmds/pull_request_32.sh16
-rw-r--r--jenkins/docker/Dockerfile244
-rw-r--r--jenkins/docker32/Dockerfile143
-rw-r--r--jenkins/make_test_output.py94
-rwxr-xr-xjenkins/pull_request_in_docker.sh66
-rw-r--r--js/README.md1
-rw-r--r--js/binary/constants.js19
-rw-r--r--js/binary/decoder.js2
-rw-r--r--js/binary/utils.js4
-rw-r--r--js/binary/writer.js6
-rw-r--r--js/binary/writer_test.js12
-rw-r--r--js/commonjs/strict_test.js (renamed from javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nano.proto)56
-rw-r--r--js/debug.js2
-rw-r--r--js/gulpfile.js18
-rw-r--r--js/map.js31
-rwxr-xr-xjs/maps_test.js40
-rw-r--r--js/message.js93
-rw-r--r--js/message_test.js12
-rw-r--r--js/package.json2
-rw-r--r--js/test10.proto (renamed from javanano/src/test/java/com/google/protobuf/nano/unittest_single_nano.proto)9
-rw-r--r--js/test9.proto (renamed from javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nameclash_nano.proto)14
-rw-r--r--js/testbinary.proto32
-rwxr-xr-xkokoro/linux/bazel/build.sh9
-rw-r--r--kokoro/linux/bazel/continuous.cfg (renamed from kokoro/macos/jruby/continuous.cfg)4
-rw-r--r--kokoro/linux/bazel/presubmit.cfg (renamed from kokoro/macos/jruby/presubmit.cfg)4
-rwxr-xr-xkokoro/linux/benchmark/build.sh92
-rwxr-xr-x[-rw-r--r--]kokoro/linux/benchmark/continuous.cfg (renamed from kokoro/linux/javanano_jdk7/continuous.cfg)4
-rwxr-xr-xkokoro/linux/javanano_jdk7/build.sh17
-rw-r--r--kokoro/linux/javanano_jdk7/presubmit.cfg11
-rwxr-xr-xkokoro/linux/javanano_oracle7/build.sh17
-rw-r--r--kokoro/linux/javanano_oracle7/continuous.cfg11
-rw-r--r--kokoro/linux/javanano_oracle7/presubmit.cfg11
-rwxr-xr-xkokoro/linux/pull_request_in_docker.sh3
-rwxr-xr-xkokoro/macos/jruby/build.sh11
-rwxr-xr-xkokoro/release/linux/build_artifacts.sh14
-rwxr-xr-xkokoro/release/linux/prepare_build.sh16
-rw-r--r--kokoro/release/linux/release.cfg8
-rwxr-xr-xkokoro/release/linux/ruby/ruby_build.sh15
-rwxr-xr-xkokoro/release/linux/ruby/ruby_build_environment.sh8
-rwxr-xr-xkokoro/release/macos/build_artifacts.sh19
-rw-r--r--kokoro/release/macos/release.cfg8
-rwxr-xr-xkokoro/release/macos/ruby/ruby_build.sh15
-rwxr-xr-xkokoro/release/macos/ruby/ruby_build_environment.sh57
-rw-r--r--kokoro/release/protoc/macos/build.sh23
-rw-r--r--kokoro/release/protoc/macos/release.cfg8
-rw-r--r--kokoro/release/protoc/windows/build.bat27
-rw-r--r--kokoro/release/protoc/windows/release.cfg8
-rw-r--r--m4/acx_pthread.m4397
-rw-r--r--m4/ax_pthread.m4485
-rwxr-xr-xmore_tests/Makefile41
-rwxr-xr-xobjectivec/DevTools/full_mac_build.sh17
-rw-r--r--objectivec/GPBArray.m4
-rw-r--r--objectivec/GPBCodedInputStream.m6
-rw-r--r--objectivec/GPBCodedOutputStream.m5
-rw-r--r--objectivec/GPBDescriptor.h34
-rw-r--r--objectivec/GPBDescriptor.m41
-rw-r--r--objectivec/GPBDictionary.m4
-rw-r--r--objectivec/GPBProtocolBuffers_RuntimeSupport.h2
-rw-r--r--objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj110
-rw-r--r--objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist8
-rw-r--r--objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme4
-rw-r--r--objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme8
-rw-r--r--objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj256
-rw-r--r--objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist8
-rw-r--r--objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme4
-rw-r--r--objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme19
-rw-r--r--objectivec/README.md9
-rw-r--r--objectivec/Tests/GPBCodedOuputStreamTests.m10
-rw-r--r--objectivec/Tests/GPBCompileTest01.m (renamed from javanano/src/test/java/com/google/protobuf/nano/unittest_stringutf8_nano.proto)17
-rw-r--r--objectivec/Tests/GPBCompileTest02.m (renamed from javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_nano.proto)20
-rw-r--r--objectivec/Tests/GPBCompileTest03.m40
-rw-r--r--objectivec/Tests/GPBCompileTest04.m40
-rw-r--r--objectivec/Tests/GPBCompileTest05.m40
-rw-r--r--objectivec/Tests/GPBCompileTest06.m40
-rw-r--r--objectivec/Tests/GPBCompileTest07.m40
-rw-r--r--objectivec/Tests/GPBCompileTest08.m40
-rw-r--r--objectivec/Tests/GPBCompileTest09.m40
-rw-r--r--objectivec/Tests/GPBCompileTest10.m40
-rw-r--r--objectivec/Tests/GPBCompileTest11.m40
-rw-r--r--objectivec/Tests/GPBCompileTest12.m40
-rw-r--r--objectivec/Tests/GPBCompileTest13.m40
-rw-r--r--objectivec/Tests/GPBCompileTest14.m40
-rw-r--r--objectivec/Tests/GPBCompileTest15.m40
-rw-r--r--objectivec/Tests/GPBCompileTest16.m40
-rw-r--r--objectivec/Tests/GPBCompileTest17.m40
-rw-r--r--objectivec/Tests/GPBCompileTest18.m40
-rw-r--r--objectivec/Tests/GPBCompileTest19.m40
-rw-r--r--objectivec/Tests/GPBCompileTest20.m40
-rw-r--r--objectivec/Tests/GPBCompileTest21.m40
-rw-r--r--objectivec/Tests/GPBCompileTest22.m40
-rw-r--r--objectivec/Tests/GPBCompileTest23.m40
-rw-r--r--objectivec/Tests/GPBCompileTest24.m (renamed from javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_merge_nano.proto)21
-rw-r--r--objectivec/Tests/GPBCompileTest25.m (renamed from javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_multiple_nano.proto)22
-rw-r--r--objectivec/Tests/GPBDescriptorTests.m57
-rw-r--r--objectivec/Tests/iOSTestHarness/AppDelegate.m35
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/Contents.json152
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_1024.pngbin205605 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_120.pngbin7233 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_152.pngbin10332 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_167.pngbin11694 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_180.pngbin13111 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_20.pngbin752 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_29.pngbin1197 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_40.pngbin1730 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_58.pngbin2748 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_60.pngbin2834 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_76.pngbin3931 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_80.pngbin4125 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_87.pngbin4671 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/LaunchImage.launchimage/Contents.json36
-rw-r--r--objectivec/Tests/iOSTestHarness/Info.plist43
-rw-r--r--objectivec/Tests/iOSTestHarness/LaunchScreen.xib33
-rw-r--r--objectivec/Tests/iOSTestHarness/en.lproj/InfoPlist.strings2
-rw-r--r--objectivec/google/protobuf/Any.pbobjc.h8
-rw-r--r--objectivec/google/protobuf/Api.pbobjc.h8
-rw-r--r--objectivec/google/protobuf/Duration.pbobjc.h8
-rw-r--r--objectivec/google/protobuf/Empty.pbobjc.h8
-rw-r--r--objectivec/google/protobuf/FieldMask.pbobjc.h12
-rw-r--r--objectivec/google/protobuf/SourceContext.pbobjc.h8
-rw-r--r--objectivec/google/protobuf/Struct.pbobjc.h8
-rw-r--r--objectivec/google/protobuf/Timestamp.pbobjc.h8
-rw-r--r--objectivec/google/protobuf/Type.pbobjc.h8
-rw-r--r--objectivec/google/protobuf/Wrappers.pbobjc.h8
-rw-r--r--php/README.md2
-rw-r--r--php/ext/google/protobuf/def.c254
-rw-r--r--php/ext/google/protobuf/encode_decode.c5
-rw-r--r--php/ext/google/protobuf/map.c44
-rw-r--r--php/ext/google/protobuf/message.c188
-rw-r--r--php/ext/google/protobuf/package.xml38
-rw-r--r--php/ext/google/protobuf/protobuf.c37
-rw-r--r--php/ext/google/protobuf/protobuf.h13
-rw-r--r--php/ext/google/protobuf/upb.c2015
-rw-r--r--php/ext/google/protobuf/upb.h989
-rw-r--r--php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php14
-rw-r--r--php/src/Google/Protobuf/Any.php108
-rw-r--r--php/src/Google/Protobuf/Api.php44
-rw-r--r--php/src/Google/Protobuf/BoolValue.php14
-rw-r--r--php/src/Google/Protobuf/BytesValue.php14
-rw-r--r--php/src/Google/Protobuf/DoubleValue.php14
-rw-r--r--php/src/Google/Protobuf/Duration.php24
-rw-r--r--php/src/Google/Protobuf/Enum.php22
-rw-r--r--php/src/Google/Protobuf/EnumValue.php18
-rw-r--r--php/src/Google/Protobuf/Field.php34
-rw-r--r--php/src/Google/Protobuf/Field/Cardinality.php42
-rw-r--r--php/src/Google/Protobuf/Field/Kind.php132
-rw-r--r--php/src/Google/Protobuf/FieldMask.php18
-rw-r--r--php/src/Google/Protobuf/Field_Cardinality.php35
-rw-r--r--php/src/Google/Protobuf/Field_Kind.php125
-rw-r--r--php/src/Google/Protobuf/FloatValue.php14
-rw-r--r--php/src/Google/Protobuf/GPBEmpty.php12
-rw-r--r--php/src/Google/Protobuf/Int32Value.php14
-rw-r--r--php/src/Google/Protobuf/Int64Value.php14
-rw-r--r--php/src/Google/Protobuf/Internal/Descriptor.php14
-rw-r--r--php/src/Google/Protobuf/Internal/DescriptorPool.php2
-rw-r--r--php/src/Google/Protobuf/Internal/DescriptorProto.php32
-rw-r--r--php/src/Google/Protobuf/Internal/DescriptorProto/ExtensionRange.php (renamed from php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php)22
-rw-r--r--php/src/Google/Protobuf/Internal/DescriptorProto/ReservedRange.php (renamed from php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php)23
-rw-r--r--php/src/Google/Protobuf/Internal/EnumDescriptor.php14
-rw-r--r--php/src/Google/Protobuf/Internal/EnumDescriptorProto.php26
-rw-r--r--php/src/Google/Protobuf/Internal/EnumDescriptorProto/EnumReservedRange.php (renamed from php/src/Google/Protobuf/Internal/EnumDescriptorProto_EnumReservedRange.php)23
-rw-r--r--php/src/Google/Protobuf/Internal/EnumOptions.php22
-rw-r--r--php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php15
-rw-r--r--php/src/Google/Protobuf/Internal/EnumValueOptions.php19
-rw-r--r--php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php14
-rw-r--r--php/src/Google/Protobuf/Internal/FieldDescriptorProto.php42
-rw-r--r--php/src/Google/Protobuf/Internal/FieldDescriptorProto/Label.php (renamed from php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php)9
-rw-r--r--php/src/Google/Protobuf/Internal/FieldDescriptorProto/Type.php (renamed from php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php)9
-rw-r--r--php/src/Google/Protobuf/Internal/FieldOptions.php68
-rw-r--r--php/src/Google/Protobuf/Internal/FieldOptions/CType.php (renamed from php/src/Google/Protobuf/Internal/FieldOptions_CType.php)9
-rw-r--r--php/src/Google/Protobuf/Internal/FieldOptions/JSType.php (renamed from php/src/Google/Protobuf/Internal/FieldOptions_JSType.php)9
-rw-r--r--php/src/Google/Protobuf/Internal/FileDescriptorProto.php37
-rw-r--r--php/src/Google/Protobuf/Internal/FileDescriptorSet.php13
-rw-r--r--php/src/Google/Protobuf/Internal/FileOptions.php185
-rw-r--r--php/src/Google/Protobuf/Internal/FileOptions/OptimizeMode.php (renamed from php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php)9
-rw-r--r--php/src/Google/Protobuf/Internal/GPBUtil.php50
-rw-r--r--php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php19
-rw-r--r--php/src/Google/Protobuf/Internal/GeneratedCodeInfo/Annotation.php (renamed from php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php)31
-rw-r--r--php/src/Google/Protobuf/Internal/MapField.php25
-rw-r--r--php/src/Google/Protobuf/Internal/Message.php252
-rw-r--r--php/src/Google/Protobuf/Internal/MessageOptions.php58
-rw-r--r--php/src/Google/Protobuf/Internal/MethodDescriptorProto.php22
-rw-r--r--php/src/Google/Protobuf/Internal/MethodOptions.php20
-rw-r--r--php/src/Google/Protobuf/Internal/MethodOptions/IdempotencyLevel.php (renamed from php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php)9
-rw-r--r--php/src/Google/Protobuf/Internal/OneofDescriptorProto.php14
-rw-r--r--php/src/Google/Protobuf/Internal/OneofOptions.php14
-rw-r--r--php/src/Google/Protobuf/Internal/RepeatedField.php23
-rw-r--r--php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php15
-rw-r--r--php/src/Google/Protobuf/Internal/ServiceOptions.php19
-rw-r--r--php/src/Google/Protobuf/Internal/SourceCodeInfo.php58
-rw-r--r--php/src/Google/Protobuf/Internal/SourceCodeInfo/Location.php (renamed from php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php)86
-rw-r--r--php/src/Google/Protobuf/Internal/UninterpretedOption.php25
-rw-r--r--php/src/Google/Protobuf/Internal/UninterpretedOption/NamePart.php (renamed from php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php)21
-rw-r--r--php/src/Google/Protobuf/ListValue.php14
-rw-r--r--php/src/Google/Protobuf/Method.php26
-rw-r--r--php/src/Google/Protobuf/Mixin.php17
-rw-r--r--php/src/Google/Protobuf/NullValue.php2
-rw-r--r--php/src/Google/Protobuf/Option.php22
-rw-r--r--php/src/Google/Protobuf/SourceContext.php15
-rw-r--r--php/src/Google/Protobuf/StringValue.php14
-rw-r--r--php/src/Google/Protobuf/Struct.php14
-rw-r--r--php/src/Google/Protobuf/Syntax.php2
-rw-r--r--php/src/Google/Protobuf/Timestamp.php41
-rw-r--r--php/src/Google/Protobuf/Type.php24
-rw-r--r--php/src/Google/Protobuf/UInt32Value.php14
-rw-r--r--php/src/Google/Protobuf/UInt64Value.php14
-rw-r--r--php/src/Google/Protobuf/Value.php24
-rw-r--r--php/tests/array_test.php12
-rwxr-xr-xphp/tests/compatibility_test.sh49
-rw-r--r--php/tests/descriptors_test.php2
-rw-r--r--php/tests/encode_decode_test.php6
-rwxr-xr-xphp/tests/gdb_test.sh10
-rw-r--r--php/tests/generated_class_test.php223
-rw-r--r--php/tests/generated_phpdoc_test.php14
-rw-r--r--php/tests/map_field_test.php10
-rw-r--r--php/tests/memory_leak_test.php69
-rw-r--r--php/tests/php_implementation_test.php75
-rw-r--r--php/tests/proto/empty/echo.proto17
-rw-r--r--php/tests/proto/test_empty_php_namespace.proto11
-rw-r--r--php/tests/proto/test_include.proto11
-rw-r--r--php/tests/proto/test_no_namespace.proto14
-rw-r--r--php/tests/proto/test_php_namespace.proto23
-rw-r--r--php/tests/proto/test_prefix.proto8
-rwxr-xr-xphp/tests/test.sh18
-rw-r--r--php/tests/test_base.php2
-rw-r--r--php/tests/test_util.php18
-rw-r--r--php/tests/undefined_test.php88
-rw-r--r--php/tests/well_known_test.php12
-rwxr-xr-xpost_process_dist.sh2
-rw-r--r--protobuf.bzl28
-rw-r--r--protoc-artifacts/Dockerfile22
-rw-r--r--protoc-artifacts/README.md8
-rwxr-xr-xprotoc-artifacts/build-protoc.sh6
-rwxr-xr-xprotoc-artifacts/build-zip.sh4
-rw-r--r--protoc-artifacts/pom.xml4
-rwxr-xr-xprotoc-artifacts/scl-enable-devtoolset.sh13
-rw-r--r--python/README.md2
-rwxr-xr-xpython/google/protobuf/__init__.py2
-rw-r--r--python/google/protobuf/compiler/__init__.py0
-rwxr-xr-xpython/google/protobuf/descriptor.py109
-rwxr-xr-xpython/google/protobuf/internal/_parameterized.py50
-rwxr-xr-xpython/google/protobuf/internal/api_implementation.py11
-rwxr-xr-xpython/google/protobuf/internal/encoder.py16
-rw-r--r--python/google/protobuf/internal/json_format_test.py15
-rwxr-xr-xpython/google/protobuf/internal/message_test.py29
-rw-r--r--python/google/protobuf/internal/no_package.proto10
-rwxr-xr-xpython/google/protobuf/internal/text_format_test.py93
-rw-r--r--python/google/protobuf/internal/well_known_types.py10
-rw-r--r--python/google/protobuf/internal/well_known_types_test.py16
-rw-r--r--python/google/protobuf/json_format.py39
-rw-r--r--python/google/protobuf/proto_api.h92
-rw-r--r--python/google/protobuf/pyext/descriptor.cc80
-rw-r--r--python/google/protobuf/pyext/descriptor_pool.cc122
-rw-r--r--python/google/protobuf/pyext/extension_dict.cc3
-rw-r--r--python/google/protobuf/pyext/extension_dict.h15
-rw-r--r--python/google/protobuf/pyext/map_container.cc29
-rw-r--r--python/google/protobuf/pyext/map_container.h17
-rw-r--r--python/google/protobuf/pyext/message.cc55
-rw-r--r--python/google/protobuf/pyext/message.h34
-rw-r--r--python/google/protobuf/pyext/message_factory.cc8
-rw-r--r--python/google/protobuf/pyext/message_module.cc17
-rw-r--r--python/google/protobuf/pyext/repeated_composite_container.cc129
-rw-r--r--python/google/protobuf/pyext/repeated_composite_container.h21
-rw-r--r--python/google/protobuf/pyext/repeated_scalar_container.cc162
-rw-r--r--python/google/protobuf/pyext/repeated_scalar_container.h19
-rw-r--r--python/google/protobuf/pyext/thread_unsafe_shared_ptr.h (renamed from src/google/protobuf/compiler/javanano/javanano_extension.h)88
-rwxr-xr-xpython/google/protobuf/text_format.py88
-rw-r--r--python/google/protobuf/util/__init__.py0
-rwxr-xr-xpython/setup.py49
-rwxr-xr-xpython/stubout.py3
-rw-r--r--ruby/Rakefile15
-rw-r--r--ruby/ext/google/protobuf_c/defs.c10
-rw-r--r--ruby/ext/google/protobuf_c/extconf.rb4
-rw-r--r--ruby/ext/google/protobuf_c/message.c10
-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/google-protobuf.gemspec2
-rw-r--r--ruby/lib/google/protobuf.rb5
-rw-r--r--ruby/lib/google/protobuf/message_exts.rb4
-rw-r--r--ruby/lib/google/protobuf/repeated_field.rb4
-rw-r--r--ruby/lib/google/protobuf/well_known_types.rb12
-rw-r--r--ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java2
-rw-r--r--ruby/tests/basic.rb56
-rw-r--r--ruby/tests/encode_decode_test.rb24
-rw-r--r--ruby/tests/generated_code_test.rb2
-rw-r--r--ruby/tests/repeated_field_test.rb9
-rw-r--r--ruby/tests/test_ruby_package.proto7
-rw-r--r--ruby/tests/well_known_types_test.rb14
-rw-r--r--src/Makefile.am136
-rw-r--r--src/README.md136
-rw-r--r--src/google/protobuf/any.cc11
-rw-r--r--src/google/protobuf/any.h11
-rw-r--r--src/google/protobuf/any.pb.cc67
-rw-r--r--src/google/protobuf/any.pb.h57
-rw-r--r--src/google/protobuf/api.pb.cc183
-rw-r--r--src/google/protobuf/api.pb.h147
-rw-r--r--[-rwxr-xr-x]src/google/protobuf/arena.cc47
-rw-r--r--src/google/protobuf/arena.h586
-rw-r--r--src/google/protobuf/arena_impl.h23
-rw-r--r--src/google/protobuf/arena_test_util.h2
-rw-r--r--src/google/protobuf/arena_unittest.cc52
-rw-r--r--[-rwxr-xr-x]src/google/protobuf/arenastring.h52
-rw-r--r--src/google/protobuf/arenastring_unittest.cc3
-rw-r--r--src/google/protobuf/compiler/annotation_test_util.cc3
-rw-r--r--src/google/protobuf/compiler/code_generator.cc2
-rw-r--r--src/google/protobuf/compiler/command_line_interface.cc43
-rw-r--r--src/google/protobuf/compiler/command_line_interface.h5
-rw-r--r--src/google/protobuf/compiler/command_line_interface_unittest.cc7
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc79
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_enum.cc2
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_enum_field.cc6
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_extension.cc3
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_field.cc28
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_field.h45
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_file.cc285
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_file.h11
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_generator.cc27
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_helpers.cc81
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_helpers.h52
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_map_field.cc12
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_map_field.h1
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message.cc449
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message.h16
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message_field.cc160
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message_field.h17
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_move_unittest.cc2
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_options.h2
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h4
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc5
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_string_field.cc177
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_string_field.h5
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_unittest.cc2243
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_unittest.inc2281
-rw-r--r--src/google/protobuf/compiler/cpp/metadata_test.cc3
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_enum.cc2
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_field_base.cc2
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_generator.cc4
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_helpers.cc2
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_map_field.cc4
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_message.cc22
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_message_field.cc2
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc4
-rw-r--r--src/google/protobuf/compiler/importer.cc14
-rw-r--r--src/google/protobuf/compiler/importer.h15
-rw-r--r--src/google/protobuf/compiler/importer_unittest.cc7
-rw-r--r--src/google/protobuf/compiler/java/java_context.cc8
-rw-r--r--src/google/protobuf/compiler/java/java_context.h5
-rw-r--r--src/google/protobuf/compiler/java/java_enum.cc4
-rw-r--r--src/google/protobuf/compiler/java/java_enum_field.cc11
-rw-r--r--src/google/protobuf/compiler/java/java_enum_field_lite.cc23
-rw-r--r--src/google/protobuf/compiler/java/java_enum_lite.cc6
-rw-r--r--src/google/protobuf/compiler/java/java_extension.cc1
-rw-r--r--src/google/protobuf/compiler/java/java_extension_lite.cc1
-rw-r--r--src/google/protobuf/compiler/java/java_field.cc9
-rw-r--r--src/google/protobuf/compiler/java/java_field.h13
-rw-r--r--src/google/protobuf/compiler/java/java_file.cc33
-rw-r--r--src/google/protobuf/compiler/java/java_file.h11
-rw-r--r--src/google/protobuf/compiler/java/java_generator.cc13
-rw-r--r--src/google/protobuf/compiler/java/java_helpers.cc33
-rw-r--r--src/google/protobuf/compiler/java/java_helpers.h7
-rw-r--r--src/google/protobuf/compiler/java/java_lazy_message_field.cc5
-rw-r--r--src/google/protobuf/compiler/java/java_map_field_lite.cc26
-rw-r--r--src/google/protobuf/compiler/java/java_message.cc12
-rw-r--r--src/google/protobuf/compiler/java/java_message_builder.cc5
-rw-r--r--src/google/protobuf/compiler/java/java_message_builder_lite.cc8
-rw-r--r--src/google/protobuf/compiler/java/java_message_field.cc23
-rw-r--r--src/google/protobuf/compiler/java/java_message_field_lite.cc23
-rw-r--r--src/google/protobuf/compiler/java/java_message_lite.cc83
-rw-r--r--src/google/protobuf/compiler/java/java_plugin_unittest.cc5
-rw-r--r--src/google/protobuf/compiler/java/java_primitive_field.cc25
-rw-r--r--src/google/protobuf/compiler/java/java_primitive_field_lite.cc14
-rw-r--r--src/google/protobuf/compiler/java/java_shared_code_generator.cc11
-rw-r--r--src/google/protobuf/compiler/java/java_shared_code_generator.h5
-rw-r--r--src/google/protobuf/compiler/java/java_string_field.cc8
-rw-r--r--src/google/protobuf/compiler/java/java_string_field_lite.cc20
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_enum.cc143
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_enum.h87
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_enum_field.cc544
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_enum_field.h126
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_extension.cc150
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_field.cc209
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_field.h130
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_file.cc263
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_file.h94
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_generator.cc230
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_generator.h72
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_helpers.cc591
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_helpers.h199
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_map_field.cc186
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_map_field.h70
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_message.cc676
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_message.h97
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_message_field.cc363
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_message_field.h121
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_params.h258
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_primitive_field.cc968
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_primitive_field.h150
-rw-r--r--src/google/protobuf/compiler/js/embed.cc112
-rw-r--r--[-rwxr-xr-x]src/google/protobuf/compiler/js/js_generator.cc89
-rw-r--r--[-rwxr-xr-x]src/google/protobuf/compiler/js/js_generator.h9
-rw-r--r--src/google/protobuf/compiler/js/well_known_types_embed.cc225
-rw-r--r--src/google/protobuf/compiler/main.cc6
-rw-r--r--src/google/protobuf/compiler/mock_code_generator.cc14
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_field.cc6
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_field.h4
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_file.cc58
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_file.h3
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_generator.cc4
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_helpers.cc15
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_helpers.h4
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_map_field.h2
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_message.cc6
-rw-r--r--src/google/protobuf/compiler/parser.cc78
-rw-r--r--src/google/protobuf/compiler/parser.h14
-rw-r--r--src/google/protobuf/compiler/parser_unittest.cc10
-rw-r--r--src/google/protobuf/compiler/php/php_generator.cc448
-rw-r--r--src/google/protobuf/compiler/php/php_generator.h10
-rw-r--r--src/google/protobuf/compiler/plugin.cc2
-rw-r--r--src/google/protobuf/compiler/plugin.pb.cc221
-rw-r--r--src/google/protobuf/compiler/plugin.pb.h218
-rw-r--r--src/google/protobuf/compiler/python/python_generator.cc87
-rw-r--r--src/google/protobuf/compiler/python/python_generator.h3
-rw-r--r--src/google/protobuf/compiler/python/python_plugin_unittest.cc5
-rw-r--r--src/google/protobuf/compiler/ruby/ruby_generator.cc23
-rw-r--r--src/google/protobuf/descriptor.cc320
-rw-r--r--src/google/protobuf/descriptor.h9
-rw-r--r--src/google/protobuf/descriptor.pb.cc1836
-rw-r--r--src/google/protobuf/descriptor.pb.h1820
-rw-r--r--src/google/protobuf/descriptor.proto11
-rw-r--r--src/google/protobuf/descriptor_database.h42
-rw-r--r--src/google/protobuf/descriptor_database_unittest.cc9
-rw-r--r--src/google/protobuf/descriptor_unittest.cc558
-rw-r--r--src/google/protobuf/drop_unknown_fields_test.cc7
-rw-r--r--src/google/protobuf/duration.pb.cc62
-rw-r--r--src/google/protobuf/duration.pb.h59
-rw-r--r--src/google/protobuf/dynamic_message.cc25
-rw-r--r--src/google/protobuf/dynamic_message.h7
-rw-r--r--src/google/protobuf/dynamic_message_unittest.cc9
-rw-r--r--src/google/protobuf/empty.pb.cc62
-rw-r--r--src/google/protobuf/empty.pb.h59
-rw-r--r--src/google/protobuf/extension_set.cc519
-rw-r--r--src/google/protobuf/extension_set.h139
-rw-r--r--src/google/protobuf/extension_set_heavy.cc146
-rw-r--r--src/google/protobuf/extension_set_unittest.cc41
-rw-r--r--src/google/protobuf/field_mask.pb.cc58
-rw-r--r--src/google/protobuf/field_mask.pb.h55
-rw-r--r--src/google/protobuf/field_mask.proto4
-rw-r--r--src/google/protobuf/generated_enum_util.h4
-rw-r--r--src/google/protobuf/generated_message_reflection.cc67
-rw-r--r--src/google/protobuf/generated_message_reflection.h284
-rw-r--r--src/google/protobuf/generated_message_reflection_unittest.cc11
-rw-r--r--src/google/protobuf/generated_message_table_driven.cc3
-rw-r--r--src/google/protobuf/generated_message_table_driven.h55
-rw-r--r--src/google/protobuf/generated_message_table_driven_lite.cc2
-rw-r--r--src/google/protobuf/generated_message_table_driven_lite.h196
-rw-r--r--src/google/protobuf/generated_message_util.cc91
-rw-r--r--src/google/protobuf/generated_message_util.h87
-rw-r--r--src/google/protobuf/implicit_weak_message.cc18
-rw-r--r--src/google/protobuf/implicit_weak_message.h7
-rw-r--r--src/google/protobuf/inlined_string_field.h271
-rw-r--r--src/google/protobuf/io/coded_stream.cc26
-rw-r--r--src/google/protobuf/io/coded_stream.h23
-rw-r--r--src/google/protobuf/io/coded_stream_unittest.cc5
-rw-r--r--src/google/protobuf/io/gzip_stream.h2
-rw-r--r--src/google/protobuf/io/printer.cc10
-rw-r--r--src/google/protobuf/io/zero_copy_stream_impl.h69
-rw-r--r--src/google/protobuf/io/zero_copy_stream_impl_lite.h48
-rw-r--r--src/google/protobuf/io/zero_copy_stream_unittest.cc5
-rw-r--r--src/google/protobuf/lite_arena_unittest.cc3
-rw-r--r--src/google/protobuf/lite_unittest.cc33
-rw-r--r--src/google/protobuf/map.h9
-rw-r--r--src/google/protobuf/map_entry.h13
-rw-r--r--src/google/protobuf/map_entry_lite.h46
-rw-r--r--src/google/protobuf/map_field.cc49
-rw-r--r--src/google/protobuf/map_field.h76
-rw-r--r--src/google/protobuf/map_field_inl.h10
-rw-r--r--src/google/protobuf/map_field_test.cc23
-rw-r--r--src/google/protobuf/map_test.cc44
-rw-r--r--src/google/protobuf/message.cc6
-rw-r--r--src/google/protobuf/message.h24
-rw-r--r--src/google/protobuf/message_lite.cc6
-rw-r--r--src/google/protobuf/message_lite.h21
-rw-r--r--src/google/protobuf/message_unittest.cc542
-rw-r--r--src/google/protobuf/message_unittest.inc577
-rw-r--r--src/google/protobuf/preserve_unknown_enum_test.cc4
-rw-r--r--src/google/protobuf/proto3_arena_lite_unittest.cc29
-rw-r--r--src/google/protobuf/proto3_arena_unittest.cc5
-rw-r--r--src/google/protobuf/proto3_lite_unittest.cc5
-rw-r--r--[-rwxr-xr-x]src/google/protobuf/reflection.h25
-rw-r--r--src/google/protobuf/reflection_internal.h102
-rw-r--r--src/google/protobuf/reflection_ops.cc4
-rw-r--r--src/google/protobuf/repeated_field.h90
-rw-r--r--src/google/protobuf/repeated_field_reflection_unittest.cc2
-rw-r--r--src/google/protobuf/repeated_field_unittest.cc14
-rw-r--r--src/google/protobuf/source_context.pb.cc61
-rw-r--r--src/google/protobuf/source_context.pb.h55
-rw-r--r--src/google/protobuf/struct.pb.cc147
-rw-r--r--src/google/protobuf/struct.pb.h171
-rw-r--r--src/google/protobuf/stubs/atomic_sequence_num.h54
-rw-r--r--src/google/protobuf/stubs/atomicops.h237
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_arm64_gcc.h325
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_arm_gcc.h151
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_arm_qnx.h146
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h231
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_generic_gcc.h163
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_mips_gcc.h313
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_power.h440
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_ppc_gcc.h155
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_solaris.h188
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_tsan.h219
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_x86_gcc.cc137
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_x86_gcc.h293
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_x86_msvc.cc113
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_x86_msvc.h150
-rw-r--r--src/google/protobuf/stubs/bytestream.h25
-rw-r--r--src/google/protobuf/stubs/callback.h37
-rw-r--r--src/google/protobuf/stubs/casts.h5
-rw-r--r--[-rwxr-xr-x]src/google/protobuf/stubs/common.cc80
-rw-r--r--src/google/protobuf/stubs/common.h12
-rw-r--r--src/google/protobuf/stubs/hash.h5
-rw-r--r--src/google/protobuf/stubs/int128.cc52
-rw-r--r--src/google/protobuf/stubs/io_win32.cc8
-rw-r--r--src/google/protobuf/stubs/io_win32_unittest.cc7
-rw-r--r--src/google/protobuf/stubs/map_util.h3
-rw-r--r--src/google/protobuf/stubs/mathlimits.h2
-rw-r--r--src/google/protobuf/stubs/mutex.h54
-rw-r--r--src/google/protobuf/stubs/once.cc99
-rw-r--r--src/google/protobuf/stubs/once.h71
-rw-r--r--src/google/protobuf/stubs/once_unittest.cc254
-rw-r--r--src/google/protobuf/stubs/platform_macros.h8
-rw-r--r--src/google/protobuf/stubs/port.h47
-rw-r--r--src/google/protobuf/stubs/scoped_ptr.h236
-rw-r--r--src/google/protobuf/stubs/shared_ptr.h471
-rw-r--r--src/google/protobuf/stubs/singleton.h1
-rw-r--r--src/google/protobuf/stubs/strutil.cc8
-rw-r--r--src/google/protobuf/stubs/type_traits.h364
-rw-r--r--src/google/protobuf/stubs/type_traits_unittest.cc631
-rw-r--r--src/google/protobuf/test_util.cc3303
-rw-r--r--src/google/protobuf/test_util.h1410
-rw-r--r--src/google/protobuf/test_util.inc2600
-rw-r--r--src/google/protobuf/text_format.cc222
-rw-r--r--src/google/protobuf/text_format.h92
-rw-r--r--src/google/protobuf/text_format_unittest.cc231
-rw-r--r--src/google/protobuf/timestamp.pb.cc62
-rw-r--r--src/google/protobuf/timestamp.pb.h59
-rw-r--r--src/google/protobuf/type.pb.cc303
-rw-r--r--src/google/protobuf/type.pb.h281
-rw-r--r--src/google/protobuf/unittest.proto58
-rw-r--r--src/google/protobuf/unittest_lite.proto19
-rw-r--r--src/google/protobuf/unknown_field_set_unittest.cc1
-rw-r--r--src/google/protobuf/util/field_comparator.h6
-rw-r--r--src/google/protobuf/util/field_mask_util.cc27
-rw-r--r--src/google/protobuf/util/field_mask_util.h4
-rw-r--r--src/google/protobuf/util/field_mask_util_test.cc13
-rw-r--r--src/google/protobuf/util/internal/datapiece.cc27
-rw-r--r--src/google/protobuf/util/internal/datapiece.h3
-rw-r--r--src/google/protobuf/util/internal/default_value_objectwriter.cc115
-rw-r--r--src/google/protobuf/util/internal/default_value_objectwriter.h57
-rw-r--r--src/google/protobuf/util/internal/default_value_objectwriter_test.cc4
-rw-r--r--src/google/protobuf/util/internal/error_listener.h15
-rw-r--r--src/google/protobuf/util/internal/field_mask_utility.cc3
-rw-r--r--src/google/protobuf/util/internal/json_objectwriter.h41
-rw-r--r--src/google/protobuf/util/internal/json_objectwriter_test.cc2
-rw-r--r--src/google/protobuf/util/internal/json_stream_parser.cc5
-rw-r--r--src/google/protobuf/util/internal/object_location_tracker.h4
-rw-r--r--src/google/protobuf/util/internal/proto_writer.cc70
-rw-r--r--src/google/protobuf/util/internal/proto_writer.h56
-rw-r--r--src/google/protobuf/util/internal/protostream_objectsource.cc76
-rw-r--r--src/google/protobuf/util/internal/protostream_objectsource.h4
-rw-r--r--src/google/protobuf/util/internal/protostream_objectsource_test.cc105
-rw-r--r--src/google/protobuf/util/internal/protostream_objectwriter.cc80
-rw-r--r--src/google/protobuf/util/internal/protostream_objectwriter.h24
-rw-r--r--src/google/protobuf/util/internal/protostream_objectwriter_test.cc24
-rw-r--r--src/google/protobuf/util/internal/structured_objectwriter.h9
-rw-r--r--src/google/protobuf/util/internal/testdata/books.proto4
-rw-r--r--src/google/protobuf/util/internal/testdata/maps.proto3
-rw-r--r--src/google/protobuf/util/internal/type_info.cc14
-rw-r--r--src/google/protobuf/util/internal/type_info_test_helper.cc3
-rw-r--r--src/google/protobuf/util/internal/type_info_test_helper.h7
-rw-r--r--src/google/protobuf/util/internal/utility.cc48
-rw-r--r--src/google/protobuf/util/internal/utility.h22
-rw-r--r--src/google/protobuf/util/json_format_proto3.proto6
-rw-r--r--src/google/protobuf/util/json_util.cc20
-rw-r--r--src/google/protobuf/util/json_util.h2
-rw-r--r--src/google/protobuf/util/json_util_test.cc112
-rw-r--r--src/google/protobuf/util/message_differencer.cc33
-rw-r--r--src/google/protobuf/util/message_differencer.h31
-rw-r--r--[-rwxr-xr-x]src/google/protobuf/util/message_differencer_unittest.cc21
-rw-r--r--src/google/protobuf/util/package_info.h2
-rw-r--r--src/google/protobuf/util/time_util.cc5
-rw-r--r--src/google/protobuf/util/type_resolver_util.cc12
-rw-r--r--src/google/protobuf/util/type_resolver_util_test.cc26
-rw-r--r--src/google/protobuf/wire_format.cc9
-rw-r--r--src/google/protobuf/wire_format.h8
-rw-r--r--src/google/protobuf/wire_format_lite.h49
-rw-r--r--src/google/protobuf/wire_format_lite_inl.h86
-rw-r--r--src/google/protobuf/wrappers.pb.cc404
-rw-r--r--src/google/protobuf/wrappers.pb.h419
-rwxr-xr-xtests.sh29
m---------third_party/googletest0
-rwxr-xr-xupdate_file_lists.sh22
772 files changed, 30074 insertions, 41489 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 af88e226..db8a893a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -19,7 +19,7 @@ m4/lt~obsolete.m4
autom4te.cache
# downloaded files
-gmock
+/gmock
# in-tree configure-generated files
Makefile
@@ -47,7 +47,6 @@ any_test.pb.*
map*unittest.pb.*
unittest*.pb.*
cpp_test*.pb.*
-src/google/protobuf/compiler/js/well_known_types_embed.cc
src/google/protobuf/util/**/*.pb.cc
src/google/protobuf/util/**/*.pb.h
@@ -58,8 +57,6 @@ python/*.egg
python/.eggs/
python/.tox
python/build/
-python/google/protobuf/compiler/
-python/google/protobuf/util/
src/js_embed
src/protoc
@@ -176,7 +173,16 @@ js/testproto_libs2.js
ruby/lib/
ruby/tests/generated_code_pb.rb
ruby/tests/test_import_pb.rb
+ruby/tests/test_ruby_package_pb.rb
ruby/Gemfile.lock
ruby/compatibility_tests/v3.0.0/protoc
ruby/compatibility_tests/v3.0.0/tests/generated_code_pb.rb
ruby/compatibility_tests/v3.0.0/tests/test_import_pb.rb
+
+# IntelliJ CLion Config files and build output
+cmake/.idea
+cmake/cmake-build-debug/
+
+# Common build subdirectories.
+./.build/
+./_build/
diff --git a/.gitmodules b/.gitmodules
index 55a47cea..bcd125a4 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -1,3 +1,7 @@
[submodule "third_party/benchmark"]
path = third_party/benchmark
url = https://github.com/google/benchmark.git
+[submodule "third_party/googletest"]
+ path = third_party/googletest
+ url = https://github.com/google/googletest.git
+ ignore = dirty
diff --git a/.travis.yml b/.travis.yml
index 99981466..74d4ea7b 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -14,21 +14,21 @@ matrix:
- os: osx
env: CONFIG=objectivec_osx
- osx_image: xcode9.1
+ 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.1
+ osx_image: xcode9.3
language: objective-c
- os: osx
env: CONFIG=objectivec_ios_release
- osx_image: xcode9.1
+ osx_image: xcode9.3
language: objective-c
- os: osx
env: CONFIG=objectivec_cocoapods_integration
- osx_image: xcode9.1
+ osx_image: xcode9.3
language: objective-c
# -----------------------------------------------------------------
diff --git a/BUILD b/BUILD
index b786ff64..ce3bd034 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"])
@@ -19,35 +19,42 @@ config_setting(
# Protobuf Runtime Library
################################################################################
-WIN_COPTS = [
+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({
- ":windows" : WIN_COPTS,
- ":windows_msvc" : WIN_COPTS,
+ ":msvc" : MSVC_COPTS,
"//conditions:default": [
"-DHAVE_PTHREAD",
"-Wall",
- "-Wwrite-strings",
"-Woverloaded-virtual",
"-Wno-sign-compare",
"-Wno-unused-function",
# Prevents ISO C++ const string assignment warnings for pyext sources.
"-Wno-writable-strings",
+ "-Wno-write-strings",
],
})
config_setting(
- name = "windows",
- values = { "cpu": "x64_windows" },
-)
-
-config_setting(
- name = "windows_msvc",
- values = { "cpu": "x64_windows_msvc" },
+ name = "msvc",
+ values = { "compiler": "msvc-cl" },
)
config_setting(
@@ -57,11 +64,13 @@ config_setting(
},
)
-# Android and Windows builds do not need to link in a separate pthread library.
+# Android and MSVC builds do not need to link in a separate pthread library.
LINK_OPTS = select({
":android": [],
- ":windows": [],
- ":windows_msvc": [],
+ ":msvc": [
+ # Suppress linker warnings about files with no symbols defined.
+ "-ignore:4221",
+ ],
"//conditions:default": ["-lpthread", "-lm"],
})
@@ -89,13 +98,10 @@ cc_library(
"src/google/protobuf/io/zero_copy_stream_impl_lite.cc",
"src/google/protobuf/message_lite.cc",
"src/google/protobuf/repeated_field.cc",
- "src/google/protobuf/stubs/atomicops_internals_x86_gcc.cc",
- "src/google/protobuf/stubs/atomicops_internals_x86_msvc.cc",
"src/google/protobuf/stubs/bytestream.cc",
"src/google/protobuf/stubs/common.cc",
"src/google/protobuf/stubs/int128.cc",
"src/google/protobuf/stubs/io_win32.cc",
- "src/google/protobuf/stubs/once.cc",
"src/google/protobuf/stubs/status.cc",
"src/google/protobuf/stubs/statusor.cc",
"src/google/protobuf/stubs/stringpiece.cc",
@@ -253,7 +259,7 @@ internal_copied_filegroup(
srcs = WELL_KNOWN_PROTOS,
dest = "",
strip_prefix = "src",
- visibility = ["//visibility:hidden"],
+ visibility = ["//visibility:private"],
)
[proto_library(
@@ -267,24 +273,6 @@ internal_copied_filegroup(
# Protocol Buffers Compiler
################################################################################
-cc_binary(
- name = "js_embed",
- srcs = ["src/google/protobuf/compiler/js/embed.cc"],
- visibility = ["//visibility:public"],
-)
-
-genrule(
- name = "generate_js_well_known_types_embed",
- srcs = [
- "src/google/protobuf/compiler/js/well_known_types/any.js",
- "src/google/protobuf/compiler/js/well_known_types/struct.js",
- "src/google/protobuf/compiler/js/well_known_types/timestamp.js",
- ],
- outs = ["src/google/protobuf/compiler/js/well_known_types_embed.cc"],
- cmd = "$(location :js_embed) $(SRCS) > $@",
- tools = [":js_embed"],
-)
-
cc_library(
name = "protoc_lib",
srcs = [
@@ -351,17 +339,6 @@ cc_library(
"src/google/protobuf/compiler/java/java_shared_code_generator.cc",
"src/google/protobuf/compiler/java/java_string_field.cc",
"src/google/protobuf/compiler/java/java_string_field_lite.cc",
- "src/google/protobuf/compiler/javanano/javanano_enum.cc",
- "src/google/protobuf/compiler/javanano/javanano_enum_field.cc",
- "src/google/protobuf/compiler/javanano/javanano_extension.cc",
- "src/google/protobuf/compiler/javanano/javanano_field.cc",
- "src/google/protobuf/compiler/javanano/javanano_file.cc",
- "src/google/protobuf/compiler/javanano/javanano_generator.cc",
- "src/google/protobuf/compiler/javanano/javanano_helpers.cc",
- "src/google/protobuf/compiler/javanano/javanano_map_field.cc",
- "src/google/protobuf/compiler/javanano/javanano_message.cc",
- "src/google/protobuf/compiler/javanano/javanano_message_field.cc",
- "src/google/protobuf/compiler/javanano/javanano_primitive_field.cc",
"src/google/protobuf/compiler/js/js_generator.cc",
"src/google/protobuf/compiler/js/well_known_types_embed.cc",
"src/google/protobuf/compiler/objectivec/objectivec_enum.cc",
@@ -386,7 +363,25 @@ cc_library(
],
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"],
)
@@ -478,6 +473,7 @@ COMMON_TEST_SRCS = [
"src/google/protobuf/arena_test_util.cc",
"src/google/protobuf/map_test_util.cc",
"src/google/protobuf/test_util.cc",
+ "src/google/protobuf/test_util.inc",
"src/google/protobuf/testing/file.cc",
"src/google/protobuf/testing/googletest.cc",
]
@@ -520,6 +516,7 @@ cc_test(
"src/google/protobuf/compiler/cpp/cpp_move_unittest.cc",
"src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc",
"src/google/protobuf/compiler/cpp/cpp_unittest.cc",
+ "src/google/protobuf/compiler/cpp/cpp_unittest.inc",
"src/google/protobuf/compiler/cpp/metadata_test.cc",
"src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc",
"src/google/protobuf/compiler/csharp/csharp_generator_unittest.cc",
@@ -544,6 +541,7 @@ cc_test(
"src/google/protobuf/map_field_test.cc",
"src/google/protobuf/map_test.cc",
"src/google/protobuf/message_unittest.cc",
+ "src/google/protobuf/message_unittest.inc",
"src/google/protobuf/no_field_presence_test.cc",
"src/google/protobuf/preserve_unknown_enum_test.cc",
"src/google/protobuf/proto3_arena_lite_unittest.cc",
@@ -556,7 +554,6 @@ cc_test(
"src/google/protobuf/stubs/common_unittest.cc",
"src/google/protobuf/stubs/int128_unittest.cc",
"src/google/protobuf/stubs/io_win32_unittest.cc",
- "src/google/protobuf/stubs/once_unittest.cc",
"src/google/protobuf/stubs/status_test.cc",
"src/google/protobuf/stubs/statusor_test.cc",
"src/google/protobuf/stubs/stringpiece_unittest.cc",
@@ -565,7 +562,6 @@ cc_test(
"src/google/protobuf/stubs/strutil_unittest.cc",
"src/google/protobuf/stubs/template_util_unittest.cc",
"src/google/protobuf/stubs/time_test.cc",
- "src/google/protobuf/stubs/type_traits_unittest.cc",
"src/google/protobuf/text_format_unittest.cc",
"src/google/protobuf/unknown_field_set_unittest.cc",
"src/google/protobuf/util/delimited_message_util_test.cc",
@@ -648,6 +644,7 @@ py_library(
name = "python_srcs",
srcs = glob(
[
+ "python/google/__init__.py",
"python/google/protobuf/*.py",
"python/google/protobuf/**/*.py",
],
@@ -696,6 +693,7 @@ cc_binary(
linkstatic = 1,
deps = [
":protobuf",
+ ":proto_api",
] + select({
"//conditions:default": [],
":use_fast_cpp_protos": ["//external:python_headers"],
@@ -838,11 +836,21 @@ 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)",
runtime = ":protobuf",
visibility = ["//visibility:public"],
+ blacklisted_protos = [":_internal_wkt_protos_genrule"],
)
proto_lang_toolchain(
diff --git a/CHANGES.txt b/CHANGES.txt
index c7c42916..c18c6377 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,3 +1,91 @@
+2018-06-01 version 3.6.0 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
+
+ C++
+ * Starting from this release, we now require C++11. For those we cannot yet
+ upgrade to C++11, we will try to keep the 3.5.x branch updated with
+ critical bug fixes only. If you have any concerns about this, please
+ comment on issue #2780.
+ * Moved to C++11 types like std::atomic and std::unique_ptr and away from our
+ old custom-built equivalents.
+ * Added support for repeated message fields in lite protos using implicit
+ weak fields. This is an experimental feature that allows the linker to
+ strip out more unused messages than previously was possible.
+ * Fixed SourceCodeInfo for interpreted options and extension range options.
+ * Fixed always_print_enums_as_ints option for JSON serialization.
+ * Added support for ignoring unknown enum values when parsing JSON.
+ * Create std::string in Arena memory.
+ * Fixed ValidateDateTime to correctly check the day.
+ * Fixed bug in ZeroCopyStreamByteSink.
+ * Various other cleanups and fixes.
+
+ Java
+ * Dropped support for Java 6.
+ * Added a UTF-8 decoder that uses Unsafe to directly decode a byte buffer.
+ * Added deprecation annotations to generated code for deprecated oneof
+ fields.
+ * Fixed map field serialization in DynamicMessage.
+ * Cleanup and documentation for Java Lite runtime.
+ * Various other fixes and cleanups
+ * Fixed unboxed arraylists to handle an edge case
+ * Improved performance for copying between unboxed arraylists
+ * Fixed lite protobuf to avoid Java compiler warnings
+ * Improved test coverage for lite runtime
+ * Performance improvements for lite runtime
+
+ Python
+ * Fixed bytes/string map key incompatibility between C++ and pure-Python
+ implementations (issue #4029)
+ * Added __init__.py files to compiler and util subpackages
+ * Use /MT for all Windows versions
+ * Fixed an issue affecting the Python-C++ implementation when used with
+ Cython (issue #2896)
+ * Various text format fixes
+ * Various fixes to resolve behavior differences between the pure-Python and
+ Python-C++ implementations
+
+ PHP
+ * Added php_metadata_namespace to control the file path of generated metadata
+ file.
+ * Changed generated classes of nested message/enum. E.g., Foo.Bar, which
+ previously generates Foo_Bar, now generates Foo/Bar
+ * Added array constructor. When creating a message, users can pass a php
+ array whose content is field name to value pairs into constructor. The
+ created message will be initialized according to the array. Note that
+ message field should use a message value instead of a sub-array.
+ * Various bug fixes.
+
+ Objective-C
+ * We removed some helper class methods from GPBDictionary to shrink the size
+ of the library, the functionary is still there, but you may need to do some
+ specific +alloc / -init… methods instead.
+ * Minor improvements in the performance of object field getters/setters by
+ avoiding some memory management overhead.
+ * Fix a memory leak during the raising of some errors.
+ * Make header importing completely order independent.
+ * Small code improvements for things the undefined behaviors compiler option
+ was flagging.
+
+ Ruby
+ * Added ruby_package file option to control the module of generated class.
+ * Various bug fixes.
+
+ Javascript
+ * Allow setting string to int64 field.
+
+ Csharp
+ * Unknown fields are now parsed and then sent back on the wire. They can be
+ discarded at parse time via a CodedInputStream option.
+ * Movement towards working with .NET 3.5 and Unity
+ * Expression trees are no longer used
+ * AOT generics issues in Unity/il2cpp have a workaround (see this commit for
+ details)
+ * Floating point values are now compared bitwise (affects NaN value
+ comparisons)
+ * The default size limit when parsing is now 2GB rather than 64MB
+ * MessageParser now supports parsing from a slice of a byte array
+ * JSON list parsing now accepts null values where the underlying proto
+ representation does
+
2017-12-20 version 3.5.1 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
Planned Future Changes
* Make C++ implementation C++11 only: we plan to require C++11 to build
diff --git a/LICENSE b/LICENSE
index f028c823..19b305b0 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,14 +1,4 @@
-This license applies to all parts of Protocol Buffers except the following:
-
- - Atomicops support for generic gcc, located in
- src/google/protobuf/stubs/atomicops_internals_generic_gcc.h.
- This file is copyrighted by Red Hat Inc.
-
- - Atomicops support for AIX/POWER, located in
- src/google/protobuf/stubs/atomicops_internals_power.h.
- This file is copyrighted by Bloomberg Finance LP.
-
-Copyright 2014, Google Inc. All rights reserved.
+Copyright 2008 Google Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
diff --git a/Makefile.am b/Makefile.am
index d392429f..24f520c6 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -8,8 +8,8 @@ AUTOMAKE_OPTIONS = foreign
# the right time.
SUBDIRS = . src
-# Always include gmock in distributions.
-DIST_SUBDIRS = $(subdirs) src conformance benchmarks
+# Always include third_party directories in distributions.
+DIST_SUBDIRS = src conformance benchmarks third_party/googletest
# Build gmock before we build protobuf tests. We don't add gmock to SUBDIRS
# because then "make check" would also build and run all of gmock's own tests,
@@ -18,8 +18,8 @@ DIST_SUBDIRS = $(subdirs) src conformance benchmarks
# the installed version of gmock if there is one.
check-local:
@echo "Making lib/libgmock.a lib/libgmock_main.a in gmock"
- @cd gmock && $(MAKE) $(AM_MAKEFLAGS) lib/libgmock.la lib/libgmock_main.la
- @cd gmock/gtest && $(MAKE) $(AM_MAKEFLAGS) lib/libgtest.la lib/libgtest_main.la
+ @cd third_party/googletest/googletest && $(MAKE) $(AM_MAKEFLAGS) lib/libgtest.la lib/libgtest_main.la
+ @cd third_party/googletest/googlemock && $(MAKE) $(AM_MAKEFLAGS) lib/libgmock.la lib/libgmock_main.la
# We would like to clean gmock when "make clean" is invoked. But we have to
# be careful because clean-local is also invoked during "make distclean", but
@@ -28,9 +28,9 @@ check-local:
# cd to the directory again and "make clean" it will fail. So, check that the
# Makefile exists before recursing.
clean-local:
- @if test -e gmock/Makefile; then \
- echo "Making clean in gmock"; \
- cd gmock && $(MAKE) $(AM_MAKEFLAGS) clean; \
+ @if test -e third_party/googletest/Makefile; then \
+ echo "Making clean in googletest"; \
+ cd third_party/googletest && $(MAKE) $(AM_MAKEFLAGS) clean; \
fi; \
if test -e conformance/Makefile; then \
echo "Making clean in conformance"; \
@@ -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 \
@@ -98,7 +99,6 @@ csharp_EXTRA_DIST= \
csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs \
csharp/src/Google.Protobuf.Test/JsonParserTest.cs \
csharp/src/Google.Protobuf.Test/JsonTokenizerTest.cs \
- csharp/src/Google.Protobuf.Test/Program.cs \
csharp/src/Google.Protobuf.Test/Reflection/CustomOptionsTest.cs \
csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs \
csharp/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs \
@@ -133,6 +133,7 @@ csharp_EXTRA_DIST= \
csharp/src/Google.Protobuf/Collections/ProtobufEqualityComparers.cs \
csharp/src/Google.Protobuf/Collections/ReadOnlyDictionary.cs \
csharp/src/Google.Protobuf/Collections/RepeatedField.cs \
+ csharp/src/Google.Protobuf/Compatibility/MethodInfoExtensions.cs \
csharp/src/Google.Protobuf/Compatibility/PropertyInfoExtensions.cs \
csharp/src/Google.Protobuf/Compatibility/StreamExtensions.cs \
csharp/src/Google.Protobuf/Compatibility/TypeExtensions.cs \
@@ -354,6 +355,7 @@ java_EXTRA_DIST=
java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto \
java/core/src/test/proto/com/google/protobuf/map_for_proto2_test.proto \
java/core/src/test/proto/com/google/protobuf/map_initialization_order_test.proto \
+ java/core/src/test/proto/com/google/protobuf/map_lite_test.proto \
java/core/src/test/proto/com/google/protobuf/map_test.proto \
java/core/src/test/proto/com/google/protobuf/multiple_files_test.proto \
java/core/src/test/proto/com/google/protobuf/nested_builders_test.proto \
@@ -369,9 +371,7 @@ java_EXTRA_DIST=
java/core/src/test/proto/com/google/protobuf/test_check_utf8_size.proto \
java/core/src/test/proto/com/google/protobuf/test_custom_options.proto \
java/core/src/test/proto/com/google/protobuf/test_extra_interfaces.proto \
- java/lite/generate-sources-build.xml \
- java/lite/generate-test-sources-build.xml \
- java/lite/pom.xml \
+ java/lite.md \
java/pom.xml \
java/util/pom.xml \
java/util/src/main/java/com/google/protobuf/util/Durations.java \
@@ -386,45 +386,6 @@ java_EXTRA_DIST=
java/util/src/test/java/com/google/protobuf/util/TimeUtilTest.java \
java/util/src/test/proto/com/google/protobuf/util/json_test.proto
-javanano_EXTRA_DIST= \
- javanano/src/main/java/com/google/protobuf/nano/CodedOutputByteBufferNano.java \
- javanano/src/main/java/com/google/protobuf/nano/FieldData.java \
- javanano/src/main/java/com/google/protobuf/nano/FieldArray.java \
- javanano/src/main/java/com/google/protobuf/nano/WireFormatNano.java \
- javanano/src/main/java/com/google/protobuf/nano/Extension.java \
- javanano/src/main/java/com/google/protobuf/nano/CodedInputByteBufferNano.java \
- javanano/src/main/java/com/google/protobuf/nano/UnknownFieldData.java \
- javanano/src/main/java/com/google/protobuf/nano/MessageNano.java \
- javanano/src/main/java/com/google/protobuf/nano/InternalNano.java \
- javanano/src/main/java/com/google/protobuf/nano/InvalidProtocolBufferNanoException.java \
- javanano/src/main/java/com/google/protobuf/nano/MapFactories.java \
- javanano/src/main/java/com/google/protobuf/nano/ExtendableMessageNano.java \
- javanano/src/main/java/com/google/protobuf/nano/MessageNanoPrinter.java \
- javanano/src/test/java/com/google/protobuf/nano/unittest_accessors_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_reference_types_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_extension_repeated_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_has_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nameclash_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_single_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/NanoTest.java \
- javanano/src/test/java/com/google/protobuf/nano/unittest_simple_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_import_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_merge_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_extension_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_packables_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_extension_singular_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_recursive_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_extension_packed_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_enum_validity_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_stringutf8_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_multiple_nano.proto \
- javanano/src/test/java/com/google/protobuf/nano/map_test.proto \
- javanano/README.md \
- javanano/pom.xml
-
objectivec_EXTRA_DIST= \
objectivec/DevTools/check_version_stamps.sh \
objectivec/DevTools/compile_testing_protos.sh \
@@ -497,11 +458,13 @@ objectivec_EXTRA_DIST= \
objectivec/GPBWireFormat.m \
objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj \
objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata \
+ objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist \
objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings \
objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme \
objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme \
objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj \
objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/contents.xcworkspacedata \
+ objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist \
objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings \
objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme \
objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme \
@@ -539,6 +502,31 @@ objectivec_EXTRA_DIST= \
objectivec/Tests/GPBArrayTests.m \
objectivec/Tests/GPBCodedInputStreamTests.m \
objectivec/Tests/GPBCodedOuputStreamTests.m \
+ objectivec/Tests/GPBCompileTest01.m \
+ objectivec/Tests/GPBCompileTest02.m \
+ objectivec/Tests/GPBCompileTest03.m \
+ objectivec/Tests/GPBCompileTest04.m \
+ objectivec/Tests/GPBCompileTest05.m \
+ objectivec/Tests/GPBCompileTest06.m \
+ objectivec/Tests/GPBCompileTest07.m \
+ objectivec/Tests/GPBCompileTest08.m \
+ objectivec/Tests/GPBCompileTest09.m \
+ objectivec/Tests/GPBCompileTest10.m \
+ objectivec/Tests/GPBCompileTest11.m \
+ objectivec/Tests/GPBCompileTest12.m \
+ objectivec/Tests/GPBCompileTest13.m \
+ objectivec/Tests/GPBCompileTest14.m \
+ objectivec/Tests/GPBCompileTest15.m \
+ objectivec/Tests/GPBCompileTest16.m \
+ objectivec/Tests/GPBCompileTest17.m \
+ objectivec/Tests/GPBCompileTest18.m \
+ objectivec/Tests/GPBCompileTest19.m \
+ objectivec/Tests/GPBCompileTest20.m \
+ objectivec/Tests/GPBCompileTest21.m \
+ objectivec/Tests/GPBCompileTest22.m \
+ objectivec/Tests/GPBCompileTest23.m \
+ objectivec/Tests/GPBCompileTest24.m \
+ objectivec/Tests/GPBCompileTest25.m \
objectivec/Tests/GPBConcurrencyTests.m \
objectivec/Tests/GPBDescriptorTests.m \
objectivec/Tests/GPBDictionaryTests+Bool.m \
@@ -565,25 +553,6 @@ objectivec_EXTRA_DIST= \
objectivec/Tests/GPBUtilitiesTests.m \
objectivec/Tests/GPBWellKnownTypesTest.m \
objectivec/Tests/GPBWireFormatTests.m \
- objectivec/Tests/iOSTestHarness/AppDelegate.m \
- objectivec/Tests/iOSTestHarness/en.lproj/InfoPlist.strings \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_20.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_29.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_40.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_58.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_60.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_76.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_80.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_87.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_120.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_152.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_167.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_180.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_1024.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/Contents.json \
- objectivec/Tests/iOSTestHarness/Images.xcassets/LaunchImage.launchimage/Contents.json \
- objectivec/Tests/iOSTestHarness/Info.plist \
- objectivec/Tests/iOSTestHarness/LaunchScreen.xib \
objectivec/Tests/text_format_map_unittest_data.txt \
objectivec/Tests/text_format_unittest_data.txt \
objectivec/Tests/unittest_cycle.proto \
@@ -651,7 +620,9 @@ php_EXTRA_DIST= \
php/src/Google/Protobuf/Field.php \
php/src/Google/Protobuf/FieldDescriptor.php \
php/src/Google/Protobuf/FieldMask.php \
+ php/src/Google/Protobuf/Field/Cardinality.php \
php/src/Google/Protobuf/Field_Cardinality.php \
+ php/src/Google/Protobuf/Field/Kind.php \
php/src/Google/Protobuf/Field_Kind.php \
php/src/Google/Protobuf/FloatValue.php \
php/src/Google/Protobuf/GPBEmpty.php \
@@ -662,30 +633,29 @@ php_EXTRA_DIST= \
php/src/Google/Protobuf/Internal/Descriptor.php \
php/src/Google/Protobuf/Internal/DescriptorPool.php \
php/src/Google/Protobuf/Internal/DescriptorProto.php \
- php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php \
- php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php \
+ php/src/Google/Protobuf/Internal/DescriptorProto/ExtensionRange.php \
+ php/src/Google/Protobuf/Internal/DescriptorProto/ReservedRange.php \
php/src/Google/Protobuf/Internal/EnumBuilderContext.php \
php/src/Google/Protobuf/Internal/EnumDescriptor.php \
php/src/Google/Protobuf/Internal/EnumDescriptorProto.php \
- php/src/Google/Protobuf/Internal/EnumDescriptorProto_EnumReservedRange.php \
+ php/src/Google/Protobuf/Internal/EnumDescriptorProto/EnumReservedRange.php \
php/src/Google/Protobuf/Internal/EnumOptions.php \
php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php \
php/src/Google/Protobuf/Internal/EnumValueOptions.php \
php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php \
- php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php \
php/src/Google/Protobuf/Internal/FieldDescriptorProto.php \
php/src/Google/Protobuf/Internal/FieldDescriptor.php \
php/src/Google/Protobuf/Internal/FieldDescriptorProto.php \
- php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php \
- php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php \
+ php/src/Google/Protobuf/Internal/FieldDescriptorProto/Label.php \
+ php/src/Google/Protobuf/Internal/FieldDescriptorProto/Type.php \
php/src/Google/Protobuf/Internal/FieldOptions.php \
- php/src/Google/Protobuf/Internal/FieldOptions_CType.php \
- php/src/Google/Protobuf/Internal/FieldOptions_JSType.php \
+ php/src/Google/Protobuf/Internal/FieldOptions/CType.php \
+ php/src/Google/Protobuf/Internal/FieldOptions/JSType.php \
php/src/Google/Protobuf/Internal/FileDescriptor.php \
php/src/Google/Protobuf/Internal/FileDescriptorProto.php \
php/src/Google/Protobuf/Internal/FileDescriptorSet.php \
php/src/Google/Protobuf/Internal/FileOptions.php \
- php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php \
+ php/src/Google/Protobuf/Internal/FileOptions/OptimizeMode.php \
php/src/Google/Protobuf/Internal/GPBDecodeException.php \
php/src/Google/Protobuf/Internal/GPBJsonWire.php \
php/src/Google/Protobuf/Internal/GPBLabel.php \
@@ -694,7 +664,7 @@ php_EXTRA_DIST= \
php/src/Google/Protobuf/Internal/GPBWire.php \
php/src/Google/Protobuf/Internal/GPBWireType.php \
php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php \
- php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php \
+ php/src/Google/Protobuf/Internal/GeneratedCodeInfo/Annotation.php \
php/src/Google/Protobuf/Internal/GetPublicDescriptorTrait.php \
php/src/Google/Protobuf/Internal/HasPublicDescriptorTrait.php \
php/src/Google/Protobuf/Internal/MapEntry.php \
@@ -705,7 +675,7 @@ php_EXTRA_DIST= \
php/src/Google/Protobuf/Internal/MessageOptions.php \
php/src/Google/Protobuf/Internal/MethodDescriptorProto.php \
php/src/Google/Protobuf/Internal/MethodOptions.php \
- php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php \
+ php/src/Google/Protobuf/Internal/MethodOptions/IdempotencyLevel.php \
php/src/Google/Protobuf/Internal/OneofDescriptor.php \
php/src/Google/Protobuf/Internal/OneofDescriptorProto.php \
php/src/Google/Protobuf/Internal/OneofField.php \
@@ -716,9 +686,9 @@ php_EXTRA_DIST= \
php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php \
php/src/Google/Protobuf/Internal/ServiceOptions.php \
php/src/Google/Protobuf/Internal/SourceCodeInfo.php \
- php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php \
+ php/src/Google/Protobuf/Internal/SourceCodeInfo/Location.php \
php/src/Google/Protobuf/Internal/UninterpretedOption.php \
- php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.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 \
@@ -748,6 +718,7 @@ php_EXTRA_DIST= \
php/tests/map_field_test.php \
php/tests/memory_leak_test.php \
php/tests/php_implementation_test.php \
+ php/tests/proto/empty/echo.proto \
php/tests/proto/test.proto \
php/tests/proto/test_descriptors.proto \
php/tests/proto/test_empty_php_namespace.proto \
@@ -774,6 +745,7 @@ python_EXTRA_DIST= \
python/MANIFEST.in \
python/google/__init__.py \
python/google/protobuf/__init__.py \
+ python/google/protobuf/compiler/__init__.py \
python/google/protobuf/descriptor.py \
python/google/protobuf/descriptor_database.py \
python/google/protobuf/descriptor_pool.py \
@@ -808,6 +780,7 @@ python_EXTRA_DIST= \
python/google/protobuf/internal/more_extensions.proto \
python/google/protobuf/internal/more_extensions_dynamic.proto \
python/google/protobuf/internal/more_messages.proto \
+ python/google/protobuf/internal/no_package.proto \
python/google/protobuf/internal/packed_field_test.proto \
python/google/protobuf/internal/proto_builder_test.py \
python/google/protobuf/internal/python_message.py \
@@ -832,6 +805,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 \
@@ -861,12 +835,14 @@ python_EXTRA_DIST= \
python/google/protobuf/pyext/repeated_scalar_container.h \
python/google/protobuf/pyext/safe_numerics.h \
python/google/protobuf/pyext/scoped_pyobject_ptr.h \
+ python/google/protobuf/pyext/thread_unsafe_shared_ptr.h \
python/google/protobuf/reflection.py \
python/google/protobuf/service.py \
python/google/protobuf/service_reflection.py \
python/google/protobuf/symbol_database.py \
python/google/protobuf/text_encoding.py \
python/google/protobuf/text_format.py \
+ python/google/protobuf/util/__init__.py \
python/release.sh \
python/mox.py \
python/setup.cfg \
@@ -932,6 +908,7 @@ ruby_EXTRA_DIST= \
ruby/tests/stress.rb \
ruby/tests/generated_code.proto \
ruby/tests/test_import.proto \
+ ruby/tests/test_ruby_package.proto \
ruby/tests/generated_code_test.rb \
ruby/tests/well_known_types_test.rb \
ruby/travis-test.sh
@@ -958,6 +935,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 \
@@ -1029,11 +1007,13 @@ 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
-all_EXTRA_DIST=$(csharp_EXTRA_DIST) $(java_EXTRA_DIST) $(javanano_EXTRA_DIST) $(objectivec_EXTRA_DIST) $(php_EXTRA_DIST) $(python_EXTRA_DIST) $(ruby_EXTRA_DIST) $(js_EXTRA_DIST)
+all_EXTRA_DIST=$(csharp_EXTRA_DIST) $(java_EXTRA_DIST) $(objectivec_EXTRA_DIST) $(php_EXTRA_DIST) $(python_EXTRA_DIST) $(ruby_EXTRA_DIST) $(js_EXTRA_DIST)
EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \
autogen.sh \
@@ -1044,7 +1024,6 @@ EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \
CHANGES.txt \
update_file_lists.sh \
BUILD \
- gmock.BUILD \
WORKSPACE \
cmake/CMakeLists.txt \
cmake/README.md \
@@ -1062,6 +1041,7 @@ EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \
cmake/protobuf.pc.cmake \
cmake/protoc.cmake \
cmake/tests.cmake \
+ cmake/version.rc.in \
editors/README.txt \
editors/proto.vim \
editors/protobuf-mode.el \
diff --git a/Protobuf.podspec b/Protobuf.podspec
index 84a37996..b5bb673e 100644
--- a/Protobuf.podspec
+++ b/Protobuf.podspec
@@ -5,7 +5,7 @@
# dependent projects use the :git notation to refer to the library.
Pod::Spec.new do |s|
s.name = 'Protobuf'
- s.version = '3.5.1'
+ s.version = '3.6.0'
s.summary = 'Protocol Buffers v.3 runtime library for Objective-C.'
s.homepage = 'https://github.com/google/protobuf'
s.license = '3-Clause BSD License'
diff --git a/README.md b/README.md
index 3a4e6ed2..f0f2e321 100644
--- a/README.md
+++ b/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) [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf) [![Build Status](https://grpc-testing.appspot.com/buildStatus/icon?job=protobuf_branch)](https://grpc-testing.appspot.com/job/protobuf_branch) [![Build Status](https://grpc-testing.appspot.com/job/protobuf_branch_32/badge/icon)](https://grpc-testing.appspot.com/job/protobuf_branch_32) [![Build Status](http://ci.bazel.io/buildStatus/icon?job=protobuf)](http://ci.bazel.io/job/protobuf/)
-
Copyright 2008 Google Inc.
https://developers.google.com/protocol-buffers/
@@ -54,19 +52,18 @@ Protobuf supports several different programming languages. For each programming
language, you can find instructions in the corresponding source directory about
how to install protobuf runtime for that specific language:
-| Language | Source |
-|--------------------------------------|-------------------------------------------------------------|
-| C++ (include C++ runtime and protoc) | [src](src) |
-| Java | [java](java) |
-| Python | [python](python) |
-| Objective-C | [objectivec](objectivec) |
-| C# | [csharp](csharp) |
-| JavaNano | [javanano](javanano) |
-| JavaScript | [js](js) |
-| Ruby | [ruby](ruby) |
-| Go | [golang/protobuf](https://github.com/golang/protobuf) |
-| PHP | [php](php) |
-| Dart | [dart-lang/protobuf](https://github.com/dart-lang/protobuf) |
+| 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) |
+| 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) | |
+| 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) | | | |
Quick Start
-----------
diff --git a/WORKSPACE b/WORKSPACE
index 1066a0e6..f3020843 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -1,17 +1,24 @@
workspace(name = "com_google_protobuf")
+load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
-new_git_repository(
- name = "googletest",
- build_file = "gmock.BUILD",
- remote = "https://github.com/google/googletest",
- tag = "release-1.8.0",
+new_local_repository(
+ name = "submodule_gmock",
+ path = "third_party/googletest",
+ 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(
@@ -21,12 +28,12 @@ bind(
bind(
name = "gtest",
- actual = "@googletest//:gtest",
+ actual = "@submodule_gmock//:gtest",
)
bind(
name = "gtest_main",
- actual = "@googletest//:gtest_main",
+ actual = "@submodule_gmock//:gtest_main",
)
bind(
diff --git a/appveyor.bat b/appveyor.bat
index ca88b25c..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
@@ -26,8 +38,8 @@ dotnet restore
dotnet build -c %configuration% || goto error
echo Testing C#
-dotnet run -c %configuration% -f netcoreapp1.0 -p Google.Protobuf.Test\Google.Protobuf.Test.csproj || goto error
-dotnet run -c %configuration% -f net451 -p Google.Protobuf.Test\Google.Protobuf.Test.csproj || goto error
+dotnet test -c %configuration% -f netcoreapp1.0 Google.Protobuf.Test\Google.Protobuf.Test.csproj || goto error
+dotnet test -c %configuration% -f net451 Google.Protobuf.Test\Google.Protobuf.Test.csproj || goto error
goto :EOF
diff --git a/appveyor.yml b/appveyor.yml
index 8b440b63..91f737a8 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -1,19 +1,29 @@
-# Only test one combination: "Visual Studio 12 + Win64 + Debug + DLL". We can
-# test more combinations but AppVeyor just takes too long to finish (each
-# combination takes ~15mins).
-platform:
- - Win64
-
configuration:
- Debug
environment:
matrix:
- - language: cpp
+ # 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: csharp
+ - platform: Win64
+ language: cpp
+ image: Visual Studio 2017
+ BUILD_DLL: OFF
+ UNICODE: ON
+
+ - platform: Win64
+ language: csharp
image: Visual Studio 2017
# Our build scripts run tests automatically; we don't want AppVeyor
@@ -21,19 +31,12 @@ environment:
test: off
install:
- - curl -L -o release-1.7.0.zip https://github.com/google/googlemock/archive/release-1.7.0.zip
- - 7z x release-1.7.0.zip
- - del /Q release-1.7.0.zip
- - rename googlemock-release-1.7.0 gmock
- - curl -L -o release-1.7.0.zip "https://github.com/google/googletest/archive/release-1.7.0.zip"
- - 7z x release-1.7.0.zip
- - del /Q release-1.7.0.zip
- - rename googletest-release-1.7.0 gtest
- - move gtest gmock
+ - git submodule update --init --recursive
before_build:
- - if %platform%==Win32 set generator=Visual Studio 12
- - if %platform%==Win64 set generator=Visual Studio 12 Win64
+ - 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
- if %platform%==Win64 set vcplatform=x64
diff --git a/autogen.sh b/autogen.sh
index 9560aaf1..580714b9 100755
--- a/autogen.sh
+++ b/autogen.sh
@@ -17,7 +17,6 @@ if [ ! -z "$@" ]; then
done
fi
-
# Check that we're being run from the right directory.
if test ! -f src/google/protobuf/stubs/common.h; then
cat >&2 << __EOF__
@@ -27,23 +26,6 @@ __EOF__
exit 1
fi
-# Check that gmock is present. Usually it is already there since the
-# directory is set up as an SVN external.
-if test ! -e gmock; then
- echo "Google Mock not present. Fetching gmock-1.7.0 from the web..."
- curl $curlopts -L -O https://github.com/google/googlemock/archive/release-1.7.0.zip
- unzip -q release-1.7.0.zip
- rm release-1.7.0.zip
- mv googlemock-release-1.7.0 gmock
-fi
-
-if test ! -e gmock/gtest; then
- curl $curlopts -L -O https://github.com/google/googletest/archive/release-1.7.0.zip
- unzip -q release-1.7.0.zip
- rm release-1.7.0.zip
- mv googletest-release-1.7.0 gmock/gtest
-fi
-
set -ex
# TODO(kenton): Remove the ",no-obsolete" part and fix the resulting warnings.
diff --git a/benchmarks/Makefile.am b/benchmarks/Makefile.am
index 5aa35c66..9f609228 100644
--- a/benchmarks/Makefile.am
+++ b/benchmarks/Makefile.am
@@ -1,9 +1,11 @@
+benchmarks_protoc_inputs_benchmark_wrapper = \
+ benchmarks.proto
+
benchmarks_protoc_inputs = \
- benchmarks.proto \
- datasets/google_message1/benchmark_message1_proto3.proto
+ datasets/google_message1/proto3/benchmark_message1_proto3.proto
benchmarks_protoc_inputs_proto2 = \
- datasets/google_message1/benchmark_message1_proto2.proto \
+ datasets/google_message1/proto2/benchmark_message1_proto2.proto \
datasets/google_message2/benchmark_message2.proto \
datasets/google_message3/benchmark_message3.proto \
datasets/google_message3/benchmark_message3_1.proto \
@@ -23,76 +25,62 @@ make_tmp_dir:
mkdir -p 'tmp/java/src/main/java'
touch make_tmp_dir
-if USE_EXTERNAL_PROTOC
-
-protoc_middleman: make_tmp_dir $(benchmarks_protoc_inputs)
- $(PROTOC) -I$(srcdir) -I$(top_srcdir) --cpp_out=. --java_out=./tmp $(benchmarks_protoc_inputs)
- touch protoc_middleman
-
-protoc_middleman2: make_tmp_dir $(benchmarks_protoc_inputs_proto2)
- $(PROTOC) -I$(srcdir) -I$(top_srcdir) --cpp_out=. --java_out=./tmp $(benchmarks_protoc_inputs_proto2)
- touch protoc_middleman2
-
-else
-
# We have to cd to $(srcdir) before executing protoc because $(protoc_inputs) is
# relative to srcdir, which may not be the same as the current directory when
# building out-of-tree.
-protoc_middleman: make_tmp_dir $(top_srcdir)/src/protoc$(EXEEXT) $(benchmarks_protoc_inputs) $(well_known_type_protoc_inputs)
- oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd --java_out=$$oldpwd/tmp/java/src/main/java --python_out=$$oldpwd/tmp $(benchmarks_protoc_inputs) )
+protoc_middleman: make_tmp_dir $(top_srcdir)/src/protoc$(EXEEXT) $(benchmarks_protoc_inputs) $(well_known_type_protoc_inputs) $(benchmarks_protoc_inputs_benchmark_wrapper)
+ 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) $(benchmarks_protoc_inputs_benchmark_wrapper) )
touch protoc_middleman
protoc_middleman2: make_tmp_dir $(top_srcdir)/src/protoc$(EXEEXT) $(benchmarks_protoc_inputs_proto2) $(well_known_type_protoc_inputs)
- oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd --java_out=$$oldpwd/tmp/java/src/main/java --python_out=$$oldpwd/tmp $(benchmarks_protoc_inputs_proto2) )
+ 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
-endif
-
-all_data = `find . -type f -name "dataset.*.pb"`
+all_data = $$(find $(srcdir) -type f -name "dataset.*.pb" -not -path "./tmp/*")
############# CPP RULES ##############
benchmarks_protoc_outputs = \
- benchmarks.pb.cc \
- datasets/google_message1/benchmark_message1_proto3.pb.cc
-
+ cpp/benchmarks.pb.cc \
+ cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc
+
benchmarks_protoc_outputs_header = \
- benchmarks.pb.h \
- datasets/google_message1/benchmark_message1_proto3.pb.h
+ cpp/benchmarks.pb.h \
+ cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.h
benchmarks_protoc_outputs_proto2_header = \
- datasets/google_message1/benchmark_message1_proto2.pb.h \
- datasets/google_message2/benchmark_message2.pb.h \
- datasets/google_message3/benchmark_message3.pb.h \
- datasets/google_message3/benchmark_message3_1.pb.h \
- datasets/google_message3/benchmark_message3_2.pb.h \
- datasets/google_message3/benchmark_message3_3.pb.h \
- datasets/google_message3/benchmark_message3_4.pb.h \
- datasets/google_message3/benchmark_message3_5.pb.h \
- datasets/google_message3/benchmark_message3_6.pb.h \
- datasets/google_message3/benchmark_message3_7.pb.h \
- datasets/google_message3/benchmark_message3_8.pb.h \
- datasets/google_message4/benchmark_message4.pb.h \
- datasets/google_message4/benchmark_message4_1.pb.h \
- datasets/google_message4/benchmark_message4_2.pb.h \
- datasets/google_message4/benchmark_message4_3.pb.h
+ cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.h \
+ cpp/datasets/google_message2/benchmark_message2.pb.h \
+ cpp/datasets/google_message3/benchmark_message3.pb.h \
+ cpp/datasets/google_message3/benchmark_message3_1.pb.h \
+ cpp/datasets/google_message3/benchmark_message3_2.pb.h \
+ cpp/datasets/google_message3/benchmark_message3_3.pb.h \
+ cpp/datasets/google_message3/benchmark_message3_4.pb.h \
+ cpp/datasets/google_message3/benchmark_message3_5.pb.h \
+ cpp/datasets/google_message3/benchmark_message3_6.pb.h \
+ cpp/datasets/google_message3/benchmark_message3_7.pb.h \
+ cpp/datasets/google_message3/benchmark_message3_8.pb.h \
+ cpp/datasets/google_message4/benchmark_message4.pb.h \
+ cpp/datasets/google_message4/benchmark_message4_1.pb.h \
+ cpp/datasets/google_message4/benchmark_message4_2.pb.h \
+ cpp/datasets/google_message4/benchmark_message4_3.pb.h
benchmarks_protoc_outputs_proto2 = \
- datasets/google_message1/benchmark_message1_proto2.pb.cc \
- datasets/google_message2/benchmark_message2.pb.cc \
- datasets/google_message3/benchmark_message3.pb.cc \
- datasets/google_message3/benchmark_message3_1.pb.cc \
- datasets/google_message3/benchmark_message3_2.pb.cc \
- datasets/google_message3/benchmark_message3_3.pb.cc \
- datasets/google_message3/benchmark_message3_4.pb.cc \
- datasets/google_message3/benchmark_message3_5.pb.cc \
- datasets/google_message3/benchmark_message3_6.pb.cc \
- datasets/google_message3/benchmark_message3_7.pb.cc \
- datasets/google_message3/benchmark_message3_8.pb.cc \
- datasets/google_message4/benchmark_message4.pb.cc \
- datasets/google_message4/benchmark_message4_1.pb.cc \
- datasets/google_message4/benchmark_message4_2.pb.cc \
- datasets/google_message4/benchmark_message4_3.pb.cc
+ cpp/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc \
+ cpp/datasets/google_message2/benchmark_message2.pb.cc \
+ cpp/datasets/google_message3/benchmark_message3.pb.cc \
+ cpp/datasets/google_message3/benchmark_message3_1.pb.cc \
+ cpp/datasets/google_message3/benchmark_message3_2.pb.cc \
+ cpp/datasets/google_message3/benchmark_message3_3.pb.cc \
+ cpp/datasets/google_message3/benchmark_message3_4.pb.cc \
+ cpp/datasets/google_message3/benchmark_message3_5.pb.cc \
+ cpp/datasets/google_message3/benchmark_message3_6.pb.cc \
+ cpp/datasets/google_message3/benchmark_message3_7.pb.cc \
+ cpp/datasets/google_message3/benchmark_message3_8.pb.cc \
+ cpp/datasets/google_message4/benchmark_message4.pb.cc \
+ cpp/datasets/google_message4/benchmark_message4_1.pb.cc \
+ cpp/datasets/google_message4/benchmark_message4_2.pb.cc \
+ cpp/datasets/google_message4/benchmark_message4_3.pb.cc
$(benchmarks_protoc_outputs): protoc_middleman
@@ -107,8 +95,7 @@ initialize_submodule:
cd $(top_srcdir)/third_party/benchmark && cmake -DCMAKE_BUILD_TYPE=Release && make
cd $$oldpwd
touch initialize_submodule
-
-$(top_srcdir)/src/libprotobuf.la: initialize_submodule
+
$(top_srcdir)/third_party/benchmark/src/libbenchmark.a: initialize_submodule
AM_CXXFLAGS = $(NO_OPT_CXXFLAGS) $(PROTOBUF_OPT_FLAG) -Wall -Wwrite-strings -Woverloaded-virtual -Wno-sign-compare
@@ -116,12 +103,12 @@ AM_CXXFLAGS = $(NO_OPT_CXXFLAGS) $(PROTOBUF_OPT_FLAG) -Wall -Wwrite-strings -Wov
bin_PROGRAMS = cpp-benchmark
cpp_benchmark_LDADD = $(top_srcdir)/src/libprotobuf.la $(top_srcdir)/third_party/benchmark/src/libbenchmark.a
-cpp_benchmark_SOURCES = cpp_benchmark.cc
-cpp_benchmark_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir) -I$(top_srcdir)/third_party/benchmark/include
+cpp_benchmark_SOURCES = cpp/cpp_benchmark.cc
+cpp_benchmark_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir)/cpp -I$(top_srcdir)/third_party/benchmark/include
# Explicit deps because BUILT_SOURCES are only done before a "make all/check"
# so a direct "make test_cpp" could fail if parallel enough.
# See: https://www.gnu.org/software/automake/manual/html_node/Built-Sources-Example.html#Recording-Dependencies-manually
-cpp_benchmark-cpp_benchmark.$(OBJEXT): $(benchmarks_protoc_outputs) $(benchmarks_protoc_outputs_proto2) $(benchmarks_protoc_outputs_header) $(benchmarks_protoc_outputs_proto2_header) $(top_srcdir)/src/libprotobuf.la $(top_srcdir)/third_party/benchmark/src/libbenchmark.a
+cpp/cpp_benchmark-cpp_benchmark.$(OBJEXT): $(benchmarks_protoc_outputs) $(benchmarks_protoc_outputs_proto2) $(benchmarks_protoc_outputs_header) $(benchmarks_protoc_outputs_proto2_header) $(top_srcdir)/src/libprotobuf.la $(top_srcdir)/third_party/benchmark/src/libbenchmark.a
nodist_cpp_benchmark_SOURCES = \
$(benchmarks_protoc_outputs) \
$(benchmarks_protoc_outputs_proto2) \
@@ -136,18 +123,26 @@ cpp: protoc_middleman protoc_middleman2 cpp-benchmark initialize_submodule
############# JAVA RULES ##############
java_benchmark_testing_files = \
- java/src/main/java/com/google/protobuf/ProtoBench.java \
java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java
javac_middleman: $(java_benchmark_testing_files) protoc_middleman protoc_middleman2
- cp -r 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
@echo "Writing shortcut script java-benchmark..."
- @echo '#! /bin/sh' > java-benchmark
- @echo 'java -cp '"tmp/java/target/*.jar"' com.google.protobuf.ProtoBench $$@' >> java-benchmark
+ @echo '#! /bin/bash' > java-benchmark
+ @echo 'all_data=""' >> java-benchmark
+ @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/*:$(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
@@ -172,11 +167,11 @@ python_add_init: protoc_middleman protoc_middleman2
python_cpp_pkg_flags = `pkg-config --cflags --libs python`
lib_LTLIBRARIES = libbenchmark_messages.la
-libbenchmark_messages_la_SOURCES = python_benchmark_messages.cc
+libbenchmark_messages_la_SOURCES = python/python_benchmark_messages.cc
libbenchmark_messages_la_LIBADD = $(top_srcdir)/src/.libs/libprotobuf.la
libbenchmark_messages_la_LDFLAGS = -version-info 1:0:0 -export-dynamic
-libbenchmark_messages_la_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir) $(python_cpp_pkg_flags)
-libbenchmark_messages_la-libbenchmark_messages_la.$(OBJEXT): $(benchmarks_protoc_outputs_header) $(benchmarks_protoc_outputs_proto2_header) $(benchmarks_protoc_outputs) $(benchmarks_protoc_outputs_proto2)
+libbenchmark_messages_la_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir)/cpp $(python_cpp_pkg_flags)
+libbenchmark_messages_la-python_benchmark_messages.$(OBJEXT): $(benchmarks_protoc_outputs_header) $(benchmarks_protoc_outputs_proto2_header) $(benchmarks_protoc_outputs) $(benchmarks_protoc_outputs_proto2)
nodist_libbenchmark_messages_la_SOURCES = \
$(benchmarks_protoc_outputs) \
$(benchmarks_protoc_outputs_proto2) \
@@ -185,32 +180,32 @@ nodist_libbenchmark_messages_la_SOURCES = \
python-pure-python-benchmark: python_add_init
@echo "Writing shortcut script python-pure-python-benchmark..."
- @echo '#! /bin/sh' > 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 '#! /bin/bash' > 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 py_benchmark.py tmp >> python-pure-python-benchmark
- @echo python tmp/py_benchmark.py false '$$@' >> 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
@chmod +x python-pure-python-benchmark
python-cpp-reflection-benchmark: python_add_init
@echo "Writing shortcut script python-cpp-reflection-benchmark..."
- @echo '#! /bin/sh' > 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 '#! /bin/bash' > 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 py_benchmark.py tmp >> python-cpp-reflection-benchmark
- @echo python tmp/py_benchmark.py false '$$@' >> 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
@chmod +x python-cpp-reflection-benchmark
python-cpp-generated-code-benchmark: python_add_init libbenchmark_messages.la
@echo "Writing shortcut script python-cpp-generated-code-benchmark..."
- @echo '#! /bin/sh' > 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 '#! /bin/bash' > 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 py_benchmark.py tmp >> python-cpp-generated-code-benchmark
- @echo python tmp/py_benchmark.py true '$$@' >> 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
@chmod +x python-cpp-generated-code-benchmark
python-pure-python: python-pure-python-benchmark
@@ -224,6 +219,287 @@ python-cpp-generated-code: python-cpp-generated-code-benchmark
############# PYTHON RULES END ##############
+############# GO RULES BEGIN ##############
+
+benchmarks_protoc_inputs_proto2_message1 = \
+ datasets/google_message1/proto2/benchmark_message1_proto2.proto
+
+benchmarks_protoc_inputs_proto2_message2 = \
+ datasets/google_message2/benchmark_message2.proto
+
+benchmarks_protoc_inputs_proto2_message3 = \
+ datasets/google_message3/benchmark_message3.proto \
+ datasets/google_message3/benchmark_message3_1.proto \
+ datasets/google_message3/benchmark_message3_2.proto \
+ datasets/google_message3/benchmark_message3_3.proto \
+ datasets/google_message3/benchmark_message3_4.proto \
+ datasets/google_message3/benchmark_message3_5.proto \
+ datasets/google_message3/benchmark_message3_6.proto \
+ datasets/google_message3/benchmark_message3_7.proto \
+ datasets/google_message3/benchmark_message3_8.proto
+
+benchmarks_protoc_inputs_proto2_message4 = \
+ datasets/google_message4/benchmark_message4.proto \
+ datasets/google_message4/benchmark_message4_1.proto \
+ datasets/google_message4/benchmark_message4_2.proto \
+ datasets/google_message4/benchmark_message4_3.proto
+
+go_protoc_middleman: make_tmp_dir $(top_srcdir)/src/protoc$(EXEEXT) $(benchmarks_protoc_inputs) $(well_known_type_protoc_inputs) $(benchmarks_protoc_inputs_proto2_message1) $(benchmarks_protoc_inputs_proto2_message2) $(benchmarks_protoc_inputs_proto2_message3) $(benchmarks_protoc_inputs_proto2_message4) $(well_known_type_protoc_inputs)
+ oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --go_out=$$oldpwd/tmp $(benchmarks_protoc_inputs) )
+ oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --go_out=$$oldpwd/tmp $(benchmarks_protoc_inputs_benchmark_wrapper) )
+ oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --go_out=$$oldpwd/tmp $(benchmarks_protoc_inputs_proto2_message1) )
+ oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --go_out=$$oldpwd/tmp $(benchmarks_protoc_inputs_proto2_message2) )
+ oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --go_out=$$oldpwd/tmp $(benchmarks_protoc_inputs_proto2_message3) )
+ oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --go_out=$$oldpwd/tmp $(benchmarks_protoc_inputs_proto2_message4) )
+ touch go_protoc_middleman
+
+go-benchmark: go_protoc_middleman
+ @echo "Writing shortcut script go-benchmark..."
+ @echo '#! /bin/bash' > go-benchmark
+ @echo 'cd $(srcdir)/go' >> go-benchmark
+ @echo 'all_data=""' >> go-benchmark
+ @echo 'conf=()' >> go-benchmark
+ @echo 'data_files=()' >> go-benchmark
+ @echo 'for arg in $$@; do if [[ $${arg:0:1} == "-" ]]; then conf+=($$arg); else data_files+=("../$$arg"); fi; done' >> go-benchmark
+ @echo 'go test -bench=. $${conf[*]} -- $${data_files[*]}' >> go-benchmark
+ @echo 'cd ..' >> go-benchmark
+ @chmod +x go-benchmark
+
+go: go_protoc_middleman go-benchmark
+ ./go-benchmark $(all_data)
+
+############# GO RULES END ##############
+
+############# GOGO RULES BEGIN ############
+
+cpp_no_group_benchmarks_protoc_outputs_header = \
+ gogo/cpp_no_group/benchmarks.pb.h \
+ gogo/cpp_no_group/datasets/google_message1/proto3/benchmark_message1_proto3.pb.h
+
+cpp_no_group_benchmarks_protoc_outputs = \
+ gogo/cpp_no_group/benchmarks.pb.cc \
+ gogo/cpp_no_group/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc
+
+cpp_no_group_benchmarks_protoc_outputs_proto2_header = \
+ gogo/cpp_no_group/datasets/google_message1/proto2/benchmark_message1_proto2.pb.h \
+ gogo/cpp_no_group/datasets/google_message2/benchmark_message2.pb.h \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3.pb.h \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_1.pb.h \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_2.pb.h \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_3.pb.h \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_4.pb.h \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_5.pb.h \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_6.pb.h \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_7.pb.h \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_8.pb.h \
+ gogo/cpp_no_group/datasets/google_message4/benchmark_message4.pb.h \
+ gogo/cpp_no_group/datasets/google_message4/benchmark_message4_1.pb.h \
+ gogo/cpp_no_group/datasets/google_message4/benchmark_message4_2.pb.h \
+ gogo/cpp_no_group/datasets/google_message4/benchmark_message4_3.pb.h
+
+cpp_no_group_benchmarks_protoc_outputs_proto2 = \
+ gogo/cpp_no_group/datasets/google_message1/proto2/benchmark_message1_proto2.pb.cc \
+ gogo/cpp_no_group/datasets/google_message2/benchmark_message2.pb.cc \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3.pb.cc \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_1.pb.cc \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_2.pb.cc \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_3.pb.cc \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_4.pb.cc \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_5.pb.cc \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_6.pb.cc \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_7.pb.cc \
+ gogo/cpp_no_group/datasets/google_message3/benchmark_message3_8.pb.cc \
+ gogo/cpp_no_group/datasets/google_message4/benchmark_message4.pb.cc \
+ gogo/cpp_no_group/datasets/google_message4/benchmark_message4_1.pb.cc \
+ gogo/cpp_no_group/datasets/google_message4/benchmark_message4_2.pb.cc \
+ gogo/cpp_no_group/datasets/google_message4/benchmark_message4_3.pb.cc
+
+$(cpp_no_group_benchmarks_protoc_outputs): cpp_no_group_protoc_middleman
+$(cpp_no_group_benchmarks_protoc_outputs_header): cpp_no_group_protoc_middleman
+$(cpp_no_group_benchmarks_protoc_outputs_proto2): cpp_no_group_protoc_middleman
+$(cpp_no_group_benchmarks_protoc_outputs_proto2_header): cpp_no_group_protoc_middleman
+
+generate_cpp_no_group_benchmark_code:
+ cp $(srcdir)/cpp/cpp_benchmark.cc gogo/cpp_no_group/cpp_benchmark.cc
+ sed -i -e "s/\#include \"datasets/\#include \"gogo\/cpp_no_group\/datasets/g" gogo/cpp_no_group/cpp_benchmark.cc
+ sed -i -e "s/\#include \"benchmarks.pb.h/\#include \"gogo\/cpp_no_group\/benchmarks.pb.h/g" gogo/cpp_no_group/cpp_benchmark.cc
+ touch generate_cpp_no_group_benchmark_code
+
+bin_PROGRAMS += cpp-no-group-benchmark
+cpp_no_group_benchmark_LDADD = $(top_srcdir)/src/libprotobuf.la $(top_srcdir)/third_party/benchmark/src/libbenchmark.a
+cpp_no_group_benchmark_SOURCES = gogo/cpp_no_group/cpp_benchmark.cc
+cpp_no_group_benchmark_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir)/gogo/cpp_no_group -I$(top_srcdir)/third_party/benchmark/include
+# Explicit deps because BUILT_SOURCES are only done before a "make all/check"
+# so a direct "make test_cpp" could fail if parallel enough.
+# See: https://www.gnu.org/software/automake/manual/html_node/Built-Sources-Example.html#Recording-Dependencies-manually
+gogo/cpp_no_group/cpp_no_group_benchmark-cpp_benchmark.$(OBJEXT): $(cpp_no_group_benchmarks_protoc_outputs) $(cpp_no_group_benchmarks_protoc_outputs_proto2) $(cpp_no_group_benchmarks_protoc_outputs_header) \
+ $(cpp_no_group_benchmarks_protoc_outputs_proto2_header) $(top_srcdir)/third_party/benchmark/src/libbenchmark.a generate_cpp_no_group_benchmark_code
+gogo/cpp_no_group/cpp_benchmark.cc: generate_cpp_no_group_benchmark_code
+nodist_cpp_no_group_benchmark_SOURCES = \
+ $(cpp_no_group_benchmarks_protoc_outputs_proto2) \
+ $(cpp_no_group_benchmarks_protoc_outputs) \
+ $(cpp_no_group_benchmarks_protoc_outputs_header) \
+ $(cpp_no_group_benchmarks_protoc_outputs_proto2_header)
+
+cpp_no_group: cpp_no_group_protoc_middleman generate_gogo_data cpp-no-group-benchmark
+ ./cpp-no-group-benchmark $(gogo_data)
+
+gogo_proto_middleman: protoc-gen-gogoproto
+ mkdir -p "tmp/gogo_proto"
+ 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
+
+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 $(gogo_data)`
+ ./gogo-data-scrubber $(all_data) $(gogo_data)
+ touch generate_gogo_data
+
+make_tmp_dir_gogo:
+ mkdir -p tmp/go_no_group/benchmark_code
+ mkdir -p tmp/gogofast/benchmark_code
+ mkdir -p tmp/gogofaster/benchmark_code
+ mkdir -p tmp/gogoslick/benchmark_code
+ touch make_tmp_dir_gogo
+
+go_no_group_protoc_middleman: make_tmp_dir_gogo $(top_srcdir)/src/protoc$(EXEEXT) gogo_proto_middleman $(well_known_type_protoc_inputs)
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --go_out=$$oldpwd/tmp/go_no_group $(benchmarks_protoc_inputs) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --go_out=$$oldpwd/tmp/go_no_group $(benchmarks_protoc_inputs_benchmark_wrapper) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --go_out=$$oldpwd/tmp/go_no_group $(benchmarks_protoc_inputs_proto2_message1) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --go_out=$$oldpwd/tmp/go_no_group $(benchmarks_protoc_inputs_proto2_message2) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --go_out=$$oldpwd/tmp/go_no_group $(benchmarks_protoc_inputs_proto2_message3) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --go_out=$$oldpwd/tmp/go_no_group $(benchmarks_protoc_inputs_proto2_message4) )
+ touch go_no_group_protoc_middleman
+
+cpp_no_group_protoc_middleman: make_tmp_dir_gogo $(top_srcdir)/src/protoc$(EXEEXT) gogo_proto_middleman $(well_known_type_protoc_inputs)
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --cpp_out=$$oldpwd/gogo/cpp_no_group $(benchmarks_protoc_inputs) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --cpp_out=$$oldpwd/gogo/cpp_no_group $(benchmarks_protoc_inputs_benchmark_wrapper) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --cpp_out=$$oldpwd/gogo/cpp_no_group $(benchmarks_protoc_inputs_proto2_message1) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --cpp_out=$$oldpwd/gogo/cpp_no_group $(benchmarks_protoc_inputs_proto2_message2) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --cpp_out=$$oldpwd/gogo/cpp_no_group $(benchmarks_protoc_inputs_proto2_message3) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --cpp_out=$$oldpwd/gogo/cpp_no_group $(benchmarks_protoc_inputs_proto2_message4) )
+ touch cpp_no_group_protoc_middleman
+
+gogofast_protoc_middleman: make_tmp_dir_gogo $(top_srcdir)/src/protoc$(EXEEXT) gogo_proto_middleman $(well_known_type_protoc_inputs)
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --gogofast_out=$$oldpwd/tmp/gogofast $(benchmarks_protoc_inputs) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --gogofast_out=$$oldpwd/tmp/gogofast $(benchmarks_protoc_inputs_benchmark_wrapper) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --gogofast_out=$$oldpwd/tmp/gogofast $(benchmarks_protoc_inputs_proto2_message1) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --gogofast_out=$$oldpwd/tmp/gogofast $(benchmarks_protoc_inputs_proto2_message2) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --gogofast_out=$$oldpwd/tmp/gogofast $(benchmarks_protoc_inputs_proto2_message3) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --gogofast_out=$$oldpwd/tmp/gogofast $(benchmarks_protoc_inputs_proto2_message4) )
+ touch gogofast_protoc_middleman
+
+gogofaster_protoc_middleman: make_tmp_dir_gogo $(top_srcdir)/src/protoc$(EXEEXT) gogo_proto_middleman $(well_known_type_protoc_inputs)
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --gogofaster_out=$$oldpwd/tmp/gogofaster $(benchmarks_protoc_inputs) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --gogofaster_out=$$oldpwd/tmp/gogofaster $(benchmarks_protoc_inputs_benchmark_wrapper) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --gogofaster_out=$$oldpwd/tmp/gogofaster $(benchmarks_protoc_inputs_proto2_message1) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --gogofaster_out=$$oldpwd/tmp/gogofaster $(benchmarks_protoc_inputs_proto2_message2) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --gogofaster_out=$$oldpwd/tmp/gogofaster $(benchmarks_protoc_inputs_proto2_message3) )
+ oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --gogofaster_out=$$oldpwd/tmp/gogofaster $(benchmarks_protoc_inputs_proto2_message4) )
+ touch gogofaster_protoc_middleman
+
+gogoslick_protoc_middleman: make_tmp_dir_gogo $(top_srcdir)/src/protoc$(EXEEXT) gogo_proto_middleman $(well_known_type_protoc_inputs)
+ 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) )
+ 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_benchmark_wrapper) )
+ 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_message1) )
+ 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_message2) )
+ 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_message3) )
+ 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
+
+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
+ @echo 'sed -i -e "s/\.\.\/tmp/../g" tmp/$$1/benchmark_code/$$1_benchmark1_test.go' >> generate-gogo-benchmark-code
+ @echo 'sed -i -e "s/b\.Run(\"\(.*\)\"/b.Run(\"\1\_$$1\"/g" tmp/$$1/benchmark_code/$$1_benchmark1_test.go' >> generate-gogo-benchmark-code
+ @echo 'if [[ $$2 == 1 ]]; then sed -i -e "s/github\.com\/golang/github.com\/gogo/g" tmp/$$1/benchmark_code/$$1_benchmark1_test.go; fi ' >> generate-gogo-benchmark-code
+ @chmod +x generate-gogo-benchmark-code
+
+generate_all_gogo_benchmark_code: generate-gogo-benchmark-code make_tmp_dir_gogo
+ ./generate-gogo-benchmark-code go_no_group 0
+ ./generate-gogo-benchmark-code gogofast 1
+ ./generate-gogo-benchmark-code gogofaster 1
+ ./generate-gogo-benchmark-code gogoslick 1
+
+gogo-benchmark:
+ @echo "Writing shortcut script gogo-benchmark..."
+ @echo '#! /bin/bash' > gogo-benchmark
+ @echo 'cd tmp/$$1/benchmark_code' >> gogo-benchmark
+ @echo 'shift' >> gogo-benchmark
+ @echo 'all_data=""' >> gogo-benchmark
+ @echo 'for data_file in $$@; do all_data="$$all_data ../../../$$data_file"; done' >> gogo-benchmark
+ @echo 'go test -bench=. -- $$all_data' >> gogo-benchmark
+ @echo 'cd ../..' >> gogo-benchmark
+ @chmod +x gogo-benchmark
+
+go_no_group: go_no_group_protoc_middleman generate_gogo_data generate_all_gogo_benchmark_code gogo-benchmark
+ ./gogo-benchmark go_no_group $(gogo_data)
+
+gogofast: gogofast_protoc_middleman generate_gogo_data gogo-benchmark generate_all_gogo_benchmark_code
+ ./gogo-benchmark gogofast $(gogo_data)
+
+gogofaster: gogofaster_protoc_middleman generate_gogo_data gogo-benchmark generate_all_gogo_benchmark_code
+ ./gogo-benchmark gogofaster $(gogo_data)
+
+gogoslick: gogoslick_protoc_middleman generate_gogo_data gogo-benchmark generate_all_gogo_benchmark_code
+ ./gogo-benchmark gogoslick $(gogo_data)
+
+
+############# GOGO RULES END ############
+
+
+############ UTIL RULES BEGIN ############
+
+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
+protoc_gen_gogoproto_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir)/cpp -I$(srcdir)/util
+
+gogo_data_scrubber_LDADD = $(top_srcdir)/src/libprotobuf.la
+gogo_data_scrubber_SOURCES = util/gogo_data_scrubber.cc
+gogo_data_scrubber_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir)/cpp -I$(srcdir)/util
+util/gogo_data_scrubber-gogo_data_scrubber.$(OBJEXT): $(benchmarks_protoc_outputs) $(benchmarks_protoc_outputs_proto2) $(benchmarks_protoc_outputs_header) $(benchmarks_protoc_outputs_proto2_header)
+nodist_gogo_data_scrubber_SOURCES = \
+ $(benchmarks_protoc_outputs) \
+ $(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
+
+proto3_data = $$(for data in $(all_data); do echo "tmp/proto3_data$${data\#$(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 #############
+
MAINTAINERCLEANFILES = \
Makefile.in
@@ -241,7 +517,35 @@ CLEANFILES = \
python_cpp_proto_library \
python-pure-python-benchmark \
python-cpp-reflection-benchmark \
- python-cpp-generated-code-benchmark
+ python-cpp-generated-code-benchmark \
+ go-benchmark \
+ go_protoc_middleman \
+ make_tmp_dir_gogo \
+ gogo_proto_middleman \
+ generate_gogo_data \
+ go_no_group_protoc_middleman \
+ go_no_group \
+ go-no-group-benchmark \
+ $(cpp_no_group_benchmarks_protoc_outputs_header) \
+ $(cpp_no_group_benchmarks_protoc_outputs) \
+ $(cpp_no_group_benchmarks_protoc_outputs_proto2_header) \
+ $(cpp_no_group_benchmarks_protoc_outputs_proto2) \
+ generate_all_gogo_benchmark_code \
+ generate-gogo-benchmark-code \
+ cpp_no_group_protoc_middleman \
+ generate_cpp_no_group_benchmark_code \
+ generate_gogo_benchmark_code \
+ gogofast_protoc_middleman \
+ gogofast \
+ gogofaster_protoc_middleman \
+ gogofaster \
+ gogoslick_protoc_middleman \
+ gogoslick \
+ gogo-benchmark \
+ gogo/cpp_no_group/cpp_benchmark.* \
+ proto3_proto_middleman \
+ generate_proto3_data
+
clean-local:
-rm -rf tmp/*
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 459c7b9d..ae5c7ddd 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -3,7 +3,9 @@
This directory contains benchmarking schemas and data sets that you
can use to test a variety of performance scenarios against your
-protobuf language runtime.
+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)
## Prerequisite
@@ -17,6 +19,11 @@ We are using [google/benchmark](https://github.com/google/benchmark) as the
benchmark tool for testing cpp. This will be automaticly made during build the
cpp benchmark.
+The cpp protobuf performance can be improved by linking with [tcmalloc library](
+https://gperftools.github.io/gperftools/tcmalloc.html). For using tcmalloc, you
+need to build [gpertools](https://github.com/gperftools/gperftools) to generate
+libtcmallc.so library.
+
### Java
We're using maven to build the java benchmarks, which is the same as to build
the Java protobuf. There're no other tools need to install. We're using
@@ -36,6 +43,21 @@ $ sudo apt-get install python3-dev
```
And you also need to make sure `pkg-config` is installed.
+### Go
+Go protobufs are maintained at [github.com/golang/protobuf](
+http://github.com/golang/protobuf). If not done already, you need to install the
+toolchain and the Go protoc-gen-go plugin for protoc.
+
+To install protoc-gen-go, run:
+
+```
+$ go get -u github.com/golang/protobuf/protoc-gen-go
+$ 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.
+
### Big data
There's some optional big testing data which is not included in the directory
@@ -64,6 +86,12 @@ $ make java
$ make cpp
```
+For linking with tcmalloc:
+
+```
+$ env LD_PRELOAD={directory to libtcmalloc.so} make cpp
+```
+
### Python:
We have three versions of python protobuf implementation: pure python, cpp
@@ -87,45 +115,59 @@ $ make python-cpp-reflection
$ make python-cpp-generated-code
```
-To run a specific dataset:
+### Go
+```
+$ make go
+```
+
+To run a specific dataset or run with specific options:
### Java:
```
$ make java-benchmark
-$ ./java-benchmark $(specific generated dataset file name) [-- $(caliper option)]
+$ ./java-benchmark $(specific generated dataset file name) [$(caliper options)]
```
### CPP:
```
$ make cpp-benchmark
-$ ./cpp-benchmark $(specific generated dataset file name)
+$ ./cpp-benchmark $(specific generated dataset file name) [$(benchmark options)]
```
### Python:
+For Python benchmark we have `--json` for outputing the json result
+
#### Pure Python:
```
$ make python-pure-python-benchmark
-$ ./python-pure-python-benchmark $(specific generated dataset file name)
+$ ./python-pure-python-benchmark [--json] $(specific generated dataset file name)
```
#### CPP reflection:
```
$ make python-cpp-reflection-benchmark
-$ ./python-cpp-reflection-benchmark $(specific generated dataset file name)
+$ ./python-cpp-reflection-benchmark [--json] $(specific generated dataset file name)
```
#### CPP generated code:
```
$ make python-cpp-generated-code-benchmark
-$ ./python-cpp-generated-code-benchmark $(specific generated dataset file name)
+$ ./python-cpp-generated-code-benchmark [--json] $(specific generated dataset file name)
```
+### Go:
+```
+$ make go-benchmark
+$ ./go-benchmark $(specific generated dataset file name) [go testing options]
+```
+
+
## Benchmark datasets
Each data set is in the format of benchmarks.proto:
diff --git a/benchmarks/cpp_benchmark.cc b/benchmarks/cpp/cpp_benchmark.cc
index 0ba4dc52..f8b55291 100644
--- a/benchmarks/cpp_benchmark.cc
+++ b/benchmarks/cpp/cpp_benchmark.cc
@@ -32,8 +32,8 @@
#include <iostream>
#include "benchmark/benchmark_api.h"
#include "benchmarks.pb.h"
-#include "datasets/google_message1/benchmark_message1_proto2.pb.h"
-#include "datasets/google_message1/benchmark_message1_proto3.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"
diff --git a/benchmarks/datasets/google_message1/benchmark_message1_proto2.proto b/benchmarks/datasets/google_message1/proto2/benchmark_message1_proto2.proto
index 21261905..21261905 100644
--- a/benchmarks/datasets/google_message1/benchmark_message1_proto2.proto
+++ b/benchmarks/datasets/google_message1/proto2/benchmark_message1_proto2.proto
diff --git a/benchmarks/datasets/google_message1/dataset.google_message1_proto2.pb b/benchmarks/datasets/google_message1/proto2/dataset.google_message1_proto2.pb
index f6fe7848..f6fe7848 100644
--- a/benchmarks/datasets/google_message1/dataset.google_message1_proto2.pb
+++ b/benchmarks/datasets/google_message1/proto2/dataset.google_message1_proto2.pb
Binary files differ
diff --git a/benchmarks/datasets/google_message1/benchmark_message1_proto3.proto b/benchmarks/datasets/google_message1/proto3/benchmark_message1_proto3.proto
index 090b554b..090b554b 100644
--- a/benchmarks/datasets/google_message1/benchmark_message1_proto3.proto
+++ b/benchmarks/datasets/google_message1/proto3/benchmark_message1_proto3.proto
diff --git a/benchmarks/datasets/google_message1/dataset.google_message1_proto3.pb b/benchmarks/datasets/google_message1/proto3/dataset.google_message1_proto3.pb
index 4955bed3..4955bed3 100644
--- a/benchmarks/datasets/google_message1/dataset.google_message1_proto3.pb
+++ b/benchmarks/datasets/google_message1/proto3/dataset.google_message1_proto3.pb
Binary files differ
diff --git a/benchmarks/go/go_benchmark_test.go b/benchmarks/go/go_benchmark_test.go
new file mode 100644
index 00000000..8c741b71
--- /dev/null
+++ b/benchmarks/go/go_benchmark_test.go
@@ -0,0 +1,124 @@
+package main
+
+import (
+ benchmarkWrapper "../tmp"
+ googleMessage1Proto2 "../tmp/datasets/google_message1/proto2"
+ googleMessage1Proto3 "../tmp/datasets/google_message1/proto3"
+ googleMessage2 "../tmp/datasets/google_message2"
+ googleMessage3 "../tmp/datasets/google_message3"
+ googleMessage4 "../tmp/datasets/google_message4"
+ "flag"
+ "github.com/golang/protobuf/proto"
+ "io/ioutil"
+ "testing"
+)
+
+// Data is returned by the Load function.
+type Dataset struct {
+ name string
+ newMessage func() proto.Message
+ marshaled [][]byte
+ unmarshaled []proto.Message
+}
+
+var datasets []Dataset
+
+// This is used to getDefaultInstance for a message type.
+func generateNewMessageFunction(dataset benchmarkWrapper.BenchmarkDataset) func() proto.Message {
+ switch dataset.MessageName {
+ case "benchmarks.proto3.GoogleMessage1":
+ return func() proto.Message { return new(googleMessage1Proto3.GoogleMessage1) }
+ case "benchmarks.proto2.GoogleMessage1":
+ return func() proto.Message { return new(googleMessage1Proto2.GoogleMessage1) }
+ case "benchmarks.proto2.GoogleMessage2":
+ return func() proto.Message { return new(googleMessage2.GoogleMessage2) }
+ case "benchmarks.google_message3.GoogleMessage3":
+ return func() proto.Message { return new(googleMessage3.GoogleMessage3) }
+ case "benchmarks.google_message4.GoogleMessage4":
+ return func() proto.Message { return new(googleMessage4.GoogleMessage4) }
+ default:
+ panic("Unknown message type: " + dataset.MessageName)
+ }
+}
+
+func init() {
+ flag.Parse()
+ for _, f := range flag.Args() {
+ // Load the benchmark.
+ b, err := ioutil.ReadFile(f)
+ if err != nil {
+ panic(err)
+ }
+
+ // Parse the benchmark.
+ var dm benchmarkWrapper.BenchmarkDataset
+ if err := proto.Unmarshal(b, &dm); err != nil {
+ panic(err)
+ }
+
+ // Determine the concrete protobuf message type to use.
+ var ds Dataset
+ ds.newMessage = generateNewMessageFunction(dm)
+
+ // Unmarshal each test message.
+ for _, payload := range dm.Payload {
+ ds.marshaled = append(ds.marshaled, payload)
+ m := ds.newMessage()
+ if err := proto.Unmarshal(payload, m); err != nil {
+ panic(err)
+ }
+ ds.unmarshaled = append(ds.unmarshaled, m)
+ }
+ ds.name = f
+
+ datasets = append(datasets, ds)
+ }
+}
+
+func Benchmark(b *testing.B) {
+ for _, ds := range datasets {
+ b.Run(ds.name, func(b *testing.B) {
+ b.Run("Unmarshal", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ for j, payload := range ds.marshaled {
+ out := ds.newMessage()
+ if err := proto.Unmarshal(payload, out); err != nil {
+ b.Fatalf("can't unmarshal message %d %v", j, err)
+ }
+ }
+ }
+ })
+ b.Run("Marshal", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ for j, m := range ds.unmarshaled {
+ if _, err := proto.Marshal(m); err != nil {
+ b.Fatalf("can't marshal message %d %+v: %v", j, m, err)
+ }
+ }
+ }
+ })
+ b.Run("Size", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ for _, m := range ds.unmarshaled {
+ proto.Size(m)
+ }
+ }
+ })
+ b.Run("Clone", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ for _, m := range ds.unmarshaled {
+ proto.Clone(m)
+ }
+ }
+ })
+ b.Run("Merge", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ for _, m := range ds.unmarshaled {
+ out := ds.newMessage()
+ proto.Merge(out, m)
+ }
+ }
+ })
+ })
+ }
+}
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/ProtoBench.java b/benchmarks/java/src/main/java/com/google/protobuf/ProtoBench.java
deleted file mode 100755
index f35b180a..00000000
--- a/benchmarks/java/src/main/java/com/google/protobuf/ProtoBench.java
+++ /dev/null
@@ -1,178 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2009 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-
-package com.google.protobuf;
-
-import com.google.caliper.BeforeExperiment;
-import com.google.caliper.Benchmark;
-import com.google.caliper.Param;
-import com.google.caliper.runner.CaliperMain;
-import com.google.protobuf.ByteString;
-import com.google.protobuf.CodedInputStream;
-import com.google.protobuf.CodedOutputStream;
-import com.google.protobuf.ExtensionRegistry;
-import com.google.protobuf.Message;
-import com.google.protobuf.benchmarks.Benchmarks.BenchmarkDataset;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.EOFException;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.RandomAccessFile;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Scanner;
-
-
-public class ProtoBench {
-
- private ProtoBench() {
- // Prevent instantiation
- }
-
- public static void main(String[] args) {
- if (args.length < 1) {
- System.err.println("Usage: ./java-benchmark <input data>");
- System.err.println("input data is in the format of \"benchmarks.proto\"");
- System.exit(1);
- }
- boolean success = true;
- for (int i = 0; i < args.length; i++) {
- success &= runTest(args[i]);
- }
- System.exit(success ? 0 : 1);
- }
-
-
- /**
- * Runs a single test with specific test data. Error messages are displayed to stderr,
- * and the return value indicates general success/failure.
- */
- public static boolean runTest(String file) {
- byte[] inputData;
- BenchmarkDataset benchmarkDataset;
- try {
- inputData = readAllBytes(file);
- benchmarkDataset = BenchmarkDataset.parseFrom(inputData);
- } catch (IOException e) {
- System.err.println("Unable to get input data");
- return false;
- }
- List<String> argsList = getCaliperOption(benchmarkDataset);
- if (argsList == null) {
- System.err.println("Unable to get default message " + benchmarkDataset.getMessageName());
- return false;
- }
- argsList.add("-DdataFile=" + file);
- argsList.add("com.google.protobuf.ProtoCaliperBenchmark");
-
- try {
- String args[] = new String[argsList.size()];
- argsList.toArray(args);
- CaliperMain.exitlessMain(args,
- new PrintWriter(System.out, true), new PrintWriter(System.err, true));
- } catch (Exception e) {
- System.err.println("Error: " + e.getMessage());
- System.err.println("Detailed exception information:");
- e.printStackTrace(System.err);
- return false;
- }
- try {
- double mininumScale = 0;
- // If the file not exist, this will throw IOException, which won't print the warning
- // information below.
- Scanner scanner = new Scanner(new String(readAllBytes("JavaBenchmarkWarning.txt")));
- while (scanner.hasNext()) {
- mininumScale = Math.max(mininumScale, scanner.nextDouble());
- }
- scanner.close();
-
- System.out.println(
- "WARNING: This benchmark's whole iterations are not enough, consider to config caliper to "
- + "run for more time to make the result more convincing. You may change the configure "
- + "code in com.google.protobuf.ProtoBench.getCaliperOption() of benchmark "
- + benchmarkDataset.getMessageName()
- + " to run for more time. e.g. Change the value of "
- + "instrument.runtime.options.timingInterval or value of "
- + "instrument.runtime.options.measurements to be at least "
- + Math.round(mininumScale * 10 + 1) / 10.0
- + " times of before, then build and run the benchmark again\n");
- Files.deleteIfExists(Paths.get("JavaBenchmarkWarning.txt"));
- } catch (IOException e) {
- // The IOException here should be file not found, which means there's no warning generated by
- // The benchmark, so this IOException should be discarded.
- }
- return true;
- }
-
-
- private static List<String> getCaliperOption(final BenchmarkDataset benchmarkDataset) {
- List<String> temp = new ArrayList<String>();
- if (benchmarkDataset.getMessageName().equals("benchmarks.proto3.GoogleMessage1")) {
- } else if (benchmarkDataset.getMessageName().equals("benchmarks.proto2.GoogleMessage1")) {
- } else if (benchmarkDataset.getMessageName().equals("benchmarks.proto2.GoogleMessage2")) {
- } else if (benchmarkDataset.getMessageName().
- equals("benchmarks.google_message3.GoogleMessage3")) {
- temp.add("-Cinstrument.runtime.options.timingInterval=3000ms");
- temp.add("-Cinstrument.runtime.options.measurements=20");
- } else if (benchmarkDataset.getMessageName().
- equals("benchmarks.google_message4.GoogleMessage4")) {
- temp.add("-Cinstrument.runtime.options.timingInterval=1500ms");
- temp.add("-Cinstrument.runtime.options.measurements=20");
- } else {
- return null;
- }
-
- temp.add("-i");
- temp.add("runtime");
- temp.add("-b");
- String benchmarkNames = "serializeToByteString,serializeToByteArray,serializeToMemoryStream"
- + ",deserializeFromByteString,deserializeFromByteArray,deserializeFromMemoryStream";
- temp.add(benchmarkNames);
-
- return temp;
- }
-
- public static byte[] readAllBytes(String filename) throws IOException {
- if (filename.equals("")) {
- return new byte[0];
- }
- RandomAccessFile file = new RandomAccessFile(new File(filename), "r");
- byte[] content = new byte[(int) file.length()];
- file.readFully(content);
- return content;
- }
-}
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 7dff16dc..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 {
@@ -99,7 +106,6 @@ public class ProtoCaliperBenchmark {
private List<ByteArrayInputStream> inputStreamList;
private List<ByteString> inputStringList;
private List<Message> sampleMessageList;
- private long counter;
private BenchmarkMessageType getMessageType() throws IOException {
if (benchmarkDataset.getMessageName().equals("benchmarks.proto3.GoogleMessage1")) {
@@ -149,30 +155,18 @@ public class ProtoCaliperBenchmark {
sampleMessageList.add(
defaultMessage.newBuilderForType().mergeFrom(singleInputData, extensions).build());
}
-
- counter = 0;
}
@Benchmark
- void serializeToByteString(int reps) throws IOException {
- if (sampleMessageList.size() == 0) {
- return;
- }
- for (int i = 0; i < reps; i++) {
- sampleMessageList.get((int) (counter % sampleMessageList.size())).toByteString();
- counter++;
- }
- }
-
- @Benchmark
void serializeToByteArray(int reps) throws IOException {
if (sampleMessageList.size() == 0) {
return;
}
for (int i = 0; i < reps; i++) {
- sampleMessageList.get((int) (counter % sampleMessageList.size())).toByteArray();
- counter++;
+ for (int j = 0; j < sampleMessageList.size(); j++) {
+ sampleMessageList.get(j).toByteArray();
+ }
}
}
@@ -182,21 +176,10 @@ public class ProtoCaliperBenchmark {
return;
}
for (int i = 0; i < reps; i++) {
- ByteArrayOutputStream output = new ByteArrayOutputStream();
- sampleMessageList.get((int) (counter % sampleMessageList.size())).writeTo(output);
- counter++;
- }
- }
-
- @Benchmark
- void deserializeFromByteString(int reps) throws IOException {
- if (inputStringList.size() == 0) {
- return;
- }
- for (int i = 0; i < reps; i++) {
- benchmarkMessageType.getDefaultInstance().getParserForType().parseFrom(
- inputStringList.get((int) (counter % inputStringList.size())), extensions);
- counter++;
+ for (int j = 0; j < sampleMessageList.size(); j++) {
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ sampleMessageList.get(j).writeTo(output);
+ }
}
}
@@ -206,9 +189,10 @@ public class ProtoCaliperBenchmark {
return;
}
for (int i = 0; i < reps; i++) {
- benchmarkMessageType.getDefaultInstance().getParserForType().parseFrom(
- inputDataList.get((int) (counter % inputDataList.size())), extensions);
- counter++;
+ for (int j = 0; j < inputDataList.size(); j++) {
+ benchmarkMessageType.getDefaultInstance().getParserForType().parseFrom(
+ inputDataList.get(j), extensions);
+ }
}
}
@@ -218,28 +202,13 @@ public class ProtoCaliperBenchmark {
return;
}
for (int i = 0; i < reps; i++) {
- benchmarkMessageType.getDefaultInstance().getParserForType().parseFrom(
- inputStreamList.get((int) (counter % inputStreamList.size())), extensions);
- inputStreamList.get((int) (counter % inputStreamList.size())).reset();
- counter++;
- }
- }
-
- @AfterExperiment
- void checkCounter() throws IOException {
- if (counter == 1) {
- // Dry run
- return;
- }
- if (benchmarkDataset.getPayloadCount() != 1
- && counter < benchmarkDataset.getPayloadCount() * 10L) {
- BufferedWriter writer = new BufferedWriter(new FileWriter("JavaBenchmarkWarning.txt", true));
- // If the total number of non-warmup reps is smaller than 100 times of the total number of
- // datasets, then output the scale that need to multiply to the configuration (either extend
- // the running time for one timingInterval or run for more measurements).
- writer.append(1.0 * benchmarkDataset.getPayloadCount() * 10L / counter + " ");
- writer.close();
+ for (int j = 0; j < inputStreamList.size(); j++) {
+ benchmarkMessageType.getDefaultInstance().getParserForType().parseFrom(
+ inputStreamList.get(j), extensions);
+ inputStreamList.get(j).reset();
+ }
}
}
}
+
diff --git a/benchmarks/python/__init__.py b/benchmarks/python/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/benchmarks/python/__init__.py
diff --git a/benchmarks/py_benchmark.py b/benchmarks/python/py_benchmark.py
index 48234f03..e86b61e7 100755
--- a/benchmarks/py_benchmark.py
+++ b/benchmarks/python/py_benchmark.py
@@ -1,24 +1,39 @@
+from __future__ import print_function
import sys
import os
import timeit
import math
+import argparse
import fnmatch
-
+import json
+
+parser = argparse.ArgumentParser(description="Python protobuf benchmark")
+parser.add_argument("data_files", metavar="dataFile", nargs="+",
+ help="testing data files.")
+parser.add_argument("--json", action="store_const", dest="json",
+ const="yes", default="no",
+ help="Whether to output json results")
+parser.add_argument("--behavior_prefix", dest="behavior_prefix",
+ help="The output json format's behavior's name's prefix",
+ default="")
+# BEGIN CPP GENERATED MESSAGE
+parser.add_argument("--cpp_generated", action="store_const",
+ dest="cpp_generated", const="yes", default="no",
+ help="Whether to link generated code library")
+# END CPP GENERATED MESSAGE
+args = parser.parse_args()
# BEGIN CPP GENERATED MESSAGE
# CPP generated code must be linked before importing the generated Python code
# for the descriptor can be found in the pool
-if len(sys.argv) < 2:
- raise IOError("Need string argument \"true\" or \"false\" for whether to use cpp generated code")
-if sys.argv[1] == "true":
+if args.cpp_generated != "no":
sys.path.append( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) + "/.libs" )
import libbenchmark_messages
sys.path.append( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) + "/tmp" )
-elif sys.argv[1] != "false":
- raise IOError("Need string argument \"true\" or \"false\" for whether to use cpp generated code")
# END CPP GENERATED MESSAGE
-import datasets.google_message1.benchmark_message1_proto2_pb2 as benchmark_message1_proto2_pb2
-import datasets.google_message1.benchmark_message1_proto3_pb2 as benchmark_message1_proto3_pb2
+
+import datasets.google_message1.proto2.benchmark_message1_proto2_pb2 as benchmark_message1_proto2_pb2
+import datasets.google_message1.proto3.benchmark_message1_proto3_pb2 as benchmark_message1_proto3_pb2
import datasets.google_message2.benchmark_message2_pb2 as benchmark_message2_pb2
import datasets.google_message3.benchmark_message3_pb2 as benchmark_message3_pb2
import datasets.google_message4.benchmark_message4_pb2 as benchmark_message4_pb2
@@ -26,19 +41,24 @@ import benchmarks_pb2 as benchmarks_pb2
def run_one_test(filename):
- data = open(os.path.dirname(sys.argv[0]) + "/../" + filename).read()
+ data = open(filename).read()
benchmark_dataset = benchmarks_pb2.BenchmarkDataset()
benchmark_dataset.ParseFromString(data)
benchmark_util = Benchmark(full_iteration=len(benchmark_dataset.payload),
module="py_benchmark",
setup_method="init")
- print "Message %s of dataset file %s" % \
- (benchmark_dataset.message_name, filename)
+ result={}
+ result["filename"] = filename
+ result["message_name"] = benchmark_dataset.message_name
+ result["benchmarks"] = {}
benchmark_util.set_test_method("parse_from_benchmark")
- print benchmark_util.run_benchmark(setup_method_args='"%s"' % (filename))
+ result["benchmarks"][args.behavior_prefix + "_parse_from_benchmark"] = \
+ benchmark_util.run_benchmark(setup_method_args='"%s"' % (filename))
benchmark_util.set_test_method("serialize_to_benchmark")
- print benchmark_util.run_benchmark(setup_method_args='"%s"' % (filename))
- print ""
+ result["benchmarks"][args.behavior_prefix + "_serialize_to_benchmark"] = \
+ benchmark_util.run_benchmark(setup_method_args='"%s"' % (filename))
+ return result
+
def init(filename):
global benchmark_dataset, message_class, message_list, counter
@@ -66,11 +86,13 @@ def init(filename):
temp.ParseFromString(one_payload)
message_list.append(temp)
+
def parse_from_benchmark():
global counter, message_class, benchmark_dataset
m = message_class().ParseFromString(benchmark_dataset.payload[counter % len(benchmark_dataset.payload)])
counter = counter + 1
+
def serialize_to_benchmark():
global counter, message_list, message_class
s = message_list[counter % len(benchmark_dataset.payload)].SerializeToString()
@@ -108,10 +130,24 @@ class Benchmark:
t = timeit.timeit(stmt="%s(%s)" % (self.test_method, test_method_args),
setup=self.full_setup_code(setup_method_args),
number=reps);
- return "Average time for %s: %.2f ns" % \
- (self.test_method, 1.0 * t / reps * (10 ** 9))
-
+ return 1.0 * t / reps * (10 ** 9)
+
if __name__ == "__main__":
- for i in range(2, len(sys.argv)):
- run_one_test(sys.argv[i])
+ results = []
+ for file in args.data_files:
+ results.append(run_one_test(file))
+
+ if args.json != "no":
+ 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" % \
+ (result["benchmarks"][ \
+ args.behavior_prefix + "_parse_from_benchmark"]))
+ print("Average time for serialize_to_benchmark: %.2f ns" % \
+ (result["benchmarks"][ \
+ args.behavior_prefix + "_serialize_to_benchmark"]))
+ print("")
diff --git a/benchmarks/python_benchmark_messages.cc b/benchmarks/python/python_benchmark_messages.cc
index 55242a2a..ded16fe9 100644
--- a/benchmarks/python_benchmark_messages.cc
+++ b/benchmarks/python/python_benchmark_messages.cc
@@ -1,8 +1,8 @@
#include <Python.h>
#include "benchmarks.pb.h"
-#include "datasets/google_message1/benchmark_message1_proto2.pb.h"
-#include "datasets/google_message1/benchmark_message1_proto3.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"
diff --git a/benchmarks/util/__init__.py b/benchmarks/util/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/benchmarks/util/__init__.py
diff --git a/benchmarks/util/big_query_utils.py b/benchmarks/util/big_query_utils.py
new file mode 100755
index 00000000..aea55bbd
--- /dev/null
+++ b/benchmarks/util/big_query_utils.py
@@ -0,0 +1,189 @@
+#!/usr/bin/env python2.7
+
+from __future__ import print_function
+import argparse
+import json
+import uuid
+import httplib2
+
+from apiclient import discovery
+from apiclient.errors import HttpError
+from oauth2client.client import GoogleCredentials
+
+# 30 days in milliseconds
+_EXPIRATION_MS = 30 * 24 * 60 * 60 * 1000
+NUM_RETRIES = 3
+
+
+def create_big_query():
+ """Authenticates with cloud platform and gets a BiqQuery service object
+ """
+ creds = GoogleCredentials.get_application_default()
+ return discovery.build(
+ 'bigquery', 'v2', credentials=creds, cache_discovery=False)
+
+
+def create_dataset(biq_query, project_id, dataset_id):
+ is_success = True
+ body = {
+ 'datasetReference': {
+ 'projectId': project_id,
+ 'datasetId': dataset_id
+ }
+ }
+
+ try:
+ dataset_req = biq_query.datasets().insert(
+ projectId=project_id, body=body)
+ 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)
+ else:
+ # Note: For more debugging info, print "http_error.content"
+ print('Error in creating dataset: %s. Err: %s' % (dataset_id,
+ http_error))
+ is_success = False
+ return is_success
+
+
+def create_table(big_query, project_id, dataset_id, table_id, table_schema,
+ description):
+ fields = [{
+ 'name': field_name,
+ 'type': field_type,
+ 'description': field_description
+ } for (field_name, field_type, field_description) in table_schema]
+ return create_table2(big_query, project_id, dataset_id, table_id, fields,
+ description)
+
+
+def create_partitioned_table(big_query,
+ project_id,
+ dataset_id,
+ table_id,
+ table_schema,
+ description,
+ partition_type='DAY',
+ expiration_ms=_EXPIRATION_MS):
+ """Creates a partitioned table. By default, a date-paritioned table is created with
+ each partition lasting 30 days after it was last modified.
+ """
+ fields = [{
+ 'name': field_name,
+ 'type': field_type,
+ 'description': field_description
+ } for (field_name, field_type, field_description) in table_schema]
+ return create_table2(big_query, project_id, dataset_id, table_id, fields,
+ description, partition_type, expiration_ms)
+
+
+def create_table2(big_query,
+ project_id,
+ dataset_id,
+ table_id,
+ fields_schema,
+ description,
+ partition_type=None,
+ expiration_ms=None):
+ is_success = True
+
+ body = {
+ 'description': description,
+ 'schema': {
+ 'fields': fields_schema
+ },
+ 'tableReference': {
+ 'datasetId': dataset_id,
+ 'projectId': project_id,
+ 'tableId': table_id
+ }
+ }
+
+ if partition_type and expiration_ms:
+ body["timePartitioning"] = {
+ "type": partition_type,
+ "expirationMs": expiration_ms
+ }
+
+ try:
+ 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']))
+ except HttpError as http_error:
+ if http_error.resp.status == 409:
+ print('Warning: Table %s already exists' % table_id)
+ else:
+ print('Error in creating table: %s. Err: %s' % (table_id,
+ http_error))
+ is_success = False
+ return is_success
+
+
+def patch_table(big_query, project_id, dataset_id, table_id, fields_schema):
+ is_success = True
+
+ body = {
+ 'schema': {
+ 'fields': fields_schema
+ },
+ 'tableReference': {
+ 'datasetId': dataset_id,
+ 'projectId': project_id,
+ 'tableId': table_id
+ }
+ }
+
+ try:
+ table_req = big_query.tables().patch(
+ projectId=project_id,
+ datasetId=dataset_id,
+ tableId=table_id,
+ body=body)
+ res = table_req.execute(num_retries=NUM_RETRIES)
+ 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))
+ is_success = False
+ return is_success
+
+
+def insert_rows(big_query, project_id, dataset_id, table_id, rows_list):
+ is_success = True
+ body = {'rows': rows_list}
+ try:
+ insert_req = big_query.tabledata().insertAll(
+ projectId=project_id,
+ datasetId=dataset_id,
+ tableId=table_id,
+ body=body)
+ res = insert_req.execute(num_retries=NUM_RETRIES)
+ if res.get('insertErrors', None):
+ 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)
+ is_success = False
+
+ return is_success
+
+
+def sync_query_job(big_query, project_id, query, timeout=5000):
+ query_data = {'query': query, 'timeoutMs': timeout}
+ query_job = None
+ try:
+ query_job = big_query.jobs().query(
+ 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)
+ return query_job
+
+
+ # List of (column name, column type, description) tuples
+def make_row(unique_row_id, row_values_dict):
+ """row_values_dict is a dictionary of column name and column value.
+ """
+ return {'insertId': unique_row_id, 'json': row_values_dict}
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
new file mode 100644
index 00000000..9ef57b0d
--- /dev/null
+++ b/benchmarks/util/gogo_data_scrubber.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::GogoDataStripper;
+
+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));
+ GogoDataStripper 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/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
new file mode 100644
index 00000000..9c1b3d04
--- /dev/null
+++ b/benchmarks/util/protoc-gen-gogoproto.cc
@@ -0,0 +1,103 @@
+#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;
+
+namespace google {
+namespace protobuf {
+namespace compiler {
+
+namespace {
+
+string StripProto(string filename) {
+ if (filename.substr(filename.size() - 11) == ".protodevel") {
+ // .protodevel
+ return filename.substr(0, filename.size() - 11);
+ } else {
+ // .proto
+ return filename.substr(0, filename.size() - 6);
+ }
+}
+
+DescriptorPool new_pool_;
+
+} // namespace
+
+class GoGoProtoGenerator : public CodeGenerator {
+ public:
+ virtual 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) {
+ bool can_generate =
+ (new_pool_.FindFileByName(file->name()) == nullptr);
+ for (int j = 0; j < file->dependency_count(); j++) {
+ can_generate &= (new_pool_.FindFileByName(
+ file->dependency(j)->name()) != nullptr);
+ }
+ for (int j = 0; j < file->public_dependency_count(); j++) {
+ can_generate &= (new_pool_.FindFileByName(
+ file->public_dependency(j)->name()) != nullptr);
+ }
+ for (int j = 0; j < file->weak_dependency_count(); j++) {
+ can_generate &= (new_pool_.FindFileByName(
+ file->weak_dependency(j)->name()) != nullptr);
+ }
+ if (can_generate) {
+ Generate(file, parameter, context, error);
+ break;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ virtual 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);
+
+ 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 = new_pool_.BuildFile(new_file)->DebugString();
+ Printer printer(output.get(), '$');
+ printer.WriteRaw(content.c_str(), content.size());
+
+ return true;
+ }
+};
+
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
+
+int main(int argc, char* argv[]) {
+ google::protobuf::compiler::GoGoProtoGenerator generator;
+ return google::protobuf::compiler::PluginMain(argc, argv, &generator);
+}
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/run_and_upload.py
new file mode 100755
index 00000000..43c9fa2d
--- /dev/null
+++ b/benchmarks/util/run_and_upload.py
@@ -0,0 +1,292 @@
+from __future__ import print_function
+from __future__ import absolute_import
+import argparse
+import os
+import re
+import copy
+import uuid
+import calendar
+import time
+from . 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
+sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
+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 = {}
+
+def get_data_size(file_name):
+ if file_name in file_size_map:
+ return file_size_map[file_name]
+ benchmark_dataset = benchmarks_pb2.BenchmarkDataset()
+ benchmark_dataset.ParseFromString(
+ open(os.path.dirname(os.path.abspath(__file__)) + "/../" + file_name).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)
+ return size, 1.0 * size / count
+
+
+def extract_file_name(file_name):
+ name_list = re.split("[/\.]", file_name)
+ short_file_name = ""
+ for name in name_list:
+ if name[:14] == "google_message":
+ short_file_name = name
+ return short_file_name
+
+
+cpp_result = []
+python_result = []
+java_result = []
+go_result = []
+
+
+# CPP results example:
+# [
+# "benchmarks": [
+# {
+# "bytes_per_second": int,
+# "cpu_time": int,
+# "name: string,
+# "time_unit: string,
+# ...
+# },
+# ...
+# ],
+# ...
+# ]
+def parse_cpp_result(filename):
+ global cpp_result
+ 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"]:
+ data_filename = "".join(
+ re.split("(_parse_|_serialize)", benchmark["name"])[0])
+ behavior = benchmark["name"][len(data_filename) + 1:]
+ cpp_result.append({
+ "language": "cpp",
+ "dataFileName": data_filename,
+ "behavior": behavior,
+ "throughput": benchmark["bytes_per_second"] / 2.0 ** 20
+ })
+
+
+# Python results example:
+# [
+# [
+# {
+# "filename": string,
+# "benchmarks": {
+# behavior: results,
+# ...
+# },
+# "message_name": STRING
+# },
+# ...
+# ], #pure-python
+# ...
+# ]
+def parse_python_result(filename):
+ global python_result
+ if filename == "":
+ return
+ if filename[0] != '/':
+ filename = os.path.dirname(os.path.abspath(__file__)) + '/' + filename
+ with open(filename) as f:
+ results_list = json.loads(f.read())
+ for results in results_list:
+ for result in results:
+ _, avg_size = get_data_size(result["filename"])
+ for behavior in result["benchmarks"]:
+ python_result.append({
+ "language": "python",
+ "dataFileName": extract_file_name(result["filename"]),
+ "behavior": behavior,
+ "throughput": avg_size /
+ result["benchmarks"][behavior] * 1e9 / 2 ** 20
+ })
+
+
+# Java results example:
+# [
+# {
+# "id": string,
+# "instrumentSpec": {...},
+# "measurements": [
+# {
+# "weight": float,
+# "value": {
+# "magnitude": float,
+# "unit": string
+# },
+# ...
+# },
+# ...
+# ],
+# "run": {...},
+# "scenario": {
+# "benchmarkSpec": {
+# "methodName": string,
+# "parameters": {
+# defined parameters in the benchmark: parameters value
+# },
+# ...
+# },
+# ...
+# }
+#
+# },
+# ...
+# ]
+def parse_java_result(filename):
+ global average_bytes_per_message, java_result
+ 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 result in results:
+ total_weight = 0
+ total_value = 0
+ for measurement in result["measurements"]:
+ total_weight += measurement["weight"]
+ total_value += measurement["value"]["magnitude"]
+ avg_time = total_value * 1.0 / total_weight
+ total_size, _ = get_data_size(
+ result["scenario"]["benchmarkSpec"]["parameters"]["dataFile"])
+ java_result.append({
+ "language": "java",
+ "throughput": total_size / avg_time * 1e9 / 2 ** 20,
+ "behavior": result["scenario"]["benchmarkSpec"]["methodName"],
+ "dataFileName": extract_file_name(
+ result["scenario"]["benchmarkSpec"]["parameters"]["dataFile"])
+ })
+
+
+# Go benchmark results:
+#
+# goos: linux
+# goarch: amd64
+# Benchmark/.././datasets/google_message2/dataset.google_message2.pb/Unmarshal-12 3000 705784 ns/op
+# Benchmark/.././datasets/google_message2/dataset.google_message2.pb/Marshal-12 2000 634648 ns/op
+# Benchmark/.././datasets/google_message2/dataset.google_message2.pb/Size-12 5000 244174 ns/op
+# Benchmark/.././datasets/google_message2/dataset.google_message2.pb/Clone-12 300 4120954 ns/op
+# 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
+ if filename == "":
+ return
+ if filename[0] != '/':
+ filename = os.path.dirname(os.path.abspath(__file__)) + '/' + filename
+ with open(filename) as f:
+ for line in f:
+ result_list = re.split("[\ \t]+", line)
+ if result_list[0][:9] != "Benchmark":
+ continue
+ 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)
+ 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),
+ "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)
+
+ 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)
diff --git a/benchmarks/util/schema_proto2_to_proto3_util.h b/benchmarks/util/schema_proto2_to_proto3_util.h
new file mode 100644
index 00000000..0079f6f1
--- /dev/null
+++ b/benchmarks/util/schema_proto2_to_proto3_util.h
@@ -0,0 +1,194 @@
+#ifndef PROTOBUF_BENCHMARKS_UTIL_SCHEMA_PROTO2_TO_PROTO3_UTIL_H_
+#define PROTOBUF_BENCHMARKS_UTIL_SCHEMA_PROTO2_TO_PROTO3_UTIL_H_
+
+#include "google/protobuf/message.h"
+#include "google/protobuf/descriptor.h"
+#include "google/protobuf/descriptor.pb.h"
+
+#include <sstream>
+#include <algorithm>
+
+using google::protobuf::Descriptor;
+using google::protobuf::DescriptorProto;
+using google::protobuf::FileDescriptorProto;
+using google::protobuf::FieldDescriptorProto;
+using google::protobuf::Message;
+using google::protobuf::EnumValueDescriptorProto;
+
+namespace google {
+namespace protobuf {
+namespace util {
+
+class SchemaGroupStripper {
+
+ public:
+ static void StripFile(const FileDescriptor* old_file,
+ FileDescriptorProto *file) {
+ for (int i = file->mutable_message_type()->size() - 1; i >= 0; i--) {
+ if (IsMessageSet(old_file->message_type(i))) {
+ file->mutable_message_type()->DeleteSubrange(i, 1);
+ continue;
+ }
+ StripMessage(old_file->message_type(i), file->mutable_message_type(i));
+ }
+ for (int i = file->mutable_extension()->size() - 1; i >= 0; i--) {
+ auto field = old_file->extension(i);
+ if (field->type() == FieldDescriptor::TYPE_GROUP ||
+ IsMessageSet(field->message_type()) ||
+ IsMessageSet(field->containing_type())) {
+ file->mutable_extension()->DeleteSubrange(i, 1);
+ }
+ }
+ }
+
+ private:
+ static bool IsMessageSet(const Descriptor *descriptor) {
+ if (descriptor != nullptr
+ && descriptor->options().message_set_wire_format()) {
+ return true;
+ }
+ return false;
+ }
+
+ static void StripMessage(const Descriptor *old_message,
+ DescriptorProto *new_message) {
+ for (int i = new_message->mutable_field()->size() - 1; i >= 0; i--) {
+ if (old_message->field(i)->type() == FieldDescriptor::TYPE_GROUP ||
+ IsMessageSet(old_message->field(i)->message_type())) {
+ new_message->mutable_field()->DeleteSubrange(i, 1);
+ }
+ }
+ for (int i = new_message->mutable_extension()->size() - 1; i >= 0; i--) {
+ auto field_type_name = new_message->mutable_extension(i)->type_name();
+ if (old_message->extension(i)->type() == FieldDescriptor::TYPE_GROUP ||
+ IsMessageSet(old_message->extension(i)->containing_type()) ||
+ IsMessageSet(old_message->extension(i)->message_type())) {
+ new_message->mutable_extension()->DeleteSubrange(i, 1);
+ }
+ }
+ for (int i = 0; i < new_message->mutable_nested_type()->size(); i++) {
+ StripMessage(old_message->nested_type(i),
+ new_message->mutable_nested_type(i));
+ }
+ }
+
+};
+
+class EnumScrubber {
+
+ public:
+ EnumScrubber()
+ : total_added_(0) {
+ }
+
+ void ScrubFile(FileDescriptorProto *file) {
+ for (int i = 0; i < file->enum_type_size(); i++) {
+ ScrubEnum(file->mutable_enum_type(i));
+ }
+ for (int i = 0; i < file->mutable_message_type()->size(); i++) {
+ ScrubMessage(file->mutable_message_type(i));
+ }
+ }
+
+ private:
+ void ScrubEnum(EnumDescriptorProto *enum_type) {
+ if (enum_type->value(0).number() != 0) {
+ bool has_zero = false;
+ for (int j = 0; j < enum_type->value().size(); j++) {
+ if (enum_type->value(j).number() == 0) {
+ EnumValueDescriptorProto temp_enum_value;
+ temp_enum_value.CopyFrom(enum_type->value(j));
+ enum_type->mutable_value(j)->CopyFrom(enum_type->value(0));
+ enum_type->mutable_value(0)->CopyFrom(temp_enum_value);
+ has_zero = true;
+ break;
+ }
+ }
+ if (!has_zero) {
+ enum_type->mutable_value()->Add();
+ for (int i = enum_type->mutable_value()->size() - 1; i > 0; i--) {
+ enum_type->mutable_value(i)->CopyFrom(
+ *enum_type->mutable_value(i - 1));
+ }
+ enum_type->mutable_value(0)->set_number(0);
+ enum_type->mutable_value(0)->set_name("ADDED_ZERO_VALUE_" +
+ std::to_string(total_added_++));
+ }
+ }
+
+ }
+
+ void ScrubMessage(DescriptorProto *message_type) {
+ for (int i = 0; i < message_type->mutable_enum_type()->size(); i++) {
+ ScrubEnum(message_type->mutable_enum_type(i));
+ }
+ for (int i = 0; i < message_type->mutable_nested_type()->size(); i++) {
+ ScrubMessage(message_type->mutable_nested_type(i));
+ }
+ }
+
+ 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
+
+#endif // PROTOBUF_BENCHMARKS_UTIL_SCHEMA_PROTO2_TO_PROTO3_UTIL_H_
diff --git a/cmake/CMakeLists.txt b/cmake/CMakeLists.txt
index bf3f8863..ece39f7f 100644
--- a/cmake/CMakeLists.txt
+++ b/cmake/CMakeLists.txt
@@ -1,5 +1,5 @@
# Minimum CMake required
-cmake_minimum_required(VERSION 2.8.12)
+cmake_minimum_required(VERSION 3.1.3)
if(protobuf_VERBOSE)
message(STATUS "Protocol Buffers Configuring...")
@@ -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()
@@ -15,6 +19,15 @@ endif()
# Project
project(protobuf C CXX)
+# Add c++11 flags
+if (CYGWIN)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")
+else()
+ set(CMAKE_CXX_STANDARD 11)
+ set(CMAKE_CXX_STANDARD_REQUIRED ON)
+ set(CMAKE_CXX_EXTENSIONS OFF)
+endif()
+
# Options
option(protobuf_BUILD_TESTS "Build tests" ON)
option(protobuf_BUILD_EXAMPLES "Build examples" OFF)
@@ -157,12 +170,23 @@ if (MSVC)
add_definitions(/bigobj)
string(REPLACE "/" "\\" PROTOBUF_SOURCE_WIN32_PATH ${protobuf_SOURCE_DIR})
string(REPLACE "/" "\\" PROTOBUF_BINARY_WIN32_PATH ${protobuf_BINARY_DIR})
+ string(REPLACE "." "," protobuf_RC_FILEVERSION "${protobuf_VERSION}")
configure_file(extract_includes.bat.in extract_includes.bat)
-
+
# Suppress linker warnings about files with no symbols defined.
set(CMAKE_STATIC_LINKER_FLAGS /ignore:4221)
+
+ # Configure Resource Compiler
+ enable_language(RC)
+ # use English language (0x409) in resource compiler
+ set(rc_flags "/l0x409")
+ # fix rc.exe invocations because of usage of add_definitions()
+ set(CMAKE_RC_COMPILE_OBJECT "<CMAKE_RC_COMPILER> ${rc_flags} <DEFINES> /fo<OBJECT> <SOURCE>")
+
+ configure_file(version.rc.in ${CMAKE_CURRENT_BINARY_DIR}/version.rc @ONLY)
endif (MSVC)
+
get_filename_component(protobuf_source_dir ${protobuf_SOURCE_DIR} PATH)
include_directories(
diff --git a/cmake/README.md b/cmake/README.md
index 1e7410d8..26a516c7 100644
--- a/cmake/README.md
+++ b/cmake/README.md
@@ -41,9 +41,16 @@ Good. Now you are ready to continue.
Getting Sources
===============
-You can get the latest stable source packages from the
-[releases](https://github.com/google/protobuf/releases) page.
-Or you can type:
+You can get the latest stable source packages from the release page:
+
+ https://github.com/google/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
+contains C++ source already); if you need C++ and multiple other languages,
+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
@@ -55,26 +62,16 @@ Go to the project folder:
C:\Path\to>cd protobuf
C:\Path\to\protobuf>
-Protobuf unit-tests require gmock to build. If you download protobuf source code
-from the *releases* page, the *gmock* directory should already be there. If you checkout
-the code via `git clone`, this *gmock* directory won't exist and you will have to
-download it manually or skip building protobuf unit-tests.
-
-You can download gmock as follows:
+Remember to update any submodules if you are using git clone (you can skip this
+step if you are using a release .tar.gz or .zip package):
- C:\Path\to\protobuf>git clone -b release-1.7.0 https://github.com/google/googlemock.git gmock
-
-Then go to *gmock* folder and download gtest:
-
- C:\Path\to\protobuf>cd gmock
- C:\Path\to\protobuf\gmock>git clone -b release-1.7.0 https://github.com/google/googletest.git gtest
-
-If you absolutely don't want to build and run protobuf unit-tests, skip
-this steps and use protobuf at your own risk.
+```console
+C:\Path\to> git submodule update --init --recursive
+```
Now go to *cmake* folder in protobuf sources:
- C:\Path\to\protobuf\gmock>cd ..\cmake
+ C:\Path\to\protobuf>cd cmake
C:\Path\to\protobuf\cmake>
Good. Now you are ready to *CMake* configuration.
@@ -124,7 +121,7 @@ It will generate *nmake* *Makefile* in current directory.
To create *Visual Studio* solution file:
C:\Path\to\protobuf\cmake\build>mkdir solution & cd solution
- C:\Path\to\protobuf\cmake\build\solution>cmake -G "Visual Studio 12 2013 Win64" ^
+ C:\Path\to\protobuf\cmake\build\solution>cmake -G "Visual Studio 14 2015 Win64" ^
-DCMAKE_INSTALL_PREFIX=../../../../install ^
../..
@@ -302,6 +299,11 @@ further disable the option `-Dprotobuf_MSVC_STATIC_RUNTIME=OFF`.
If it reports NOTFOUND for zlib_include or zlib_lib, you might haven't put
the headers or the .lib file in the right directory.
+If you already have ZLIB library and headers at some other location on your system then alternatively you can define following configuration flags to locate them:
+
+ -DZLIB_INCLUDE_DIR=<path to dir containing zlib headers>
+ -DZLIB_LIB=<path to dir containing zlib>
+
Build and testing protobuf as usual.
Notes on Compiler Warnings
diff --git a/cmake/extract_includes.bat.in b/cmake/extract_includes.bat.in
index 5178f5b2..9fd9de0d 100644
--- a/cmake/extract_includes.bat.in
+++ b/cmake/extract_includes.bat.in
@@ -5,7 +5,6 @@ mkdir include\google\protobuf\compiler
mkdir include\google\protobuf\compiler\cpp
mkdir include\google\protobuf\compiler\csharp
mkdir include\google\protobuf\compiler\java
-mkdir include\google\protobuf\compiler\javanano
mkdir include\google\protobuf\compiler\js
mkdir include\google\protobuf\compiler\objectivec
mkdir include\google\protobuf\compiler\php
@@ -28,7 +27,6 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\csharp\cshar
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\importer.h" include\google\protobuf\compiler\importer.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\java_generator.h" include\google\protobuf\compiler\java\java_generator.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\java_names.h" include\google\protobuf\compiler\java\java_names.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\javanano\javanano_generator.h" include\google\protobuf\compiler\javanano\javanano_generator.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\js\js_generator.h" include\google\protobuf\compiler\js\js_generator.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\js\well_known_types_embed.h" include\google\protobuf\compiler\js\well_known_types_embed.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\objectivec\objectivec_generator.h" include\google\protobuf\compiler\objectivec\objectivec_generator.h
@@ -54,6 +52,7 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_message_tab
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_message_util.h" include\google\protobuf\generated_message_util.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\has_bits.h" include\google\protobuf\has_bits.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\implicit_weak_message.h" include\google\protobuf\implicit_weak_message.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\inlined_string_field.h" include\google\protobuf\inlined_string_field.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\coded_stream.h" include\google\protobuf\io\coded_stream.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\gzip_stream.h" include\google\protobuf\io\gzip_stream.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\printer.h" include\google\protobuf\io\printer.h
@@ -79,20 +78,6 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\repeated_field.h" inc
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\service.h" include\google\protobuf\service.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\source_context.pb.h" include\google\protobuf\source_context.pb.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\struct.pb.h" include\google\protobuf\struct.pb.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomic_sequence_num.h" include\google\protobuf\stubs\atomic_sequence_num.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops.h" include\google\protobuf\stubs\atomicops.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_arm64_gcc.h" include\google\protobuf\stubs\atomicops_internals_arm64_gcc.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_arm_gcc.h" include\google\protobuf\stubs\atomicops_internals_arm_gcc.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_arm_qnx.h" include\google\protobuf\stubs\atomicops_internals_arm_qnx.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_generic_c11_atomic.h" include\google\protobuf\stubs\atomicops_internals_generic_c11_atomic.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_generic_gcc.h" include\google\protobuf\stubs\atomicops_internals_generic_gcc.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_mips_gcc.h" include\google\protobuf\stubs\atomicops_internals_mips_gcc.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_power.h" include\google\protobuf\stubs\atomicops_internals_power.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_ppc_gcc.h" include\google\protobuf\stubs\atomicops_internals_ppc_gcc.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_solaris.h" include\google\protobuf\stubs\atomicops_internals_solaris.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_tsan.h" include\google\protobuf\stubs\atomicops_internals_tsan.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_x86_gcc.h" include\google\protobuf\stubs\atomicops_internals_x86_gcc.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_x86_msvc.h" include\google\protobuf\stubs\atomicops_internals_x86_msvc.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\bytestream.h" include\google\protobuf\stubs\bytestream.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\callback.h" include\google\protobuf\stubs\callback.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\casts.h" include\google\protobuf\stubs\casts.h
@@ -105,14 +90,11 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\mutex.h" includ
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\once.h" include\google\protobuf\stubs\once.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\platform_macros.h" include\google\protobuf\stubs\platform_macros.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\port.h" include\google\protobuf\stubs\port.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\scoped_ptr.h" include\google\protobuf\stubs\scoped_ptr.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\shared_ptr.h" include\google\protobuf\stubs\shared_ptr.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\singleton.h" include\google\protobuf\stubs\singleton.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\status.h" include\google\protobuf\stubs\status.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\stl_util.h" include\google\protobuf\stubs\stl_util.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\stringpiece.h" include\google\protobuf\stubs\stringpiece.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\template_util.h" include\google\protobuf\stubs\template_util.h
-copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\type_traits.h" include\google\protobuf\stubs\type_traits.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\text_format.h" include\google\protobuf\text_format.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\timestamp.pb.h" include\google\protobuf\timestamp.pb.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\type.pb.h" include\google\protobuf\type.pb.h
@@ -129,3 +111,15 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wire_format.h" includ
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wire_format_lite.h" include\google\protobuf\wire_format_lite.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wire_format_lite_inl.h" include\google\protobuf\wire_format_lite_inl.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wrappers.pb.h" include\google\protobuf\wrappers.pb.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\any.proto" include\google\protobuf\any.proto
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\api.proto" include\google\protobuf\api.proto
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\plugin.proto" include\google\protobuf\compiler\plugin.proto
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\descriptor.proto" include\google\protobuf\descriptor.proto
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\duration.proto" include\google\protobuf\duration.proto
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\empty.proto" include\google\protobuf\empty.proto
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\field_mask.proto" include\google\protobuf\field_mask.proto
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\source_context.proto" include\google\protobuf\source_context.proto
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\struct.proto" include\google\protobuf\struct.proto
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\timestamp.proto" include\google\protobuf\timestamp.proto
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\type.proto" include\google\protobuf\type.proto
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wrappers.proto" include\google\protobuf\wrappers.proto
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 2df6a293..1d0b0b84 100644
--- a/cmake/libprotobuf-lite.cmake
+++ b/cmake/libprotobuf-lite.cmake
@@ -10,13 +10,10 @@ set(libprotobuf_lite_files
${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_impl_lite.cc
${protobuf_source_dir}/src/google/protobuf/message_lite.cc
${protobuf_source_dir}/src/google/protobuf/repeated_field.cc
- ${protobuf_source_dir}/src/google/protobuf/stubs/atomicops_internals_x86_gcc.cc
- ${protobuf_source_dir}/src/google/protobuf/stubs/atomicops_internals_x86_msvc.cc
${protobuf_source_dir}/src/google/protobuf/stubs/bytestream.cc
${protobuf_source_dir}/src/google/protobuf/stubs/common.cc
${protobuf_source_dir}/src/google/protobuf/stubs/int128.cc
${protobuf_source_dir}/src/google/protobuf/stubs/io_win32.cc
- ${protobuf_source_dir}/src/google/protobuf/stubs/once.cc
${protobuf_source_dir}/src/google/protobuf/stubs/status.cc
${protobuf_source_dir}/src/google/protobuf/stubs/statusor.cc
${protobuf_source_dir}/src/google/protobuf/stubs/stringpiece.cc
@@ -38,7 +35,6 @@ set(libprotobuf_lite_includes
${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_impl_lite.h
${protobuf_source_dir}/src/google/protobuf/message_lite.h
${protobuf_source_dir}/src/google/protobuf/repeated_field.h
- ${protobuf_source_dir}/src/google/protobuf/stubs/atomicops_internals_x86_msvc.h
${protobuf_source_dir}/src/google/protobuf/stubs/bytestream.h
${protobuf_source_dir}/src/google/protobuf/stubs/common.h
${protobuf_source_dir}/src/google/protobuf/stubs/int128.h
@@ -52,8 +48,14 @@ set(libprotobuf_lite_includes
${protobuf_source_dir}/src/google/protobuf/wire_format_lite.h
)
+if (MSVC)
+set(libprotobuf_lite_rc_files
+ ${CMAKE_CURRENT_BINARY_DIR}/version.rc
+)
+endif()
+
add_library(libprotobuf-lite ${protobuf_SHARED_OR_STATIC}
- ${libprotobuf_lite_files} ${libprotobuf_lite_includes})
+ ${libprotobuf_lite_files} ${libprotobuf_lite_includes} ${libprotobuf_lite_rc_files})
target_link_libraries(libprotobuf-lite ${CMAKE_THREAD_LIBS_INIT})
target_include_directories(libprotobuf-lite PUBLIC ${protobuf_source_dir}/src)
if(MSVC AND protobuf_BUILD_SHARED_LIBS)
diff --git a/cmake/libprotobuf.cmake b/cmake/libprotobuf.cmake
index 65d05c19..bd570be7 100644
--- a/cmake/libprotobuf.cmake
+++ b/cmake/libprotobuf.cmake
@@ -112,8 +112,14 @@ set(libprotobuf_includes
${protobuf_source_dir}/src/google/protobuf/wrappers.pb.h
)
+if (MSVC)
+set(libprotobuf_rc_files
+ ${CMAKE_CURRENT_BINARY_DIR}/version.rc
+)
+endif()
+
add_library(libprotobuf ${protobuf_SHARED_OR_STATIC}
- ${libprotobuf_lite_files} ${libprotobuf_files} ${libprotobuf_includes})
+ ${libprotobuf_lite_files} ${libprotobuf_files} ${libprotobuf_includes} ${libprotobuf_rc_files})
target_link_libraries(libprotobuf ${CMAKE_THREAD_LIBS_INIT})
if(protobuf_WITH_ZLIB)
target_link_libraries(libprotobuf ${ZLIB_LIBRARIES})
diff --git a/cmake/libprotoc.cmake b/cmake/libprotoc.cmake
index 5f6d078c..92dfd306 100644
--- a/cmake/libprotoc.cmake
+++ b/cmake/libprotoc.cmake
@@ -61,17 +61,6 @@ set(libprotoc_files
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_shared_code_generator.cc
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_string_field.cc
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_string_field_lite.cc
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_enum.cc
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_enum_field.cc
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_extension.cc
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_field.cc
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_file.cc
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_generator.cc
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_helpers.cc
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_map_field.cc
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_message.cc
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_message_field.cc
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_primitive_field.cc
${protobuf_source_dir}/src/google/protobuf/compiler/js/js_generator.cc
${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types_embed.cc
${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_enum.cc
@@ -96,41 +85,29 @@ set(libprotoc_files
)
set(libprotoc_headers
- ${protobuf_source_dir}/src/google/protobuf/compiler/code_generator.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/command_line_interface.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/importer.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/mock_code_generator.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/package_info.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/parser.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/plugin.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/plugin.pb.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/subprocess.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/zip_writer.h
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_enum.h
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_enum_field.h
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_extension.h
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_field.h
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_file.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_generator.h
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_helpers.h
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_map_field.h
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_message.h
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_message_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_options.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_primitive_field.h
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_service.h
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_string_field.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_unittest.h
${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_doc_comment.h
${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_enum.h
${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_enum_field.h
${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_field_base.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_generator.h
${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_helpers.h
${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_map_field.h
${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_message.h
${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_message_field.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_names.h
${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_options.h
${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_primitive_field.h
${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_reflection_class.h
@@ -149,7 +126,6 @@ set(libprotoc_headers
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_extension_lite.h
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_field.h
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_file.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator.h
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator_factory.h
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_helpers.h
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_lazy_message_field.h
@@ -162,7 +138,6 @@ set(libprotoc_headers
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_field.h
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_field_lite.h
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_lite.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_names.h
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_name_resolver.h
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_options.h
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_primitive_field.h
@@ -171,52 +146,29 @@ set(libprotoc_headers
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_shared_code_generator.h
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_string_field.h
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_string_field_lite.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_enum.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_enum_field.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_extension.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_field.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_file.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_generator.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_helpers.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_map_field.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_message.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_message_field.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_params.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_primitive_field.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/js/js_generator.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types_embed.h
${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_enum.h
${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_enum_field.h
${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_extension.h
${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_field.h
${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_file.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_generator.h
${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_map_field.h
${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_message.h
${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_message_field.h
${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_oneof.h
${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/php/php_generator.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/python/python_generator.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/ruby/ruby_generator.h
- ${protobuf_source_dir}/src/google/protobuf/compiler/plugin.pb.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/subprocess.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/zip_writer.h
)
-set(js_well_known_types_sources
- ${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types/any.js
- ${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types/struct.js
- ${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types/timestamp.js
-)
-add_executable(js_embed ${protobuf_source_dir}/src/google/protobuf/compiler/js/embed.cc)
-add_custom_command(
- OUTPUT ${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types_embed.cc
- DEPENDS js_embed ${js_well_known_types_sources}
- COMMAND js_embed ${js_well_known_types_sources} > ${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types_embed.cc
+if (MSVC)
+set(libprotoc_rc_files
+ ${CMAKE_CURRENT_BINARY_DIR}/version.rc
)
+endif()
add_library(libprotoc ${protobuf_SHARED_OR_STATIC}
- ${libprotoc_files} ${libprotoc_headers})
+ ${libprotoc_files} ${libprotoc_headers} ${libprotoc_rc_files})
target_link_libraries(libprotoc libprotobuf)
if(MSVC AND protobuf_BUILD_SHARED_LIBS)
target_compile_definitions(libprotoc
diff --git a/cmake/protobuf-config.cmake.in b/cmake/protobuf-config.cmake.in
index acedcc7a..18054687 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} ${_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 5777b16e..bb160f47 100644
--- a/cmake/protoc.cmake
+++ b/cmake/protoc.cmake
@@ -2,6 +2,15 @@ set(protoc_files
${protobuf_source_dir}/src/google/protobuf/compiler/main.cc
)
-add_executable(protoc ${protoc_files})
+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)
add_executable(protobuf::protoc ALIAS protoc)
+
+set_target_properties(protoc PROPERTIES
+ VERSION ${protobuf_VERSION})
diff --git a/cmake/tests.cmake b/cmake/tests.cmake
index d4622c6b..f91567b8 100644
--- a/cmake/tests.cmake
+++ b/cmake/tests.cmake
@@ -1,24 +1,31 @@
-if (NOT EXISTS "${PROJECT_SOURCE_DIR}/../gmock/CMakeLists.txt")
- message(FATAL_ERROR "Cannot find gmock directory.")
+if (NOT EXISTS "${PROJECT_SOURCE_DIR}/../third_party/googletest/CMakeLists.txt")
+ message(FATAL_ERROR
+ "Cannot find third_party/googletest directory that's needed to "
+ "build tests. If you use git, make sure you have cloned submodules:\n"
+ " git submodule update --init --recursive\n"
+ "If instead you want to skip tests, run cmake with:\n"
+ " cmake -Dprotobuf_BUILD_TESTS=OFF\n")
endif()
option(protobuf_ABSOLUTE_TEST_PLUGIN_PATH
"Using absolute test_plugin path in tests" ON)
mark_as_advanced(protobuf_ABSOLUTE_TEST_PLUGIN_PATH)
+set(googlemock_source_dir "${protobuf_source_dir}/third_party/googletest/googlemock")
+set(googletest_source_dir "${protobuf_source_dir}/third_party/googletest/googletest")
include_directories(
- ${protobuf_source_dir}/gmock
- ${protobuf_source_dir}/gmock/gtest
- ${protobuf_source_dir}/gmock/gtest/include
- ${protobuf_source_dir}/gmock/include
+ ${googlemock_source_dir}
+ ${googletest_source_dir}
+ ${googletest_source_dir}/include
+ ${googlemock_source_dir}/include
)
add_library(gmock STATIC
- ${protobuf_source_dir}/gmock/src/gmock-all.cc
- ${protobuf_source_dir}/gmock/gtest/src/gtest-all.cc
+ "${googlemock_source_dir}/src/gmock-all.cc"
+ "${googletest_source_dir}/src/gtest-all.cc"
)
target_link_libraries(gmock ${CMAKE_THREAD_LIBS_INIT})
-add_library(gmock_main STATIC ${protobuf_source_dir}/gmock/src/gmock_main.cc)
+add_library(gmock_main STATIC "${googlemock_source_dir}/src/gmock_main.cc")
target_link_libraries(gmock_main gmock)
set(lite_test_protos
@@ -107,6 +114,7 @@ set(common_test_files
${protobuf_source_dir}/src/google/protobuf/arena_test_util.cc
${protobuf_source_dir}/src/google/protobuf/map_test_util.cc
${protobuf_source_dir}/src/google/protobuf/test_util.cc
+ ${protobuf_source_dir}/src/google/protobuf/test_util.inc
${protobuf_source_dir}/src/google/protobuf/testing/file.cc
${protobuf_source_dir}/src/google/protobuf/testing/googletest.cc
)
@@ -127,6 +135,7 @@ set(tests_files
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_unittest.cc
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_unittest.inc
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/metadata_test.cc
${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc
${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_generator_unittest.cc
@@ -151,6 +160,7 @@ set(tests_files
${protobuf_source_dir}/src/google/protobuf/map_field_test.cc
${protobuf_source_dir}/src/google/protobuf/map_test.cc
${protobuf_source_dir}/src/google/protobuf/message_unittest.cc
+ ${protobuf_source_dir}/src/google/protobuf/message_unittest.inc
${protobuf_source_dir}/src/google/protobuf/no_field_presence_test.cc
${protobuf_source_dir}/src/google/protobuf/preserve_unknown_enum_test.cc
${protobuf_source_dir}/src/google/protobuf/proto3_arena_lite_unittest.cc
@@ -163,7 +173,6 @@ set(tests_files
${protobuf_source_dir}/src/google/protobuf/stubs/common_unittest.cc
${protobuf_source_dir}/src/google/protobuf/stubs/int128_unittest.cc
${protobuf_source_dir}/src/google/protobuf/stubs/io_win32_unittest.cc
- ${protobuf_source_dir}/src/google/protobuf/stubs/once_unittest.cc
${protobuf_source_dir}/src/google/protobuf/stubs/status_test.cc
${protobuf_source_dir}/src/google/protobuf/stubs/statusor_test.cc
${protobuf_source_dir}/src/google/protobuf/stubs/stringpiece_unittest.cc
@@ -172,7 +181,6 @@ set(tests_files
${protobuf_source_dir}/src/google/protobuf/stubs/strutil_unittest.cc
${protobuf_source_dir}/src/google/protobuf/stubs/template_util_unittest.cc
${protobuf_source_dir}/src/google/protobuf/stubs/time_test.cc
- ${protobuf_source_dir}/src/google/protobuf/stubs/type_traits_unittest.cc
${protobuf_source_dir}/src/google/protobuf/text_format_unittest.cc
${protobuf_source_dir}/src/google/protobuf/unknown_field_set_unittest.cc
${protobuf_source_dir}/src/google/protobuf/util/delimited_message_util_test.cc
@@ -196,6 +204,10 @@ 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")
+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/cmake/version.rc.in b/cmake/version.rc.in
new file mode 100644
index 00000000..cbce1e53
--- /dev/null
+++ b/cmake/version.rc.in
@@ -0,0 +1,45 @@
+#define VS_FF_DEBUG 0x1L
+#define VS_VERSION_INFO 0x1L
+#define VS_FFI_FILEFLAGSMASK 0x17L
+#define VER_PRIVATEBUILD 0x0L
+#define VER_PRERELEASE 0x0L
+#define VOS__WINDOWS32 0x4L
+#define VFT_DLL 0x2L
+#define VFT2_UNKNOWN 0x0L
+
+#ifndef DEBUG
+#define VER_DEBUG 0
+#else
+#define VER_DEBUG VS_FF_DEBUG
+#endif
+
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION @protobuf_RC_FILEVERSION@,0
+ PRODUCTVERSION @protobuf_RC_FILEVERSION@,0
+ FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
+ FILEFLAGS VER_DEBUG
+ FILEOS VOS__WINDOWS32
+ FILETYPE VFT_DLL
+BEGIN
+ BLOCK "VarFileInfo"
+ BEGIN
+ // English language (0x409) and the Windows Unicode codepage (1200)
+ VALUE "Translation", 0x409, 1200
+ END
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "040904b0"
+ BEGIN
+ VALUE "FileDescription", "Compiled with @CMAKE_CXX_COMPILER_ID@ @CMAKE_CXX_COMPILER_VERSION@\0"
+ VALUE "ProductVersion", "@protobuf_VERSION@\0"
+ VALUE "FileVersion", "@protobuf_VERSION@\0"
+ VALUE "InternalName", "protobuf\0"
+ VALUE "ProductName", "Protocol Buffers - Google's Data Interchange Format\0"
+ VALUE "CompanyName", "Google Inc.\0"
+ VALUE "LegalCopyright", "Copyright 2008 Google Inc. All rights reserved.\0"
+ VALUE "Licence", "BSD\0"
+ VALUE "Info", "https://developers.google.com/protocol-buffers/\0"
+ END
+ END
+END
diff --git a/configure.ac b/configure.ac
index faa1cdc3..69b3fe30 100644
--- a/configure.ac
+++ b/configure.ac
@@ -17,7 +17,7 @@ AC_PREREQ(2.59)
# In the SVN trunk, the version should always be the next anticipated release
# version with the "-pre" suffix. (We used to use "-SNAPSHOT" but this pushed
# the size of one file name in the dist tarfile over the 99-char limit.)
-AC_INIT([Protocol Buffers],[3.5.1],[protobuf@googlegroups.com],[protobuf])
+AC_INIT([Protocol Buffers],[3.6.0],[protobuf@googlegroups.com],[protobuf])
AM_MAINTAINER_MODE([enable])
@@ -88,7 +88,7 @@ AS_IF([test "x${ac_cv_env_CXXFLAGS_set}" = "x"],[
# Protocol Buffers contains several checks that are intended to be used only
# for debugging and which might hurt performance. Most users are probably
# end users who don't want these checks, so add -DNDEBUG by default.
- CXXFLAGS="$CXXFLAGS -DNDEBUG"
+ CXXFLAGS="$CXXFLAGS -std=c++11 -DNDEBUG"
AC_MSG_RESULT([use default: $PROTOBUF_OPT_FLAG $CXXFLAGS])
],[
@@ -184,14 +184,13 @@ AS_IF([test "$with_protoc" != "no"], [
])
AM_CONDITIONAL([USE_EXTERNAL_PROTOC], [test "$with_protoc" != "no"])
-ACX_PTHREAD
-AM_CONDITIONAL([HAVE_PTHREAD], [test "x$acx_pthread_ok" = "xyes"])
-
+AX_PTHREAD
+AM_CONDITIONAL([HAVE_PTHREAD], [test "x$ax_pthread_ok" = "xyes"])
# We still keep this for improving pbconfig.h for unsupported platforms.
AC_CXX_STL_HASH
case "$target_os" in
- mingw* | cygwin* | win* | aix*)
+ mingw* | cygwin* | win* | aix* | *android* )
;;
*)
# Need to link against rt on Solaris
@@ -208,14 +207,14 @@ case "$target_os" in
esac
AM_CONDITIONAL([OBJC_CONFORMANCE_TEST], [test $OBJC_CONFORMANCE_TEST = 1])
-AX_CXX_COMPILE_STDCXX([11], [noext], [optional])
+AX_CXX_COMPILE_STDCXX([11], [noext], [mandatory])
# HACK: Make gmock's configure script pick up our copy of CFLAGS and CXXFLAGS,
# since the flags added by ACX_CHECK_SUNCC must be used when compiling gmock
# too.
export CFLAGS
export CXXFLAGS
-AC_CONFIG_SUBDIRS([gmock])
+AC_CONFIG_SUBDIRS([third_party/googletest])
AC_CONFIG_FILES([Makefile src/Makefile benchmarks/Makefile conformance/Makefile protobuf.pc protobuf-lite.pc])
AC_OUTPUT
diff --git a/conformance/conformance_cpp.cc b/conformance/conformance_cpp.cc
index 9540b50e..97ae1a7a 100644
--- a/conformance/conformance_cpp.cc
+++ b/conformance/conformance_cpp.cc
@@ -45,7 +45,6 @@ using google::protobuf::Descriptor;
using google::protobuf::DescriptorPool;
using google::protobuf::Message;
using google::protobuf::MessageFactory;
-using google::protobuf::internal::scoped_ptr;
using google::protobuf::util::BinaryToJsonString;
using google::protobuf::util::JsonToBinaryString;
using google::protobuf::util::NewTypeResolverForDescriptorPool;
diff --git a/conformance/conformance_test.cc b/conformance/conformance_test.cc
index e4b046dc..22bbbfb3 100644
--- a/conformance/conformance_test.cc
+++ b/conformance/conformance_test.cc
@@ -1910,6 +1910,10 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
{
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);
}
@@ -2321,6 +2325,24 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
}
)");
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"(
diff --git a/conformance/conformance_test.h b/conformance/conformance_test.h
index 4882412c..2649f8b2 100644
--- a/conformance/conformance_test.h
+++ b/conformance/conformance_test.h
@@ -256,8 +256,7 @@ class ConformanceTestSuite {
// The set of tests that the testee opted out of;
std::set<std::string> skipped_;
- google::protobuf::internal::scoped_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_runner.cc b/conformance/conformance_test_runner.cc
index 09631f0c..b0357b87 100644
--- a/conformance/conformance_test_runner.cc
+++ b/conformance/conformance_test_runner.cc
@@ -68,7 +68,6 @@
using conformance::ConformanceRequest;
using conformance::ConformanceResponse;
-using google::protobuf::internal::scoped_array;
using google::protobuf::StringAppendF;
using std::string;
using std::vector;
@@ -183,7 +182,7 @@ class ForkPipeRunner : public google::protobuf::ConformanceTestRunner {
CHECK_SYSCALL(close(toproc_pipe_fd[1]));
CHECK_SYSCALL(close(fromproc_pipe_fd[0]));
- scoped_array<char> executable(new char[executable_.size() + 1]);
+ std::unique_ptr<char[]> executable(new char[executable_.size() + 1]);
memcpy(executable.get(), executable_.c_str(), executable_.size());
executable[executable_.size()] = '\0';
diff --git a/conformance/failure_list_ruby.txt b/conformance/failure_list_ruby.txt
index 1bab1359..b2683372 100644
--- a/conformance/failure_list_ruby.txt
+++ b/conformance/failure_list_ruby.txt
@@ -120,6 +120,8 @@ 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
diff --git a/csharp/Google.Protobuf.Tools.nuspec b/csharp/Google.Protobuf.Tools.nuspec
index 62eb3b58..0ba7cc9f 100644
--- a/csharp/Google.Protobuf.Tools.nuspec
+++ b/csharp/Google.Protobuf.Tools.nuspec
@@ -5,7 +5,7 @@
<title>Google Protocol Buffers tools</title>
<summary>Tools for Protocol Buffers - Google's data interchange format.</summary>
<description>See project site for more info.</description>
- <version>3.5.1</version>
+ <version>3.6.0</version>
<authors>Google Inc.</authors>
<owners>protobuf-packages</owners>
<licenseUrl>https://github.com/google/protobuf/blob/master/LICENSE</licenseUrl>
@@ -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 c1d12419..9d1225f1 100644
--- a/csharp/README.md
+++ b/csharp/README.md
@@ -41,13 +41,17 @@ in its implementation, as well as the new Visual Studio 2017 csproj
format. These features have no impact when using the compiled code -
they're only relevant when building the `Google.Protobuf` assembly.
+In order to run and debug the AddressBook example in the IDE, you must
+install the optional component, ".Net Core 1.0 - 1.1 development tools
+for Web" (as it's labelled in current versions of the VS2017
+installer), above and beyond the main .NET Core cross-platform
+development feature.
+
Testing
=======
-The unit tests use [NUnit 3](https://github.com/nunit/nunit). NUnit doesn't yet
-support `dotnet test`, so for now the test project is a console application
-using NUnitLite. Simply run `Google.Protobuf.Test.exe` to run the unit tests
-directly, or else use `dotnet run`.
+The unit tests use [NUnit 3](https://github.com/nunit/nunit). Tests can be
+run using the Visual Studio Test Explorer or `dotnet test`.
.NET 3.5
========
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/buildall.sh b/csharp/buildall.sh
index dd4b463d..50d8906d 100755
--- a/csharp/buildall.sh
+++ b/csharp/buildall.sh
@@ -14,4 +14,4 @@ echo Running tests.
# If we want to test the .NET 4.5 version separately, we could
# run Mono explicitly. However, we don't have any differences between
# the .NET 4.5 and netstandard1.0 assemblies.
-dotnet run -c $CONFIG -f netcoreapp1.0 -p $SRC/Google.Protobuf.Test/Google.Protobuf.Test.csproj
+dotnet test -c $CONFIG -f netcoreapp1.0 $SRC/Google.Protobuf.Test/Google.Protobuf.Test.csproj
diff --git a/csharp/src/AddressBook/Addressbook.cs b/csharp/src/AddressBook/Addressbook.cs
index ceb93699..21a8ce02 100644
--- a/csharp/src/AddressBook/Addressbook.cs
+++ b/csharp/src/AddressBook/Addressbook.cs
@@ -78,7 +78,7 @@ namespace Google.Protobuf.Examples.AddressBook {
id_ = other.id_;
email_ = other.email_;
phones_ = other.phones_.Clone();
- LastUpdated = other.lastUpdated_ != null ? other.LastUpdated.Clone() : null;
+ lastUpdated_ = other.lastUpdated_ != null ? other.lastUpdated_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
diff --git a/csharp/src/Google.Protobuf.Test/ByteStringTest.cs b/csharp/src/Google.Protobuf.Test/ByteStringTest.cs
index afdd491f..afdd491f 100755..100644
--- a/csharp/src/Google.Protobuf.Test/ByteStringTest.cs
+++ b/csharp/src/Google.Protobuf.Test/ByteStringTest.cs
diff --git a/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs b/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs
index e7c6b805..8795fa65 100644
--- a/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs
+++ b/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs
@@ -615,5 +615,88 @@ namespace Google.Protobuf
var stream = new CodedInputStream(new byte[10]);
stream.Dispose();
}
+
+ [Test]
+ public void TestParseMessagesCloseTo2G()
+ {
+ byte[] serializedMessage = GenerateBigSerializedMessage();
+ // How many of these big messages do we need to take us near our 2GB limit?
+ int count = Int32.MaxValue / serializedMessage.Length;
+ // Now make a MemoryStream that will fake a near-2GB stream of messages by returning
+ // our big serialized message 'count' times.
+ using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count))
+ {
+ Assert.DoesNotThrow(()=>TestAllTypes.Parser.ParseFrom(stream));
+ }
+ }
+
+ [Test]
+ public void TestParseMessagesOver2G()
+ {
+ byte[] serializedMessage = GenerateBigSerializedMessage();
+ // How many of these big messages do we need to take us near our 2GB limit?
+ int count = Int32.MaxValue / serializedMessage.Length;
+ // Now add one to take us over the 2GB limit
+ count++;
+ // Now make a MemoryStream that will fake a near-2GB stream of messages by returning
+ // our big serialized message 'count' times.
+ using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count))
+ {
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream),
+ "Protocol message was too large. May be malicious. " +
+ "Use CodedInputStream.SetSizeLimit() to increase the size limit.");
+ }
+ }
+
+ /// <returns>A serialized big message</returns>
+ private static byte[] GenerateBigSerializedMessage()
+ {
+ byte[] value = new byte[16 * 1024 * 1024];
+ TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
+ message.SingleBytes = ByteString.CopyFrom(value);
+ return message.ToByteArray();
+ }
+
+ /// <summary>
+ /// A MemoryStream that repeats a byte arrays' content a number of times.
+ /// Simulates really large input without consuming loads of memory. Used above
+ /// to test the parsing behavior when the input size exceeds 2GB or close to it.
+ /// </summary>
+ private class RepeatingMemoryStream: MemoryStream
+ {
+ private readonly byte[] bytes;
+ private readonly int maxIterations;
+ private int index = 0;
+
+ public RepeatingMemoryStream(byte[] bytes, int maxIterations)
+ {
+ this.bytes = bytes;
+ this.maxIterations = maxIterations;
+ }
+
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ if (bytes.Length == 0)
+ {
+ return 0;
+ }
+ int numBytesCopiedTotal = 0;
+ while (numBytesCopiedTotal < count && index < maxIterations)
+ {
+ int numBytesToCopy = Math.Min(bytes.Length - (int)Position, count);
+ Array.Copy(bytes, (int)Position, buffer, offset, numBytesToCopy);
+ numBytesCopiedTotal += numBytesToCopy;
+ offset += numBytesToCopy;
+ count -= numBytesCopiedTotal;
+ Position += numBytesToCopy;
+ if (Position >= bytes.Length)
+ {
+ Position = 0;
+ index++;
+ }
+ }
+ return numBytesCopiedTotal;
+ }
+ }
}
} \ No newline at end of file
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/Google.Protobuf.Test.csproj b/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj
index 06d07b9f..6a430116 100644
--- a/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj
+++ b/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj
@@ -1,7 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <OutputType>Exe</OutputType>
<TargetFrameworks>net451;netcoreapp1.0</TargetFrameworks>
<AssemblyOriginatorKeyFile>../../keys/Google.Protobuf.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>
@@ -14,8 +13,9 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="NUnit" Version="3.6.1" />
- <PackageReference Include="NUnitLite" Version="3.6.1" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0" />
+ <PackageReference Include="NUnit" Version="3.9.0" />
+ <PackageReference Include="NUnit3TestAdapter" Version="3.9.0" />
</ItemGroup>
<!--
@@ -26,5 +26,5 @@
<PropertyGroup Condition="'$(OS)' != 'Windows_NT'">
<TargetFrameworks>netcoreapp1.0</TargetFrameworks>
</PropertyGroup>
-
+
</Project>
diff --git a/csharp/src/Google.Protobuf.Test/JsonParserTest.cs b/csharp/src/Google.Protobuf.Test/JsonParserTest.cs
index 329ae9be..a6cf04ab 100644
--- a/csharp/src/Google.Protobuf.Test/JsonParserTest.cs
+++ b/csharp/src/Google.Protobuf.Test/JsonParserTest.cs
@@ -696,6 +696,22 @@ namespace Google.Protobuf
}
[Test]
+ public void Value_List_WithNullElement()
+ {
+ var expected = Value.ForList(Value.ForString("x"), Value.ForNull(), Value.ForString("y"));
+ var actual = Value.Parser.ParseJson("[\"x\", null, \"y\"]");
+ Assert.AreEqual(expected, actual);
+ }
+
+ [Test]
+ public void StructValue_NullElement()
+ {
+ var expected = Value.ForStruct(new Struct { Fields = { { "x", Value.ForNull() } } });
+ var actual = Value.Parser.ParseJson("{ \"x\": null }");
+ Assert.AreEqual(expected, actual);
+ }
+
+ [Test]
public void ParseListValue()
{
Assert.AreEqual(new ListValue { Values = { Value.ForNumber(1), Value.ForString("x") } }, ListValue.Parser.ParseJson("[1, \"x\"]"));
diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs b/csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs
index cb1bc920..51715a0c 100644
--- a/csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs
+++ b/csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs
@@ -642,7 +642,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestMapSubmessage(TestMapSubmessage other) : this() {
- TestMap = other.testMap_ != null ? other.TestMap.Clone() : null;
+ testMap_ = other.testMap_ != null ? other.testMap_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/TestMessagesProto3.cs b/csharp/src/Google.Protobuf.Test/TestProtos/TestMessagesProto3.cs
index a2a236d9..7353be7b 100644
--- a/csharp/src/Google.Protobuf.Test/TestProtos/TestMessagesProto3.cs
+++ b/csharp/src/Google.Protobuf.Test/TestProtos/TestMessagesProto3.cs
@@ -273,13 +273,13 @@ namespace ProtobufTestMessages.Proto3 {
optionalBool_ = other.optionalBool_;
optionalString_ = other.optionalString_;
optionalBytes_ = other.optionalBytes_;
- OptionalNestedMessage = other.optionalNestedMessage_ != null ? other.OptionalNestedMessage.Clone() : null;
- OptionalForeignMessage = other.optionalForeignMessage_ != null ? other.OptionalForeignMessage.Clone() : null;
+ optionalNestedMessage_ = other.optionalNestedMessage_ != null ? other.optionalNestedMessage_.Clone() : null;
+ optionalForeignMessage_ = other.optionalForeignMessage_ != null ? other.optionalForeignMessage_.Clone() : null;
optionalNestedEnum_ = other.optionalNestedEnum_;
optionalForeignEnum_ = other.optionalForeignEnum_;
optionalStringPiece_ = other.optionalStringPiece_;
optionalCord_ = other.optionalCord_;
- RecursiveMessage = other.recursiveMessage_ != null ? other.RecursiveMessage.Clone() : null;
+ recursiveMessage_ = other.recursiveMessage_ != null ? other.recursiveMessage_.Clone() : null;
repeatedInt32_ = other.repeatedInt32_.Clone();
repeatedInt64_ = other.repeatedInt64_.Clone();
repeatedUint32_ = other.repeatedUint32_.Clone();
@@ -338,12 +338,12 @@ namespace ProtobufTestMessages.Proto3 {
repeatedDoubleWrapper_ = other.repeatedDoubleWrapper_.Clone();
repeatedStringWrapper_ = other.repeatedStringWrapper_.Clone();
repeatedBytesWrapper_ = other.repeatedBytesWrapper_.Clone();
- OptionalDuration = other.optionalDuration_ != null ? other.OptionalDuration.Clone() : null;
- OptionalTimestamp = other.optionalTimestamp_ != null ? other.OptionalTimestamp.Clone() : null;
- OptionalFieldMask = other.optionalFieldMask_ != null ? other.OptionalFieldMask.Clone() : null;
- OptionalStruct = other.optionalStruct_ != null ? other.OptionalStruct.Clone() : null;
- OptionalAny = other.optionalAny_ != null ? other.OptionalAny.Clone() : null;
- OptionalValue = other.optionalValue_ != null ? other.OptionalValue.Clone() : null;
+ optionalDuration_ = other.optionalDuration_ != null ? other.optionalDuration_.Clone() : null;
+ optionalTimestamp_ = other.optionalTimestamp_ != null ? other.optionalTimestamp_.Clone() : null;
+ optionalFieldMask_ = other.optionalFieldMask_ != null ? other.optionalFieldMask_.Clone() : null;
+ optionalStruct_ = other.optionalStruct_ != null ? other.optionalStruct_.Clone() : null;
+ optionalAny_ = other.optionalAny_ != null ? other.optionalAny_.Clone() : null;
+ optionalValue_ = other.optionalValue_ != null ? other.optionalValue_.Clone() : null;
repeatedDuration_ = other.repeatedDuration_.Clone();
repeatedTimestamp_ = other.repeatedTimestamp_.Clone();
repeatedFieldmask_ = other.repeatedFieldmask_.Clone();
@@ -3455,7 +3455,7 @@ namespace ProtobufTestMessages.Proto3 {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public NestedMessage(NestedMessage other) : this() {
a_ = other.a_;
- Corecursive = other.corecursive_ != null ? other.Corecursive.Clone() : null;
+ corecursive_ = other.corecursive_ != null ? other.corecursive_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestCustomOptionsProto3.cs b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestCustomOptionsProto3.cs
index 6d02bda6..3ab5a48b 100644
--- a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestCustomOptionsProto3.cs
+++ b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestCustomOptionsProto3.cs
@@ -1740,9 +1740,9 @@ namespace UnitTest.Issues.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ComplexOptionType2(ComplexOptionType2 other) : this() {
- Bar = other.bar_ != null ? other.Bar.Clone() : null;
+ bar_ = other.bar_ != null ? other.bar_.Clone() : null;
baz_ = other.baz_;
- Fred = other.fred_ != null ? other.Fred.Clone() : null;
+ fred_ = other.fred_ != null ? other.fred_.Clone() : null;
barney_ = other.barney_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -2331,7 +2331,7 @@ namespace UnitTest.Issues.TestProtos {
public Aggregate(Aggregate other) : this() {
i_ = other.i_;
s_ = other.s_;
- Sub = other.sub_ != null ? other.Sub.Clone() : null;
+ sub_ = other.sub_ != null ? other.sub_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs
index 01a86f8f..819fc201 100644
--- a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs
+++ b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs
@@ -704,7 +704,7 @@ namespace UnitTest.Issues.TestProtos {
public DeprecatedFieldsMessage(DeprecatedFieldsMessage other) : this() {
primitiveValue_ = other.primitiveValue_;
primitiveArray_ = other.primitiveArray_.Clone();
- MessageValue = other.messageValue_ != null ? other.MessageValue.Clone() : null;
+ messageValue_ = other.messageValue_ != null ? other.messageValue_.Clone() : null;
messageArray_ = other.messageArray_.Clone();
enumValue_ = other.enumValue_;
enumArray_ = other.enumArray_.Clone();
diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestProto3.cs b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestProto3.cs
index 4242c192..d5dbe866 100644
--- a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestProto3.cs
+++ b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestProto3.cs
@@ -280,13 +280,13 @@ namespace Google.Protobuf.TestProtos {
singleBool_ = other.singleBool_;
singleString_ = other.singleString_;
singleBytes_ = other.singleBytes_;
- SingleNestedMessage = other.singleNestedMessage_ != null ? other.SingleNestedMessage.Clone() : null;
- SingleForeignMessage = other.singleForeignMessage_ != null ? other.SingleForeignMessage.Clone() : null;
- SingleImportMessage = other.singleImportMessage_ != null ? other.SingleImportMessage.Clone() : null;
+ singleNestedMessage_ = other.singleNestedMessage_ != null ? other.singleNestedMessage_.Clone() : null;
+ singleForeignMessage_ = other.singleForeignMessage_ != null ? other.singleForeignMessage_.Clone() : null;
+ singleImportMessage_ = other.singleImportMessage_ != null ? other.singleImportMessage_.Clone() : null;
singleNestedEnum_ = other.singleNestedEnum_;
singleForeignEnum_ = other.singleForeignEnum_;
singleImportEnum_ = other.singleImportEnum_;
- SinglePublicImportMessage = other.singlePublicImportMessage_ != null ? other.SinglePublicImportMessage.Clone() : null;
+ singlePublicImportMessage_ = other.singlePublicImportMessage_ != null ? other.singlePublicImportMessage_.Clone() : null;
repeatedInt32_ = other.repeatedInt32_.Clone();
repeatedInt64_ = other.repeatedInt64_.Clone();
repeatedUint32_ = other.repeatedUint32_.Clone();
@@ -1786,8 +1786,8 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public NestedTestAllTypes(NestedTestAllTypes other) : this() {
- Child = other.child_ != null ? other.Child.Clone() : null;
- Payload = other.payload_ != null ? other.Payload.Clone() : null;
+ child_ = other.child_ != null ? other.child_.Clone() : null;
+ payload_ = other.payload_ != null ? other.payload_.Clone() : null;
repeatedChild_ = other.repeatedChild_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -2342,7 +2342,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestForeignNested(TestForeignNested other) : this() {
- ForeignNested = other.foreignNested_ != null ? other.ForeignNested.Clone() : null;
+ foreignNested_ = other.foreignNested_ != null ? other.foreignNested_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -2641,7 +2641,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestRecursiveMessage(TestRecursiveMessage other) : this() {
- A = other.a_ != null ? other.A.Clone() : null;
+ a_ = other.a_ != null ? other.a_.Clone() : null;
i_ = other.i_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -2807,7 +2807,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestMutualRecursionA(TestMutualRecursionA other) : this() {
- Bb = other.bb_ != null ? other.Bb.Clone() : null;
+ bb_ = other.bb_ != null ? other.bb_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -2942,7 +2942,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestMutualRecursionB(TestMutualRecursionB other) : this() {
- A = other.a_ != null ? other.A.Clone() : null;
+ a_ = other.a_ != null ? other.a_.Clone() : null;
optionalInt32_ = other.optionalInt32_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -3241,7 +3241,7 @@ namespace Google.Protobuf.TestProtos {
primitiveField_ = other.primitiveField_;
stringField_ = other.stringField_;
enumField_ = other.enumField_;
- MessageField = other.messageField_ != null ? other.MessageField.Clone() : null;
+ messageField_ = other.messageField_ != null ? other.messageField_.Clone() : null;
repeatedPrimitiveField_ = other.repeatedPrimitiveField_.Clone();
repeatedStringField_ = other.repeatedStringField_.Clone();
repeatedEnumField_ = other.repeatedEnumField_.Clone();
@@ -3546,7 +3546,7 @@ namespace Google.Protobuf.TestProtos {
myString_ = other.myString_;
myInt_ = other.myInt_;
myFloat_ = other.myFloat_;
- SingleNestedMessage = other.singleNestedMessage_ != null ? other.SingleNestedMessage.Clone() : null;
+ singleNestedMessage_ = other.singleNestedMessage_ != null ? other.singleNestedMessage_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestWellKnownTypes.cs b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestWellKnownTypes.cs
index 2e1d2bd6..fe913802 100644
--- a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestWellKnownTypes.cs
+++ b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestWellKnownTypes.cs
@@ -204,15 +204,15 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestWellKnownTypes(TestWellKnownTypes other) : this() {
- AnyField = other.anyField_ != null ? other.AnyField.Clone() : null;
- ApiField = other.apiField_ != null ? other.ApiField.Clone() : null;
- DurationField = other.durationField_ != null ? other.DurationField.Clone() : null;
- EmptyField = other.emptyField_ != null ? other.EmptyField.Clone() : null;
- FieldMaskField = other.fieldMaskField_ != null ? other.FieldMaskField.Clone() : null;
- SourceContextField = other.sourceContextField_ != null ? other.SourceContextField.Clone() : null;
- StructField = other.structField_ != null ? other.StructField.Clone() : null;
- TimestampField = other.timestampField_ != null ? other.TimestampField.Clone() : null;
- TypeField = other.typeField_ != null ? other.TypeField.Clone() : null;
+ anyField_ = other.anyField_ != null ? other.anyField_.Clone() : null;
+ apiField_ = other.apiField_ != null ? other.apiField_.Clone() : null;
+ durationField_ = other.durationField_ != null ? other.durationField_.Clone() : null;
+ emptyField_ = other.emptyField_ != null ? other.emptyField_.Clone() : null;
+ fieldMaskField_ = other.fieldMaskField_ != null ? other.fieldMaskField_.Clone() : null;
+ sourceContextField_ = other.sourceContextField_ != null ? other.sourceContextField_.Clone() : null;
+ structField_ = other.structField_ != null ? other.structField_.Clone() : null;
+ timestampField_ = other.timestampField_ != null ? other.timestampField_.Clone() : null;
+ typeField_ = other.typeField_ != null ? other.typeField_.Clone() : null;
DoubleField = other.DoubleField;
FloatField = other.FloatField;
Int64Field = other.Int64Field;
@@ -222,7 +222,7 @@ namespace Google.Protobuf.TestProtos {
BoolField = other.BoolField;
StringField = other.StringField;
BytesField = other.BytesField;
- ValueField = other.valueField_ != null ? other.ValueField.Clone() : null;
+ valueField_ = other.valueField_ != null ? other.valueField_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
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/CodedInputStream.cs b/csharp/src/Google.Protobuf/CodedInputStream.cs
index 6bee238f..0a829545 100644
--- a/csharp/src/Google.Protobuf/CodedInputStream.cs
+++ b/csharp/src/Google.Protobuf/CodedInputStream.cs
@@ -94,7 +94,7 @@ namespace Google.Protobuf
private bool hasNextTag = false;
internal const int DefaultRecursionLimit = 64;
- internal const int DefaultSizeLimit = 64 << 20; // 64MB
+ internal const int DefaultSizeLimit = Int32.MaxValue;
internal const int BufferSize = 4096;
/// <summary>
@@ -248,7 +248,7 @@ namespace Google.Protobuf
/// <remarks>
/// This limit is applied when reading from the underlying stream, as a sanity check. It is
/// not applied when reading from a byte array data source without an underlying stream.
- /// The default value is 64MB.
+ /// The default value is Int32.MaxValue.
/// </remarks>
/// <value>
/// The size limit.
@@ -1058,7 +1058,7 @@ namespace Google.Protobuf
RecomputeBufferSizeAfterLimit();
int totalBytesRead =
totalBytesRetired + bufferSize + bufferSizeAfterLimit;
- if (totalBytesRead > sizeLimit || totalBytesRead < 0)
+ if (totalBytesRead < 0 || totalBytesRead > sizeLimit)
{
throw InvalidProtocolBufferException.SizeLimitExceeded();
}
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.Test/Program.cs b/csharp/src/Google.Protobuf/Compatibility/MethodInfoExtensions.cs
index 954c02b5..7b946cb6 100755..100644
--- a/csharp/src/Google.Protobuf.Test/Program.cs
+++ b/csharp/src/Google.Protobuf/Compatibility/MethodInfoExtensions.cs
@@ -1,4 +1,4 @@
-#region Copyright notice and license
+#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2017 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
@@ -29,20 +29,19 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
-using NUnitLite;
+
+#if NET35
+using System;
using System.Reflection;
-namespace Google.Protobuf.Test
+namespace Google.Protobuf.Compatibility
{
- class Program
+ // .NET Core (at least netstandard1.0) doesn't have Delegate.CreateDelegate, and .NET 3.5 doesn't have
+ // MethodInfo.CreateDelegate. Proxy from one to the other on .NET 3.5...
+ internal static class MethodInfoExtensions
{
- public static int Main(string[] args)
- {
- #if NET35
- return new AutoRun(typeof(Program).Assembly).Execute(args);
- #else
- return new AutoRun(typeof(Program).GetTypeInfo().Assembly).Execute(args);
- #endif
- }
+ internal static Delegate CreateDelegate(this MethodInfo method, Type type) =>
+ Delegate.CreateDelegate(type, method);
}
-} \ No newline at end of file
+}
+#endif
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 4df0bda6..46728b72 100644
--- a/csharp/src/Google.Protobuf/Google.Protobuf.csproj
+++ b/csharp/src/Google.Protobuf/Google.Protobuf.csproj
@@ -4,7 +4,7 @@
<Description>C# runtime library for Protocol Buffers - Google's data interchange format.</Description>
<Copyright>Copyright 2015, Google Inc.</Copyright>
<AssemblyTitle>Google Protocol Buffers</AssemblyTitle>
- <VersionPrefix>3.5.1</VersionPrefix>
+ <VersionPrefix>3.6.0</VersionPrefix>
<Authors>Google Inc.</Authors>
<TargetFrameworks>netstandard1.0;net45</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
@@ -17,8 +17,6 @@
<PackageLicenseUrl>https://github.com/google/protobuf/blob/master/LICENSE</PackageLicenseUrl>
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/google/protobuf.git</RepositoryUrl>
- <IncludeSymbols>true</IncludeSymbols>
- <IncludeSource>true</IncludeSource>
</PropertyGroup>
<!--
@@ -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/JsonParser.cs b/csharp/src/Google.Protobuf/JsonParser.cs
index 3621b0c0..284bce93 100644
--- a/csharp/src/Google.Protobuf/JsonParser.cs
+++ b/csharp/src/Google.Protobuf/JsonParser.cs
@@ -264,11 +264,12 @@ namespace Google.Protobuf
return;
}
tokenizer.PushBack(token);
- if (token.Type == JsonToken.TokenType.Null)
+ object value = ParseSingleValue(field, tokenizer);
+ if (value == null)
{
throw new InvalidProtocolBufferException("Repeated field elements cannot be null");
}
- list.Add(ParseSingleValue(field, tokenizer));
+ list.Add(value);
}
}
diff --git a/csharp/src/Google.Protobuf/Reflection/Descriptor.cs b/csharp/src/Google.Protobuf/Reflection/Descriptor.cs
index af68fa86..4cbed33b 100644
--- a/csharp/src/Google.Protobuf/Reflection/Descriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/Descriptor.cs
@@ -89,7 +89,7 @@ namespace Google.Protobuf.Reflection {
"KAkSEwoLb3V0cHV0X3R5cGUYAyABKAkSLwoHb3B0aW9ucxgEIAEoCzIeLmdv",
"b2dsZS5wcm90b2J1Zi5NZXRob2RPcHRpb25zEh8KEGNsaWVudF9zdHJlYW1p",
"bmcYBSABKAg6BWZhbHNlEh8KEHNlcnZlcl9zdHJlYW1pbmcYBiABKAg6BWZh",
- "bHNlIvAFCgtGaWxlT3B0aW9ucxIUCgxqYXZhX3BhY2thZ2UYASABKAkSHAoU",
+ "bHNlIqYGCgtGaWxlT3B0aW9ucxIUCgxqYXZhX3BhY2thZ2UYASABKAkSHAoU",
"amF2YV9vdXRlcl9jbGFzc25hbWUYCCABKAkSIgoTamF2YV9tdWx0aXBsZV9m",
"aWxlcxgKIAEoCDoFZmFsc2USKQodamF2YV9nZW5lcmF0ZV9lcXVhbHNfYW5k",
"X2hhc2gYFCABKAhCAhgBEiUKFmphdmFfc3RyaW5nX2NoZWNrX3V0ZjgYGyAB",
@@ -102,61 +102,62 @@ namespace Google.Protobuf.Reflection {
"ZmFsc2USHwoQY2NfZW5hYmxlX2FyZW5hcxgfIAEoCDoFZmFsc2USGQoRb2Jq",
"Y19jbGFzc19wcmVmaXgYJCABKAkSGAoQY3NoYXJwX25hbWVzcGFjZRglIAEo",
"CRIUCgxzd2lmdF9wcmVmaXgYJyABKAkSGAoQcGhwX2NsYXNzX3ByZWZpeBgo",
- "IAEoCRIVCg1waHBfbmFtZXNwYWNlGCkgASgJEkMKFHVuaW50ZXJwcmV0ZWRf",
- "b3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVk",
- "T3B0aW9uIjoKDE9wdGltaXplTW9kZRIJCgVTUEVFRBABEg0KCUNPREVfU0la",
- "RRACEhAKDExJVEVfUlVOVElNRRADKgkI6AcQgICAgAJKBAgmECci8gEKDk1l",
- "c3NhZ2VPcHRpb25zEiYKF21lc3NhZ2Vfc2V0X3dpcmVfZm9ybWF0GAEgASgI",
- "OgVmYWxzZRIuCh9ub19zdGFuZGFyZF9kZXNjcmlwdG9yX2FjY2Vzc29yGAIg",
- "ASgIOgVmYWxzZRIZCgpkZXByZWNhdGVkGAMgASgIOgVmYWxzZRIRCgltYXBf",
- "ZW50cnkYByABKAgSQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQu",
- "Z29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICA",
- "AkoECAgQCUoECAkQCiKeAwoMRmllbGRPcHRpb25zEjoKBWN0eXBlGAEgASgO",
- "MiMuZ29vZ2xlLnByb3RvYnVmLkZpZWxkT3B0aW9ucy5DVHlwZToGU1RSSU5H",
- "Eg4KBnBhY2tlZBgCIAEoCBI/CgZqc3R5cGUYBiABKA4yJC5nb29nbGUucHJv",
- "dG9idWYuRmllbGRPcHRpb25zLkpTVHlwZToJSlNfTk9STUFMEhMKBGxhenkY",
- "BSABKAg6BWZhbHNlEhkKCmRlcHJlY2F0ZWQYAyABKAg6BWZhbHNlEhMKBHdl",
- "YWsYCiABKAg6BWZhbHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMo",
- "CzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uIi8KBUNU",
- "eXBlEgoKBlNUUklORxAAEggKBENPUkQQARIQCgxTVFJJTkdfUElFQ0UQAiI1",
- "CgZKU1R5cGUSDQoJSlNfTk9STUFMEAASDQoJSlNfU1RSSU5HEAESDQoJSlNf",
- "TlVNQkVSEAIqCQjoBxCAgICAAkoECAQQBSJeCgxPbmVvZk9wdGlvbnMSQwoU",
- "dW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVm",
- "LlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAiKTAQoLRW51bU9wdGlv",
- "bnMSEwoLYWxsb3dfYWxpYXMYAiABKAgSGQoKZGVwcmVjYXRlZBgDIAEoCDoF",
- "ZmFsc2USQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xl",
- "LnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAkoECAUQ",
- "BiJ9ChBFbnVtVmFsdWVPcHRpb25zEhkKCmRlcHJlY2F0ZWQYASABKAg6BWZh",
- "bHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5w",
- "cm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIiewoOU2Vy",
- "dmljZU9wdGlvbnMSGQoKZGVwcmVjYXRlZBghIAEoCDoFZmFsc2USQwoUdW5p",
- "bnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVu",
- "aW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAiKtAgoNTWV0aG9kT3B0aW9u",
- "cxIZCgpkZXByZWNhdGVkGCEgASgIOgVmYWxzZRJfChFpZGVtcG90ZW5jeV9s",
- "ZXZlbBgiIAEoDjIvLmdvb2dsZS5wcm90b2J1Zi5NZXRob2RPcHRpb25zLklk",
- "ZW1wb3RlbmN5TGV2ZWw6E0lERU1QT1RFTkNZX1VOS05PV04SQwoUdW5pbnRl",
- "cnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50",
- "ZXJwcmV0ZWRPcHRpb24iUAoQSWRlbXBvdGVuY3lMZXZlbBIXChNJREVNUE9U",
- "RU5DWV9VTktOT1dOEAASEwoPTk9fU0lERV9FRkZFQ1RTEAESDgoKSURFTVBP",
- "VEVOVBACKgkI6AcQgICAgAIingIKE1VuaW50ZXJwcmV0ZWRPcHRpb24SOwoE",
- "bmFtZRgCIAMoCzItLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0",
- "aW9uLk5hbWVQYXJ0EhgKEGlkZW50aWZpZXJfdmFsdWUYAyABKAkSGgoScG9z",
- "aXRpdmVfaW50X3ZhbHVlGAQgASgEEhoKEm5lZ2F0aXZlX2ludF92YWx1ZRgF",
- "IAEoAxIUCgxkb3VibGVfdmFsdWUYBiABKAESFAoMc3RyaW5nX3ZhbHVlGAcg",
- "ASgMEhcKD2FnZ3JlZ2F0ZV92YWx1ZRgIIAEoCRozCghOYW1lUGFydBIRCglu",
- "YW1lX3BhcnQYASACKAkSFAoMaXNfZXh0ZW5zaW9uGAIgAigIItUBCg5Tb3Vy",
- "Y2VDb2RlSW5mbxI6Cghsb2NhdGlvbhgBIAMoCzIoLmdvb2dsZS5wcm90b2J1",
- "Zi5Tb3VyY2VDb2RlSW5mby5Mb2NhdGlvbhqGAQoITG9jYXRpb24SEAoEcGF0",
- "aBgBIAMoBUICEAESEAoEc3BhbhgCIAMoBUICEAESGAoQbGVhZGluZ19jb21t",
- "ZW50cxgDIAEoCRIZChF0cmFpbGluZ19jb21tZW50cxgEIAEoCRIhChlsZWFk",
- "aW5nX2RldGFjaGVkX2NvbW1lbnRzGAYgAygJIqcBChFHZW5lcmF0ZWRDb2Rl",
- "SW5mbxJBCgphbm5vdGF0aW9uGAEgAygLMi0uZ29vZ2xlLnByb3RvYnVmLkdl",
- "bmVyYXRlZENvZGVJbmZvLkFubm90YXRpb24aTwoKQW5ub3RhdGlvbhIQCgRw",
- "YXRoGAEgAygFQgIQARITCgtzb3VyY2VfZmlsZRgCIAEoCRINCgViZWdpbhgD",
- "IAEoBRILCgNlbmQYBCABKAVCjwEKE2NvbS5nb29nbGUucHJvdG9idWZCEERl",
- "c2NyaXB0b3JQcm90b3NIAVo+Z2l0aHViLmNvbS9nb2xhbmcvcHJvdG9idWYv",
- "cHJvdG9jLWdlbi1nby9kZXNjcmlwdG9yO2Rlc2NyaXB0b3L4AQGiAgNHUEKq",
- "AhpHb29nbGUuUHJvdG9idWYuUmVmbGVjdGlvbg=="));
+ "IAEoCRIVCg1waHBfbmFtZXNwYWNlGCkgASgJEh4KFnBocF9tZXRhZGF0YV9u",
+ "YW1lc3BhY2UYLCABKAkSFAoMcnVieV9wYWNrYWdlGC0gASgJEkMKFHVuaW50",
+ "ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5Vbmlu",
+ "dGVycHJldGVkT3B0aW9uIjoKDE9wdGltaXplTW9kZRIJCgVTUEVFRBABEg0K",
+ "CUNPREVfU0laRRACEhAKDExJVEVfUlVOVElNRRADKgkI6AcQgICAgAJKBAgm",
+ "ECci8gEKDk1lc3NhZ2VPcHRpb25zEiYKF21lc3NhZ2Vfc2V0X3dpcmVfZm9y",
+ "bWF0GAEgASgIOgVmYWxzZRIuCh9ub19zdGFuZGFyZF9kZXNjcmlwdG9yX2Fj",
+ "Y2Vzc29yGAIgASgIOgVmYWxzZRIZCgpkZXByZWNhdGVkGAMgASgIOgVmYWxz",
+ "ZRIRCgltYXBfZW50cnkYByABKAgSQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y",
+ "5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24q",
+ "CQjoBxCAgICAAkoECAgQCUoECAkQCiKeAwoMRmllbGRPcHRpb25zEjoKBWN0",
+ "eXBlGAEgASgOMiMuZ29vZ2xlLnByb3RvYnVmLkZpZWxkT3B0aW9ucy5DVHlw",
+ "ZToGU1RSSU5HEg4KBnBhY2tlZBgCIAEoCBI/CgZqc3R5cGUYBiABKA4yJC5n",
+ "b29nbGUucHJvdG9idWYuRmllbGRPcHRpb25zLkpTVHlwZToJSlNfTk9STUFM",
+ "EhMKBGxhenkYBSABKAg6BWZhbHNlEhkKCmRlcHJlY2F0ZWQYAyABKAg6BWZh",
+ "bHNlEhMKBHdlYWsYCiABKAg6BWZhbHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0",
+ "aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0",
+ "aW9uIi8KBUNUeXBlEgoKBlNUUklORxAAEggKBENPUkQQARIQCgxTVFJJTkdf",
+ "UElFQ0UQAiI1CgZKU1R5cGUSDQoJSlNfTk9STUFMEAASDQoJSlNfU1RSSU5H",
+ "EAESDQoJSlNfTlVNQkVSEAIqCQjoBxCAgICAAkoECAQQBSJeCgxPbmVvZk9w",
+ "dGlvbnMSQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xl",
+ "LnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAiKTAQoL",
+ "RW51bU9wdGlvbnMSEwoLYWxsb3dfYWxpYXMYAiABKAgSGQoKZGVwcmVjYXRl",
+ "ZBgDIAEoCDoFZmFsc2USQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygL",
+ "MiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCA",
+ "gICAAkoECAUQBiJ9ChBFbnVtVmFsdWVPcHRpb25zEhkKCmRlcHJlY2F0ZWQY",
+ "ASABKAg6BWZhbHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIk",
+ "Lmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQgICA",
+ "gAIiewoOU2VydmljZU9wdGlvbnMSGQoKZGVwcmVjYXRlZBghIAEoCDoFZmFs",
+ "c2USQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnBy",
+ "b3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAiKtAgoNTWV0",
+ "aG9kT3B0aW9ucxIZCgpkZXByZWNhdGVkGCEgASgIOgVmYWxzZRJfChFpZGVt",
+ "cG90ZW5jeV9sZXZlbBgiIAEoDjIvLmdvb2dsZS5wcm90b2J1Zi5NZXRob2RP",
+ "cHRpb25zLklkZW1wb3RlbmN5TGV2ZWw6E0lERU1QT1RFTkNZX1VOS05PV04S",
+ "QwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3Rv",
+ "YnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24iUAoQSWRlbXBvdGVuY3lMZXZlbBIX",
+ "ChNJREVNUE9URU5DWV9VTktOT1dOEAASEwoPTk9fU0lERV9FRkZFQ1RTEAES",
+ "DgoKSURFTVBPVEVOVBACKgkI6AcQgICAgAIingIKE1VuaW50ZXJwcmV0ZWRP",
+ "cHRpb24SOwoEbmFtZRgCIAMoCzItLmdvb2dsZS5wcm90b2J1Zi5VbmludGVy",
+ "cHJldGVkT3B0aW9uLk5hbWVQYXJ0EhgKEGlkZW50aWZpZXJfdmFsdWUYAyAB",
+ "KAkSGgoScG9zaXRpdmVfaW50X3ZhbHVlGAQgASgEEhoKEm5lZ2F0aXZlX2lu",
+ "dF92YWx1ZRgFIAEoAxIUCgxkb3VibGVfdmFsdWUYBiABKAESFAoMc3RyaW5n",
+ "X3ZhbHVlGAcgASgMEhcKD2FnZ3JlZ2F0ZV92YWx1ZRgIIAEoCRozCghOYW1l",
+ "UGFydBIRCgluYW1lX3BhcnQYASACKAkSFAoMaXNfZXh0ZW5zaW9uGAIgAigI",
+ "ItUBCg5Tb3VyY2VDb2RlSW5mbxI6Cghsb2NhdGlvbhgBIAMoCzIoLmdvb2ds",
+ "ZS5wcm90b2J1Zi5Tb3VyY2VDb2RlSW5mby5Mb2NhdGlvbhqGAQoITG9jYXRp",
+ "b24SEAoEcGF0aBgBIAMoBUICEAESEAoEc3BhbhgCIAMoBUICEAESGAoQbGVh",
+ "ZGluZ19jb21tZW50cxgDIAEoCRIZChF0cmFpbGluZ19jb21tZW50cxgEIAEo",
+ "CRIhChlsZWFkaW5nX2RldGFjaGVkX2NvbW1lbnRzGAYgAygJIqcBChFHZW5l",
+ "cmF0ZWRDb2RlSW5mbxJBCgphbm5vdGF0aW9uGAEgAygLMi0uZ29vZ2xlLnBy",
+ "b3RvYnVmLkdlbmVyYXRlZENvZGVJbmZvLkFubm90YXRpb24aTwoKQW5ub3Rh",
+ "dGlvbhIQCgRwYXRoGAEgAygFQgIQARITCgtzb3VyY2VfZmlsZRgCIAEoCRIN",
+ "CgViZWdpbhgDIAEoBRILCgNlbmQYBCABKAVCjwEKE2NvbS5nb29nbGUucHJv",
+ "dG9idWZCEERlc2NyaXB0b3JQcm90b3NIAVo+Z2l0aHViLmNvbS9nb2xhbmcv",
+ "cHJvdG9idWYvcHJvdG9jLWdlbi1nby9kZXNjcmlwdG9yO2Rlc2NyaXB0b3L4",
+ "AQGiAgNHUEKqAhpHb29nbGUuUHJvdG9idWYuUmVmbGVjdGlvbg=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
@@ -171,7 +172,7 @@ namespace Google.Protobuf.Reflection {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.EnumValueDescriptorProto), global::Google.Protobuf.Reflection.EnumValueDescriptorProto.Parser, new[]{ "Name", "Number", "Options" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.ServiceDescriptorProto), global::Google.Protobuf.Reflection.ServiceDescriptorProto.Parser, new[]{ "Name", "Method", "Options" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.MethodDescriptorProto), global::Google.Protobuf.Reflection.MethodDescriptorProto.Parser, new[]{ "Name", "InputType", "OutputType", "Options", "ClientStreaming", "ServerStreaming" }, null, null, null),
- new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FileOptions), global::Google.Protobuf.Reflection.FileOptions.Parser, new[]{ "JavaPackage", "JavaOuterClassname", "JavaMultipleFiles", "JavaGenerateEqualsAndHash", "JavaStringCheckUtf8", "OptimizeFor", "GoPackage", "CcGenericServices", "JavaGenericServices", "PyGenericServices", "PhpGenericServices", "Deprecated", "CcEnableArenas", "ObjcClassPrefix", "CsharpNamespace", "SwiftPrefix", "PhpClassPrefix", "PhpNamespace", "UninterpretedOption" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode) }, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FileOptions), global::Google.Protobuf.Reflection.FileOptions.Parser, new[]{ "JavaPackage", "JavaOuterClassname", "JavaMultipleFiles", "JavaGenerateEqualsAndHash", "JavaStringCheckUtf8", "OptimizeFor", "GoPackage", "CcGenericServices", "JavaGenericServices", "PyGenericServices", "PhpGenericServices", "Deprecated", "CcEnableArenas", "ObjcClassPrefix", "CsharpNamespace", "SwiftPrefix", "PhpClassPrefix", "PhpNamespace", "PhpMetadataNamespace", "RubyPackage", "UninterpretedOption" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode) }, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.MessageOptions), global::Google.Protobuf.Reflection.MessageOptions.Parser, new[]{ "MessageSetWireFormat", "NoStandardDescriptorAccessor", "Deprecated", "MapEntry", "UninterpretedOption" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FieldOptions), global::Google.Protobuf.Reflection.FieldOptions.Parser, new[]{ "Ctype", "Packed", "Jstype", "Lazy", "Deprecated", "Weak", "UninterpretedOption" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FieldOptions.Types.CType), typeof(global::Google.Protobuf.Reflection.FieldOptions.Types.JSType) }, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.OneofOptions), global::Google.Protobuf.Reflection.OneofOptions.Parser, new[]{ "UninterpretedOption" }, null, null, null),
@@ -350,8 +351,8 @@ namespace Google.Protobuf.Reflection {
enumType_ = other.enumType_.Clone();
service_ = other.service_.Clone();
extension_ = other.extension_.Clone();
- Options = other.options_ != null ? other.Options.Clone() : null;
- SourceCodeInfo = other.sourceCodeInfo_ != null ? other.SourceCodeInfo.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
+ sourceCodeInfo_ = other.sourceCodeInfo_ != null ? other.sourceCodeInfo_.Clone() : null;
syntax_ = other.syntax_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -775,7 +776,7 @@ namespace Google.Protobuf.Reflection {
enumType_ = other.enumType_.Clone();
extensionRange_ = other.extensionRange_.Clone();
oneofDecl_ = other.oneofDecl_.Clone();
- Options = other.options_ != null ? other.Options.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
reservedRange_ = other.reservedRange_.Clone();
reservedName_ = other.reservedName_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
@@ -1099,7 +1100,7 @@ namespace Google.Protobuf.Reflection {
public ExtensionRange(ExtensionRange other) : this() {
start_ = other.start_;
end_ = other.end_;
- Options = other.options_ != null ? other.Options.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -1597,7 +1598,7 @@ namespace Google.Protobuf.Reflection {
defaultValue_ = other.defaultValue_;
oneofIndex_ = other.oneofIndex_;
jsonName_ = other.jsonName_;
- Options = other.options_ != null ? other.Options.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -2078,7 +2079,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OneofDescriptorProto(OneofDescriptorProto other) : this() {
name_ = other.name_;
- Options = other.options_ != null ? other.Options.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -2245,7 +2246,7 @@ namespace Google.Protobuf.Reflection {
public EnumDescriptorProto(EnumDescriptorProto other) : this() {
name_ = other.name_;
value_ = other.value_.Clone();
- Options = other.options_ != null ? other.Options.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
reservedRange_ = other.reservedRange_.Clone();
reservedName_ = other.reservedName_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
@@ -2658,7 +2659,7 @@ namespace Google.Protobuf.Reflection {
public EnumValueDescriptorProto(EnumValueDescriptorProto other) : this() {
name_ = other.name_;
number_ = other.number_;
- Options = other.options_ != null ? other.Options.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -2852,7 +2853,7 @@ namespace Google.Protobuf.Reflection {
public ServiceDescriptorProto(ServiceDescriptorProto other) : this() {
name_ = other.name_;
method_ = other.method_.Clone();
- Options = other.options_ != null ? other.Options.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -3039,7 +3040,7 @@ namespace Google.Protobuf.Reflection {
name_ = other.name_;
inputType_ = other.inputType_;
outputType_ = other.outputType_;
- Options = other.options_ != null ? other.Options.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
clientStreaming_ = other.clientStreaming_;
serverStreaming_ = other.serverStreaming_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
@@ -3341,6 +3342,8 @@ namespace Google.Protobuf.Reflection {
swiftPrefix_ = other.swiftPrefix_;
phpClassPrefix_ = other.phpClassPrefix_;
phpNamespace_ = other.phpNamespace_;
+ phpMetadataNamespace_ = other.phpMetadataNamespace_;
+ rubyPackage_ = other.rubyPackage_;
uninterpretedOption_ = other.uninterpretedOption_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -3632,6 +3635,38 @@ namespace Google.Protobuf.Reflection {
}
}
+ /// <summary>Field number for the "php_metadata_namespace" field.</summary>
+ public const int PhpMetadataNamespaceFieldNumber = 44;
+ private string phpMetadataNamespace_ = "";
+ /// <summary>
+ /// Use this option to change the namespace of php generated metadata classes.
+ /// Default is empty. When this option is empty, the proto file name will be used
+ /// for determining the namespace.
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public string PhpMetadataNamespace {
+ get { return phpMetadataNamespace_; }
+ set {
+ phpMetadataNamespace_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
+ }
+ }
+
+ /// <summary>Field number for the "ruby_package" field.</summary>
+ public const int RubyPackageFieldNumber = 45;
+ private string rubyPackage_ = "";
+ /// <summary>
+ /// Use this option to change the package of ruby generated classes. Default
+ /// is empty. When this option is not set, the package name will be used for
+ /// determining the ruby package.
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public string RubyPackage {
+ get { return rubyPackage_; }
+ set {
+ rubyPackage_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
+ }
+ }
+
/// <summary>Field number for the "uninterpreted_option" field.</summary>
public const int UninterpretedOptionFieldNumber = 999;
private static readonly pb::FieldCodec<global::Google.Protobuf.Reflection.UninterpretedOption> _repeated_uninterpretedOption_codec
@@ -3677,6 +3712,8 @@ namespace Google.Protobuf.Reflection {
if (SwiftPrefix != other.SwiftPrefix) return false;
if (PhpClassPrefix != other.PhpClassPrefix) return false;
if (PhpNamespace != other.PhpNamespace) return false;
+ if (PhpMetadataNamespace != other.PhpMetadataNamespace) return false;
+ if (RubyPackage != other.RubyPackage) return false;
if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
@@ -3702,6 +3739,8 @@ namespace Google.Protobuf.Reflection {
if (SwiftPrefix.Length != 0) hash ^= SwiftPrefix.GetHashCode();
if (PhpClassPrefix.Length != 0) hash ^= PhpClassPrefix.GetHashCode();
if (PhpNamespace.Length != 0) hash ^= PhpNamespace.GetHashCode();
+ if (PhpMetadataNamespace.Length != 0) hash ^= PhpMetadataNamespace.GetHashCode();
+ if (RubyPackage.Length != 0) hash ^= RubyPackage.GetHashCode();
hash ^= uninterpretedOption_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
@@ -3788,6 +3827,14 @@ namespace Google.Protobuf.Reflection {
output.WriteRawTag(208, 2);
output.WriteBool(PhpGenericServices);
}
+ if (PhpMetadataNamespace.Length != 0) {
+ output.WriteRawTag(226, 2);
+ output.WriteString(PhpMetadataNamespace);
+ }
+ if (RubyPackage.Length != 0) {
+ output.WriteRawTag(234, 2);
+ output.WriteString(RubyPackage);
+ }
uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
@@ -3851,6 +3898,12 @@ namespace Google.Protobuf.Reflection {
if (PhpNamespace.Length != 0) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(PhpNamespace);
}
+ if (PhpMetadataNamespace.Length != 0) {
+ size += 2 + pb::CodedOutputStream.ComputeStringSize(PhpMetadataNamespace);
+ }
+ if (RubyPackage.Length != 0) {
+ size += 2 + pb::CodedOutputStream.ComputeStringSize(RubyPackage);
+ }
size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
@@ -3917,6 +3970,12 @@ namespace Google.Protobuf.Reflection {
if (other.PhpNamespace.Length != 0) {
PhpNamespace = other.PhpNamespace;
}
+ if (other.PhpMetadataNamespace.Length != 0) {
+ PhpMetadataNamespace = other.PhpMetadataNamespace;
+ }
+ if (other.RubyPackage.Length != 0) {
+ RubyPackage = other.RubyPackage;
+ }
uninterpretedOption_.Add(other.uninterpretedOption_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
@@ -4001,6 +4060,14 @@ namespace Google.Protobuf.Reflection {
PhpGenericServices = input.ReadBool();
break;
}
+ case 354: {
+ PhpMetadataNamespace = input.ReadString();
+ break;
+ }
+ case 362: {
+ RubyPackage = input.ReadString();
+ break;
+ }
case 7994: {
uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec);
break;
diff --git a/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs
index 9124beee..be94cb10 100644
--- a/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs
@@ -30,6 +30,7 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
+using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@@ -43,6 +44,16 @@ namespace Google.Protobuf.Reflection
/// </summary>
public sealed class FileDescriptor : IDescriptor
{
+ // Prevent linker failures when using IL2CPP with the well-known types.
+ static FileDescriptor()
+ {
+ ForceReflectionInitialization<Syntax>();
+ ForceReflectionInitialization<NullValue>();
+ ForceReflectionInitialization<Field.Types.Cardinality>();
+ ForceReflectionInitialization<Field.Types.Kind>();
+ ForceReflectionInitialization<Value.KindOneofCase>();
+ }
+
private FileDescriptor(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, DescriptorPool pool, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo)
{
SerializedData = descriptorData;
@@ -334,5 +345,18 @@ namespace Google.Protobuf.Reflection
/// The (possibly empty) set of custom options for this file.
/// </summary>
public CustomOptions CustomOptions => Proto.Options?.CustomOptions ?? CustomOptions.Empty;
+
+ /// <summary>
+ /// Performs initialization for the given generic type argument.
+ /// </summary>
+ /// <remarks>
+ /// This method is present for the sake of AOT compilers. It allows code (whether handwritten or generated)
+ /// to make calls into the reflection machinery of this library to express an intention to use that type
+ /// reflectively (e.g. for JSON parsing and formatting). The call itself does almost nothing, but AOT compilers
+ /// attempting to determine which generic type arguments need to be handled will spot the code path and act
+ /// accordingly.
+ /// </remarks>
+ /// <typeparam name="T">The type to force initialization for.</typeparam>
+ public static void ForceReflectionInitialization<T>() => ReflectionUtil.ForceInitialize<T>();
}
}
diff --git a/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs
index 86942acc..86942acc 100755..100644
--- a/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs
diff --git a/csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs b/csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs
index 8714ab18..97596218 100644
--- a/csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs
@@ -52,7 +52,7 @@ namespace Google.Protobuf.Reflection
throw new ArgumentException("Cannot read from property");
}
this.descriptor = descriptor;
- caseDelegate = ReflectionUtil.CreateFuncIMessageT<int>(caseProperty.GetGetMethod());
+ caseDelegate = ReflectionUtil.CreateFuncIMessageInt32(caseProperty.GetGetMethod());
this.descriptor = descriptor;
clearDelegate = ReflectionUtil.CreateActionIMessage(clearMethod);
diff --git a/csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs b/csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs
index df820ca3..feaeba0e 100644
--- a/csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs
+++ b/csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs
@@ -30,9 +30,8 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
+using Google.Protobuf.Compatibility;
using System;
-using System.Collections.Generic;
-using System.Linq.Expressions;
using System.Reflection;
namespace Google.Protobuf.Reflection
@@ -47,61 +46,160 @@ namespace Google.Protobuf.Reflection
/// </summary>
internal static class ReflectionUtil
{
+ static ReflectionUtil()
+ {
+ ForceInitialize<string>(); // Handles all reference types
+ ForceInitialize<int>();
+ ForceInitialize<long>();
+ ForceInitialize<uint>();
+ ForceInitialize<ulong>();
+ ForceInitialize<float>();
+ ForceInitialize<double>();
+ ForceInitialize<bool>();
+ ForceInitialize<int?>();
+ ForceInitialize<long?>();
+ ForceInitialize<uint?>();
+ ForceInitialize<ulong?>();
+ ForceInitialize<float?>();
+ ForceInitialize<double?>();
+ ForceInitialize<bool?>();
+ ForceInitialize<SampleEnum>();
+ SampleEnumMethod();
+ }
+
+ internal static void ForceInitialize<T>() => new ReflectionHelper<IMessage, T>();
+
/// <summary>
/// Empty Type[] used when calling GetProperty to force property instead of indexer fetching.
/// </summary>
internal static readonly Type[] EmptyTypes = new Type[0];
/// <summary>
- /// Creates a delegate which will cast the argument to the appropriate method target type,
+ /// Creates a delegate which will cast the argument to the type that declares the method,
/// call the method on it, then convert the result to object.
/// </summary>
- internal static Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method)
- {
- ParameterExpression parameter = Expression.Parameter(typeof(IMessage), "p");
- Expression downcast = Expression.Convert(parameter, method.DeclaringType);
- Expression call = Expression.Call(downcast, method);
- Expression upcast = Expression.Convert(call, typeof(object));
- return Expression.Lambda<Func<IMessage, object>>(upcast, parameter).Compile();
- }
+ /// <param name="method">The method to create a delegate for, which must be declared in an IMessage
+ /// implementation.</param>
+ internal static Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method) =>
+ GetReflectionHelper(method.DeclaringType, method.ReturnType).CreateFuncIMessageObject(method);
/// <summary>
- /// Creates a delegate which will cast the argument to the appropriate method target type,
- /// call the method on it, then convert the result to the specified type.
+ /// Creates a delegate which will cast the argument to the type that declares the method,
+ /// call the method on it, then convert the result to the specified type. The method is expected
+ /// to actually return an enum (because of where we're calling it - for oneof cases). Sometimes that
+ /// means we need some extra work to perform conversions.
/// </summary>
- internal static Func<IMessage, T> CreateFuncIMessageT<T>(MethodInfo method)
- {
- ParameterExpression parameter = Expression.Parameter(typeof(IMessage), "p");
- Expression downcast = Expression.Convert(parameter, method.DeclaringType);
- Expression call = Expression.Call(downcast, method);
- Expression upcast = Expression.Convert(call, typeof(T));
- return Expression.Lambda<Func<IMessage, T>>(upcast, parameter).Compile();
- }
+ /// <param name="method">The method to create a delegate for, which must be declared in an IMessage
+ /// implementation.</param>
+ internal static Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method) =>
+ GetReflectionHelper(method.DeclaringType, method.ReturnType).CreateFuncIMessageInt32(method);
/// <summary>
/// Creates a delegate which will execute the given method after casting the first argument to
- /// the target type of the method, and the second argument to the first parameter type of the method.
+ /// the type that declares the method, and the second argument to the first parameter type of the method.
/// </summary>
- internal static Action<IMessage, object> CreateActionIMessageObject(MethodInfo method)
- {
- ParameterExpression targetParameter = Expression.Parameter(typeof(IMessage), "target");
- ParameterExpression argParameter = Expression.Parameter(typeof(object), "arg");
- Expression castTarget = Expression.Convert(targetParameter, method.DeclaringType);
- Expression castArgument = Expression.Convert(argParameter, method.GetParameters()[0].ParameterType);
- Expression call = Expression.Call(castTarget, method, castArgument);
- return Expression.Lambda<Action<IMessage, object>>(call, targetParameter, argParameter).Compile();
- }
+ /// <param name="method">The method to create a delegate for, which must be declared in an IMessage
+ /// implementation.</param>
+ internal static Action<IMessage, object> CreateActionIMessageObject(MethodInfo method) =>
+ GetReflectionHelper(method.DeclaringType, method.GetParameters()[0].ParameterType).CreateActionIMessageObject(method);
/// <summary>
/// Creates a delegate which will execute the given method after casting the first argument to
- /// the target type of the method.
+ /// type that declares the method.
+ /// </summary>
+ /// <param name="method">The method to create a delegate for, which must be declared in an IMessage
+ /// implementation.</param>
+ internal static Action<IMessage> CreateActionIMessage(MethodInfo method) =>
+ GetReflectionHelper(method.DeclaringType, typeof(object)).CreateActionIMessage(method);
+
+ /// <summary>
+ /// Creates a reflection helper for the given type arguments. Currently these are created on demand
+ /// rather than cached; this will be "busy" when initially loading a message's descriptor, but after that
+ /// they can be garbage collected. We could cache them by type if that proves to be important, but creating
+ /// an object is pretty cheap.
/// </summary>
- internal static Action<IMessage> CreateActionIMessage(MethodInfo method)
+ private static IReflectionHelper GetReflectionHelper(Type t1, Type t2) =>
+ (IReflectionHelper) Activator.CreateInstance(typeof(ReflectionHelper<,>).MakeGenericType(t1, t2));
+
+ // Non-generic interface allowing us to use an instance of ReflectionHelper<T1, T2> without statically
+ // knowing the types involved.
+ private interface IReflectionHelper
{
- ParameterExpression targetParameter = Expression.Parameter(typeof(IMessage), "target");
- Expression castTarget = Expression.Convert(targetParameter, method.DeclaringType);
- Expression call = Expression.Call(castTarget, method);
- return Expression.Lambda<Action<IMessage>>(call, targetParameter).Compile();
- }
+ Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method);
+ Action<IMessage> CreateActionIMessage(MethodInfo method);
+ Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method);
+ Action<IMessage, object> CreateActionIMessageObject(MethodInfo method);
+ }
+
+ private class ReflectionHelper<T1, T2> : IReflectionHelper
+ {
+
+ public Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method)
+ {
+ // On pleasant runtimes, we can create a Func<int> from a method returning
+ // an enum based on an int. That's the fast path.
+ if (CanConvertEnumFuncToInt32Func)
+ {
+ var del = (Func<T1, int>) method.CreateDelegate(typeof(Func<T1, int>));
+ return message => del((T1) message);
+ }
+ else
+ {
+ // On some runtimes (e.g. old Mono) the return type has to be exactly correct,
+ // so we go via boxing. Reflection is already fairly inefficient, and this is
+ // only used for one-of case checking, fortunately.
+ var del = (Func<T1, T2>) method.CreateDelegate(typeof(Func<T1, T2>));
+ return message => (int) (object) del((T1) message);
+ }
+ }
+
+ public Action<IMessage> CreateActionIMessage(MethodInfo method)
+ {
+ var del = (Action<T1>) method.CreateDelegate(typeof(Action<T1>));
+ return message => del((T1) message);
+ }
+
+ public Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method)
+ {
+ var del = (Func<T1, T2>) method.CreateDelegate(typeof(Func<T1, T2>));
+ return message => del((T1) message);
+ }
+
+ public Action<IMessage, object> CreateActionIMessageObject(MethodInfo method)
+ {
+ var del = (Action<T1, T2>) method.CreateDelegate(typeof(Action<T1, T2>));
+ return (message, arg) => del((T1) message, (T2) arg);
+ }
+ }
+
+ // Runtime compatibility checking code - see ReflectionHelper<T1, T2>.CreateFuncIMessageInt32 for
+ // details about why we're doing this.
+
+ // Deliberately not inside the generic type. We only want to check this once.
+ private static bool CanConvertEnumFuncToInt32Func { get; } = CheckCanConvertEnumFuncToInt32Func();
+
+ private static bool CheckCanConvertEnumFuncToInt32Func()
+ {
+ try
+ {
+ // Try to do the conversion using reflection, so we can see whether it's supported.
+ MethodInfo method = typeof(ReflectionUtil).GetMethod(nameof(SampleEnumMethod));
+ // If this passes, we're in a reasonable runtime.
+ method.CreateDelegate(typeof(Func<int>));
+ return true;
+ }
+ catch (ArgumentException)
+ {
+ return false;
+ }
+ }
+
+ public enum SampleEnum
+ {
+ X
+ }
+
+ // Public to make the reflection simpler.
+ public static SampleEnum SampleEnumMethod() => SampleEnum.X;
}
-} \ No newline at end of file
+}
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs
index 4db1f633..e4a4a365 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs
@@ -93,7 +93,7 @@ namespace Google.Protobuf.WellKnownTypes {
methods_ = other.methods_.Clone();
options_ = other.options_.Clone();
version_ = other.version_;
- SourceContext = other.sourceContext_ != null ? other.SourceContext.Clone() : null;
+ sourceContext_ = other.sourceContext_ != null ? other.sourceContext_.Clone() : null;
mixins_ = other.mixins_.Clone();
syntax_ = other.syntax_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs
index 3565f433..b73930b2 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs
@@ -244,8 +244,8 @@ namespace Google.Protobuf.WellKnownTypes {
///
/// ## Field Mask Verification
///
- /// The implementation of the all the API methods, which have any FieldMask type
- /// field in the request, should verify the included field paths, and return
+ /// The implementation of any API method which has a FieldMask type field in the
+ /// request should verify the included field paths, and return an
/// `INVALID_ARGUMENT` error if any path is duplicated or unmappable.
/// </summary>
public sealed partial class FieldMask : pb::IMessage<FieldMask> {
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/Type.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs
index 84310550..3e2fe541 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs
@@ -123,7 +123,7 @@ namespace Google.Protobuf.WellKnownTypes {
fields_ = other.fields_.Clone();
oneofs_ = other.oneofs_.Clone();
options_ = other.options_.Clone();
- SourceContext = other.sourceContext_ != null ? other.SourceContext.Clone() : null;
+ sourceContext_ = other.sourceContext_ != null ? other.sourceContext_.Clone() : null;
syntax_ = other.syntax_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -913,7 +913,7 @@ namespace Google.Protobuf.WellKnownTypes {
name_ = other.name_;
enumvalue_ = other.enumvalue_.Clone();
options_ = other.options_.Clone();
- SourceContext = other.sourceContext_ != null ? other.SourceContext.Clone() : null;
+ sourceContext_ = other.sourceContext_ != null ? other.sourceContext_.Clone() : null;
syntax_ = other.syntax_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -1350,7 +1350,7 @@ namespace Google.Protobuf.WellKnownTypes {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Option(Option other) : this() {
name_ = other.name_;
- Value = other.value_ != null ? other.Value.Clone() : null;
+ value_ = other.value_ != null ? other.value_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
diff --git a/docs/performance.md b/docs/performance.md
new file mode 100644
index 00000000..3bca58af
--- /dev/null
+++ b/docs/performance.md
@@ -0,0 +1,304 @@
+# 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:
+
+* **C++** - For C++ there're 3 kinds of parsing ways:
+ * **new** - This is for using new operator for creating message instance.
+ * **new arena** - This is for using arena for creating new message instance.
+ * **reuse** - This is for reusing the same message instance for parsing.
+* **Java** - For Java there're 3 kinds of parsing/Serialization ways:
+ * **byte[]** - This is for parsing from a Byte Array.
+ * **ByteString** - This is for parsing from a
+ com.google.protobuf.ByteString.
+ * **InputStream** - This is for parsing from a InputStream
+* **Python** - For Pythong there're 3 kinds of python protobuf for testing:
+ * **C++-genereated-code** - This is for using cpp generated code of the
+ proto file as dynamic linked library.
+ * **C++-reflection** - This is for using cpp reflection, which there's no
+ generated code, but still using cpp protobuf library as dynamic linked
+ library.
+ * **pure-Python** - This is for pure Python version, which don't link with
+ any cpp protobuf library.
+
+## Parsing performance
+
+<table>
+<tbody><tr>
+<th rowspan="2"> </th>
+<th colspan="3" rowspan="1">C++</th>
+<th colspan="3" rowspan="1">C++ with tcmalloc</th>
+<th colspan="3" rowspan="1">java</th>
+<th colspan="3" rowspan="1">python</th>
+</tr>
+<tr>
+<th colspan="1">new</th>
+<th colspan="1">new arena</th>
+<th colspan="1">reuse</th>
+<th colspan="1">new</th>
+<th colspan="1">new arena</th>
+<th colspan="1">reuse</th>
+<th colspan="1">byte[]</th>
+<th colspan="1">ByteString</th>
+<th colspan="1">InputStream</th>
+<th colspan="1">C++-generated-code</th>
+<th colspan="1">C++-reflection</th>
+<th colspan="1">pure-Python</th>
+</tr>
+<tr>
+<td>google_message1_proto2</td>
+<td>368.717MB/s</td>
+<td>261.847MB/s</td>
+<td>799.403MB/s</td>
+<td>645.183MB/s</td>
+<td>441.023MB/s</td>
+<td>1.122GB/s</td>
+<td>425.437MB/s</td>
+<td>425.937MB/s</td>
+<td>251.018MB/s</td>
+<td>82.8314MB/s</td>
+<td>47.6763MB/s</td>
+<td>3.76299MB/s</td>
+</tr>
+<tr>
+<td>google_message1_proto3</td>
+<td>294.517MB/s</td>
+<td>229.116MB/s</td>
+<td>469.982MB/s</td>
+<td>434.510MB/s</td>
+<td>394.701MB/s</td>
+<td>591.931MB/s</td>
+<td>357.597MB/s</td>
+<td>378.568MB/s</td>
+<td>221.676MB/s</td>
+<td>82.0498MB/s</td>
+<td>39.9467MB/s</td>
+<td>3.77751MB/s</td>
+</tr>
+<tr>
+<td>google_message2</td>
+<td>277.242MB/s</td>
+<td>347.611MB/s</td>
+<td>793.67MB/s</td>
+<td>503.721MB/s</td>
+<td>596.333MB/s</td>
+<td>922.533MB/s</td>
+<td>416.778MB/s</td>
+<td>419.543MB/s</td>
+<td>367.145MB/s</td>
+<td>241.46MB/s</td>
+<td>71.5723MB/s</td>
+<td>2.73538MB/s</td>
+</tr>
+<tr>
+<td>google_message3_1</td>
+<td>213.478MB/s</td>
+<td>291.58MB/s</td>
+<td>543.398MB/s</td>
+<td>539.704MB/s</td>
+<td>717.300MB/s</td>
+<td>927.333MB/s</td>
+<td>684.241MB/s</td>
+<td>704.47MB/s</td>
+<td>648.624MB/s</td>
+<td>209.036MB/s</td>
+<td>142.356MB/s</td>
+<td>15.3324MB/s</td>
+</tr>
+<tr>
+<td>google_message3_2</td>
+<td>672.685MB/s</td>
+<td>802.767MB/s</td>
+<td>1.21505GB/s</td>
+<td>985.790MB/s</td>
+<td>1.136GB/s</td>
+<td>1.367GB/s</td>
+<td>1.54439GB/s</td>
+<td>1.60603GB/s</td>
+<td>1.33443GB/s</td>
+<td>573.835MB/s</td>
+<td>314.33MB/s</td>
+<td>15.0169MB/s</td>
+</tr>
+<tr>
+<td>google_message3_3</td>
+<td>207.681MB/s</td>
+<td>140.591MB/s</td>
+<td>535.181MB/s</td>
+<td>369.743MB/s</td>
+<td>262.301MB/s</td>
+<td>556.644MB/s</td>
+<td>279.385MB/s</td>
+<td>304.853MB/s</td>
+<td>107.575MB/s</td>
+<td>32.248MB/s</td>
+<td>26.1431MB/s</td>
+<td>2.63541MB/s</td>
+</tr>
+<tr>
+<td>google_message3_4</td>
+<td>7.96091GB/s</td>
+<td>7.10024GB/s</td>
+<td>9.3013GB/s</td>
+<td>8.518GB/s</td>
+<td>8.171GB/s</td>
+<td>9.917GB/s</td>
+<td>5.78006GB/s</td>
+<td>5.85198GB/s</td>
+<td>4.62609GB/s</td>
+<td>2.49631GB/s</td>
+<td>2.35442GB/s</td>
+<td>802.061MB/s</td>
+</tr>
+<tr>
+<td>google_message3_5</td>
+<td>76.0072MB/s</td>
+<td>51.6769MB/s</td>
+<td>237.856MB/s</td>
+<td>178.495MB/s</td>
+<td>111.751MB/s</td>
+<td>329.569MB/s</td>
+<td>121.038MB/s</td>
+<td>132.866MB/s</td>
+<td>36.9197MB/s</td>
+<td>10.3962MB/s</td>
+<td>8.84659MB/s</td>
+<td>1.25203MB/s</td>
+</tr>
+<tr>
+<td>google_message4</td>
+<td>331.46MB/s</td>
+<td>404.862MB/s</td>
+<td>427.99MB/s</td>
+<td>589.887MB/s</td>
+<td>720.367MB/s</td>
+<td>705.373MB/s</td>
+<td>606.228MB/s</td>
+<td>589.13MB/s</td>
+<td>530.692MB/s</td>
+<td>305.543MB/s</td>
+<td>174.834MB/s</td>
+<td>7.86485MB/s</td>
+</tr>
+</tbody></table>
+
+## Serialization performance
+
+<table>
+<tbody><tr>
+<th rowspan="2"> </th>
+<th colspan="1" rowspan="2">C++</th>
+<th colspan="1" rowspan="2">C++ with tcmalloc</th>
+<th colspan="3" rowspan="1">java</th>
+<th colspan="3" rowspan="1">python</th>
+</tr>
+<tr>
+<th colspan="1">byte[]</th>
+<th colspan="1">ByteString</th>
+<th colspan="1">InputStream</th>
+<th colspan="1">C++-generated-code</th>
+<th colspan="1">C++-reflection</th>
+<th colspan="1">pure-Python</th>
+</tr>
+<tr>
+<td>google_message1_proto2</td>
+<td>1.39698GB/s</td>
+<td>1.701GB/s</td>
+<td>1.12915GB/s</td>
+<td>1.13589GB/s</td>
+<td>758.609MB/s</td>
+<td>260.911MB/s</td>
+<td>58.4815MB/s</td>
+<td>5.77824MB/s</td>
+</tr>
+<tr>
+<td>google_message1_proto3</td>
+<td>959.305MB/s</td>
+<td>939.404MB/s</td>
+<td>1.15372GB/s</td>
+<td>1.07824GB/s</td>
+<td>802.337MB/s</td>
+<td>239.4MB/s</td>
+<td>33.6336MB/s</td>
+<td>5.80524MB/s</td>
+</tr>
+<tr>
+<td>google_message2</td>
+<td>1.27429GB/s</td>
+<td>1.402GB/s</td>
+<td>1.01039GB/s</td>
+<td>1022.99MB/s</td>
+<td>798.736MB/s</td>
+<td>996.755MB/s</td>
+<td>57.9601MB/s</td>
+<td>4.09246MB/s</td>
+</tr>
+<tr>
+<td>google_message3_1</td>
+<td>1.31916GB/s</td>
+<td>2.049GB/s</td>
+<td>991.496MB/s</td>
+<td>860.332MB/s</td>
+<td>662.88MB/s</td>
+<td>1.48625GB/s</td>
+<td>421.287MB/s</td>
+<td>18.002MB/s</td>
+</tr>
+<tr>
+<td>google_message3_2</td>
+<td>2.15676GB/s</td>
+<td>2.632GB/s</td>
+<td>2.14736GB/s</td>
+<td>2.08136GB/s</td>
+<td>1.55997GB/s</td>
+<td>2.39597GB/s</td>
+<td>326.777MB/s</td>
+<td>16.0527MB/s</td>
+</tr>
+<tr>
+<td>google_message3_3</td>
+<td>650.456MB/s</td>
+<td>1.040GB/s</td>
+<td>593.52MB/s</td>
+<td>580.667MB/s</td>
+<td>346.839MB/s</td>
+<td>123.978MB/s</td>
+<td>35.893MB/s</td>
+<td>2.32834MB/s</td>
+</tr>
+<tr>
+<td>google_message3_4</td>
+<td>8.70154GB/s</td>
+<td>9.825GB/s</td>
+<td>5.88645GB/s</td>
+<td>5.93946GB/s</td>
+<td>2.44388GB/s</td>
+<td>5.9241GB/s</td>
+<td>4.05837GB/s</td>
+<td>876.87MB/s</td>
+</tr>
+<tr>
+<td>google_message3_5</td>
+<td>246.33MB/s</td>
+<td>443.993MB/s</td>
+<td>283.278MB/s</td>
+<td>259.167MB/s</td>
+<td>206.37MB/s</td>
+<td>37.0285MB/s</td>
+<td>12.2228MB/s</td>
+<td>1.1979MB/s</td>
+</tr>
+<tr>
+<td>google_message4</td>
+<td>1.56674GB/s</td>
+<td>2.19601GB/s</td>
+<td>776.907MB/s</td>
+<td>770.707MB/s</td>
+<td>702.931MB/s</td>
+<td>1.49623GB/s</td>
+<td>205.116MB/s</td>
+<td>8.93428MB/s</td>
+</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.
diff --git a/docs/third_party.md b/docs/third_party.md
index 1b03b9ff..2d54f679 100644
--- a/docs/third_party.md
+++ b/docs/third_party.md
@@ -25,6 +25,7 @@ These are projects we know about implementing Protocol Buffers for other program
* Clojure: http://github.com/ninjudd/clojure-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 +40,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 +89,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
@@ -124,6 +126,8 @@ GRPC (http://www.grpc.io/) is Google's RPC implementation for Protocol Buffers.
* https://github.com/tony612/grpc-elixir (Elixir)
* 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)
## Other Utilities
diff --git a/examples/add_person_test.go b/examples/add_person_test.go
index 0507db6f..f8ba9338 100644
--- a/examples/add_person_test.go
+++ b/examples/add_person_test.go
@@ -30,10 +30,10 @@ unknown
t.Errorf("promptForAddress(%q) got %d, want ID %d", in, got.Id, 12345)
}
if got.Name != "Example Name" {
- t.Errorf("promptForAddress(%q) => want name %q, got %q", "Example Name", got.Name)
+ t.Errorf("promptForAddress(%q) => want name %q, got %q", in, "Example Name", got.Name)
}
if got.Email != "name@example.com" {
- t.Errorf("promptForAddress(%q) => want email %q, got %q", "name@example.com", got.Email)
+ t.Errorf("promptForAddress(%q) => want email %q, got %q", in, "name@example.com", got.Email)
}
want := []*pb.Person_PhoneNumber{
diff --git a/generate_changelog.py b/generate_changelog.py
index d90a9b70..8e5bf423 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", [
diff --git a/gmock.BUILD b/gmock.BUILD
deleted file mode 100644
index b1ae15a9..00000000
--- a/gmock.BUILD
+++ /dev/null
@@ -1,28 +0,0 @@
-cc_library(
- name = "gtest",
- srcs = [
- "googletest/src/gtest-all.cc",
- "googlemock/src/gmock-all.cc",
- ],
- hdrs = glob([
- "**/*.h",
- "googletest/src/*.cc",
- "googlemock/src/*.cc",
- ]),
- includes = [
- "googlemock",
- "googletest",
- "googletest/include",
- "googlemock/include",
- ],
- linkopts = ["-pthread"],
- visibility = ["//visibility:public"],
-)
-
-cc_library(
- name = "gtest_main",
- srcs = ["googlemock/src/gmock_main.cc"],
- linkopts = ["-pthread"],
- visibility = ["//visibility:public"],
- deps = [":gtest"],
-)
diff --git a/java/README.md b/java/README.md
index 0e0fba64..5e4fb8b4 100644
--- a/java/README.md
+++ b/java/README.md
@@ -1,17 +1,65 @@
-Protocol Buffers - Google's data interchange format
-===================================================
-
-[![Build Status](https://travis-ci.org/google/protobuf.svg?branch=master)](https://travis-ci.org/google/protobuf)
+# Protocol Buffers - Google's data interchange format
Copyright 2008 Google Inc.
-This directory contains the Java Protocol Buffers runtime library.
+https://developers.google.com/protocol-buffers/
+
+## Use Java Protocol Buffers
+
+To use protobuf in Java, first obtain the protocol compiler (a.k.a., protoc,
+see instructions in the toplevel [README.md](../README.md)) and use it to
+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:
+
+```xml
+<dependency>
+ <groupId>com.google.protobuf</groupId>
+ <artifactId>protobuf-java</artifactId>
+ <version>3.5.1</version>
+</dependency>
+```
+
+Make sure the version number of the runtime matches (or is newer than) the
+version number of the protoc.
+
+If you want to use features like protobuf JsonFormat, add a dependency on the
+protobuf-java-util package:
+
+```xml
+<dependency>
+ <groupId>com.google.protobuf</groupId>
+ <artifactId>protobuf-java-util</artifactId>
+ <version>3.5.1</version>
+</dependency>
+```
+
+### Use Java Protocol Buffers on Android
+
+For Android users, it's recommended to use protobuf Java Lite runtime because
+of its smaller code size. Java Lite runtime also works better with Proguard
+because it doesn't rely on Java reflection and is optimized to allow as much
+code stripping as possible. You can following these [instructions to use Java
+Lite runtime](lite.md).
+
+### Use Java Protocol Buffers with Bazel
+
+Bazel has native build rules to work with protobuf. For Java, you can use the
+`java_proto_library` rule for server and the `java_lite_proto_library` rule
+for Android. Check out [our build files examples](../examples/BUILD) to learn
+how to use them.
+
+## Build from Source
-Installation - With Maven
-=========================
+Most users should follow the instructions above to use protobuf Java runtime.
+If you are contributing code to protobuf or want to use a protobuf version
+that hasn't been officially released yet, you can folllow the instructions
+below to build protobuf from source code.
-The Protocol Buffers build is managed using Maven. If you would
-rather build without Maven, see below.
+### Build from Source - With Maven
1) Install Apache Maven if you don't have it:
@@ -45,20 +93,15 @@ rather build without Maven, see below.
The .jar will be placed in the "target" directory.
-The above instructions will install 3 maven artifacts:
+The above instructions will install 2 maven artifacts:
* protobuf-java: The core Java Protocol Buffers library. Most users only
need this artifact.
- * protobuf-lite: The lite version of core Java Protobuf Buffers library. It
- is a subset of the core library and is used together with
- the 'lite' code generator flag to reduce generated code size
- for mobile.
* protobuf-java-util: Utilities to work with protos. It contains JSON support
as well as utilities to work with proto3 well-known
types.
-Installation - Without Maven
-============================
+### Build from Source - Without Maven
If you would rather not install Maven to build the library, you may
follow these instructions instead. Note that these instructions skip
@@ -83,8 +126,7 @@ library (without the util package).
4) Install the classes wherever you prefer.
-Compatibility Notice
-====================
+## Compatibility Notice
* Protobuf minor version releases are backwards-compatible. If your code
can build/run against the old version, it's expected to build/run against
@@ -118,8 +160,7 @@ Compatibility Notice
* Protobuf LITE runtime APIs are not stable yet. They are subject to change even
in minor version releases.
-Documentation
-=============
+## Documentation
The complete documentation for Protocol Buffers is available via the
web at:
diff --git a/java/core/generate-test-sources-build.xml b/java/core/generate-test-sources-build.xml
index abcdf5dd..1d11f131 100644
--- a/java/core/generate-test-sources-build.xml
+++ b/java/core/generate-test-sources-build.xml
@@ -39,6 +39,7 @@
<arg value="${test.proto.dir}/com/google/protobuf/field_presence_test.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/map_for_proto2_lite_test.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/map_for_proto2_test.proto"/>
+ <arg value="${test.proto.dir}/com/google/protobuf/map_lite_test.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/map_test.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/map_initialization_order_test.proto"/>
</exec>
diff --git a/java/core/pom.xml b/java/core/pom.xml
index 4b65e72e..a7d4ea37 100644
--- a/java/core/pom.xml
+++ b/java/core/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-parent</artifactId>
- <version>3.5.1</version>
+ <version>3.6.0</version>
</parent>
<artifactId>protobuf-java</artifactId>
@@ -135,6 +135,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 908764df..fc3c2a5d 100644
--- a/java/core/src/main/java/com/google/protobuf/AbstractMessage.java
+++ b/java/core/src/main/java/com/google/protobuf/AbstractMessage.java
@@ -125,6 +125,16 @@ public abstract class AbstractMessage
protected int memoizedSize = -1;
@Override
+ int getMemoizedSerializedSize() {
+ return memoizedSize;
+ }
+
+ @Override
+ void setMemoizedSerializedSize(int size) {
+ memoizedSize = size;
+ }
+
+ @Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) {
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 24830c0a..b22bbaab 100644
--- a/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java
+++ b/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java
@@ -99,6 +99,16 @@ public abstract class AbstractMessageLite<
codedOutput.flush();
}
+ // We'd like these to be abstract but some folks are extending this class directly. They shouldn't
+ // be doing that and they should feel bad.
+ int getMemoizedSerializedSize() {
+ throw new UnsupportedOperationException();
+ }
+
+ void setMemoizedSerializedSize(int size) {
+ throw new UnsupportedOperationException();
+ }
+
/**
* Package private helper method for AbstractParser to create
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 fd4c142b..4d7a9727 100644
--- a/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java
@@ -82,6 +82,18 @@ final class BooleanArrayList extends AbstractProtobufList<Boolean>
}
@Override
+ protected void removeRange(int fromIndex, int toIndex) {
+ ensureIsMutable();
+ if (toIndex < fromIndex) {
+ throw new IndexOutOfBoundsException("toIndex < fromIndex");
+ }
+
+ System.arraycopy(array, toIndex, array, fromIndex, size - toIndex);
+ size -= (toIndex - fromIndex);
+ modCount++;
+ }
+
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -246,7 +258,9 @@ final class BooleanArrayList extends AbstractProtobufList<Boolean>
ensureIsMutable();
ensureIndexInRange(index);
boolean value = array[index];
- System.arraycopy(array, index + 1, array, index, size - index);
+ if (index < size - 1) {
+ System.arraycopy(array, index + 1, array, index, size - index);
+ }
size--;
modCount++;
return value;
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 7a3f0eb9..1297462e 100644
--- a/java/core/src/main/java/com/google/protobuf/CodedInputStream.java
+++ b/java/core/src/main/java/com/google/protobuf/CodedInputStream.java
@@ -66,11 +66,9 @@ public abstract class CodedInputStream {
/**
* Whether to enable our custom UTF-8 decode codepath which does not use {@link StringCoding}.
- * Enabled by default, disable by setting
- * {@code -Dcom.google.protobuf.enableCustomutf8Decode=false} in JVM args.
+ * Currently disabled.
*/
- private static final boolean ENABLE_CUSTOM_UTF8_DECODE
- = !"false".equals(System.getProperty("com.google.protobuf.enableCustomUtf8Decode"));
+ private static final boolean ENABLE_CUSTOM_UTF8_DECODE = false;
/** Visible for subclasses. See setRecursionLimit() */
int recursionDepth;
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 093a5f61..7b1ac651 100644
--- a/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java
+++ b/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java
@@ -377,6 +377,7 @@ public abstract class CodedOutputStream extends ByteOutput {
public abstract void writeMessage(final int fieldNumber, final MessageLite value)
throws IOException;
+
/**
* Write a MessageSet extension field to the stream. For historical reasons,
* the wire format differs from normal fields.
@@ -481,6 +482,7 @@ public abstract class CodedOutputStream extends ByteOutput {
// Abstract to avoid overhead of additional virtual method calls.
public abstract void writeMessageNoTag(final MessageLite value) throws IOException;
+
//=================================================================
@ExperimentalApi
@@ -666,6 +668,7 @@ public abstract class CodedOutputStream extends ByteOutput {
return computeTagSize(fieldNumber) + computeMessageSizeNoTag(value);
}
+
/**
* Compute the number of bytes that would be needed to encode a
* MessageSet extension to the stream. For historical reasons,
@@ -913,6 +916,7 @@ public abstract class CodedOutputStream extends ByteOutput {
return computeLengthDelimitedFieldSize(value.getSerializedSize());
}
+
static int computeLengthDelimitedFieldSize(int fieldLength) {
return computeUInt32SizeNoTag(fieldLength) + fieldLength;
}
@@ -1049,6 +1053,7 @@ public abstract class CodedOutputStream extends ByteOutput {
writeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP);
}
+
/**
* Write a {@code group} field to the stream.
*
@@ -1059,6 +1064,7 @@ public abstract class CodedOutputStream extends ByteOutput {
value.writeTo(this);
}
+
/**
* Compute the number of bytes that would be needed to encode a
* {@code group} field, including tag.
@@ -1070,6 +1076,7 @@ public abstract class CodedOutputStream extends ByteOutput {
return computeTagSize(fieldNumber) * 2 + computeGroupSizeNoTag(value);
}
+
/**
* Compute the number of bytes that would be needed to encode a
* {@code group} field.
@@ -1079,6 +1086,7 @@ public abstract class CodedOutputStream extends ByteOutput {
return value.getSerializedSize();
}
+
/**
* Encode and write a varint. {@code value} is treated as
* unsigned, so it won't be sign-extended if negative.
@@ -1273,6 +1281,7 @@ public abstract class CodedOutputStream extends ByteOutput {
writeMessageNoTag(value);
}
+
@Override
public final void writeMessageSetExtension(final int fieldNumber, final MessageLite value)
throws IOException {
@@ -1297,6 +1306,7 @@ public abstract class CodedOutputStream extends ByteOutput {
value.writeTo(this);
}
+
@Override
public final void write(byte value) throws IOException {
try {
@@ -1608,6 +1618,7 @@ public abstract class CodedOutputStream extends ByteOutput {
writeMessageNoTag(value);
}
+
@Override
public void writeMessageSetExtension(final int fieldNumber, final MessageLite value)
throws IOException {
@@ -1632,6 +1643,7 @@ public abstract class CodedOutputStream extends ByteOutput {
value.writeTo(this);
}
+
@Override
public void write(byte value) throws IOException {
try {
@@ -1928,6 +1940,7 @@ public abstract class CodedOutputStream extends ByteOutput {
writeMessageNoTag(value);
}
+
@Override
public void writeMessageSetExtension(int fieldNumber, MessageLite value) throws IOException {
writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_START_GROUP);
@@ -1950,6 +1963,7 @@ public abstract class CodedOutputStream extends ByteOutput {
value.writeTo(this);
}
+
@Override
public void write(byte value) throws IOException {
if (position >= limit) {
@@ -2456,6 +2470,7 @@ public abstract class CodedOutputStream extends ByteOutput {
writeMessageNoTag(value);
}
+
@Override
public void writeMessageSetExtension(final int fieldNumber, final MessageLite value)
throws IOException {
@@ -2480,6 +2495,7 @@ public abstract class CodedOutputStream extends ByteOutput {
value.writeTo(this);
}
+
@Override
public void write(byte value) throws IOException {
if (position == limit) {
@@ -2759,6 +2775,7 @@ public abstract class CodedOutputStream extends ByteOutput {
writeMessageNoTag(value);
}
+
@Override
public void writeMessageSetExtension(final int fieldNumber, final MessageLite value)
throws IOException {
@@ -2783,6 +2800,7 @@ public abstract class CodedOutputStream extends ByteOutput {
value.writeTo(this);
}
+
@Override
public void write(byte value) throws IOException {
if (position == limit) {
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 867b85ce..5b28b4a8 100644
--- a/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java
@@ -82,6 +82,18 @@ final class DoubleArrayList extends AbstractProtobufList<Double>
}
@Override
+ protected void removeRange(int fromIndex, int toIndex) {
+ ensureIsMutable();
+ if (toIndex < fromIndex) {
+ throw new IndexOutOfBoundsException("toIndex < fromIndex");
+ }
+
+ System.arraycopy(array, toIndex, array, fromIndex, size - toIndex);
+ size -= (toIndex - fromIndex);
+ modCount++;
+ }
+
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -247,7 +259,9 @@ final class DoubleArrayList extends AbstractProtobufList<Double>
ensureIsMutable();
ensureIndexInRange(index);
double value = array[index];
- System.arraycopy(array, index + 1, array, index, size - index);
+ if (index < size - 1) {
+ System.arraycopy(array, index + 1, array, index, size - index);
+ }
size--;
modCount++;
return value;
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 ba532021..a6a774b7 100644
--- a/java/core/src/main/java/com/google/protobuf/DynamicMessage.java
+++ b/java/core/src/main/java/com/google/protobuf/DynamicMessage.java
@@ -339,6 +339,20 @@ public final class DynamicMessage extends AbstractMessage {
this.fields = FieldSet.newFieldSet();
this.unknownFields = UnknownFieldSet.getDefaultInstance();
this.oneofCases = new FieldDescriptor[type.toProto().getOneofDeclCount()];
+ // A MapEntry has all of its fields present at all times.
+ if (type.getOptions().getMapEntry()) {
+ populateMapEntry();
+ }
+ }
+
+ private void populateMapEntry() {
+ for (FieldDescriptor field : type.getFields()) {
+ if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
+ fields.setField(field, getDefaultInstance(field.getMessageType()));
+ } else {
+ fields.setField(field, field.getDefaultValue());
+ }
+ }
}
// ---------------------------------------------------------------
@@ -351,6 +365,10 @@ public final class DynamicMessage extends AbstractMessage {
} else {
fields.clear();
}
+ // A MapEntry has all of its fields present at all times.
+ if (type.getOptions().getMapEntry()) {
+ populateMapEntry();
+ }
unknownFields = UnknownFieldSet.getDefaultInstance();
return this;
}
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 76645583..7c080af3 100644
--- a/java/core/src/main/java/com/google/protobuf/FloatArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/FloatArrayList.java
@@ -82,6 +82,18 @@ final class FloatArrayList extends AbstractProtobufList<Float>
}
@Override
+ protected void removeRange(int fromIndex, int toIndex) {
+ ensureIsMutable();
+ if (toIndex < fromIndex) {
+ throw new IndexOutOfBoundsException("toIndex < fromIndex");
+ }
+
+ System.arraycopy(array, toIndex, array, fromIndex, size - toIndex);
+ size -= (toIndex - fromIndex);
+ modCount++;
+ }
+
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -246,7 +258,9 @@ final class FloatArrayList extends AbstractProtobufList<Float>
ensureIsMutable();
ensureIndexInRange(index);
float value = array[index];
- System.arraycopy(array, index + 1, array, index, size - index);
+ if (index < size - 1) {
+ System.arraycopy(array, index + 1, array, index, size - index);
+ }
size--;
modCount++;
return value;
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 8b8d9fc6..df01547e 100644
--- a/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java
+++ b/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java
@@ -230,9 +230,13 @@ public abstract class GeneratedMessageLite<
* Called by subclasses to complete parsing. For use by generated code only.
*/
protected void makeImmutable() {
+ // BEGIN REGULAR
dynamicMethod(MethodToInvoke.MAKE_IMMUTABLE);
-
unknownFields.makeImmutable();
+ // END REGULAR
+ // BEGIN EXPERIMENTAL
+ // Protobuf.getInstance().schemaFor(this).makeImmutable(this);
+ // END EXPERIMENTAL
}
protected final <
@@ -269,15 +273,15 @@ public abstract class GeneratedMessageLite<
* For use by generated code only.
*/
public static enum MethodToInvoke {
- IS_INITIALIZED,
// BEGIN REGULAR
+ IS_INITIALIZED,
VISIT,
+ MERGE_FROM_STREAM,
+ MAKE_IMMUTABLE,
// END REGULAR
// Rely on/modify instance state
GET_MEMOIZED_IS_INITIALIZED,
SET_MEMOIZED_IS_INITIALIZED,
- MERGE_FROM_STREAM,
- MAKE_IMMUTABLE,
// Rely on static state
NEW_MUTABLE_INSTANCE,
@@ -339,6 +343,16 @@ public abstract class GeneratedMessageLite<
}
// END REGULAR
+ @Override
+ int getMemoizedSerializedSize() {
+ return memoizedSerializedSize;
+ }
+
+ @Override
+ void setMemoizedSerializedSize(int size) {
+ memoizedSerializedSize = size;
+ }
+
/**
@@ -449,13 +463,41 @@ public abstract class GeneratedMessageLite<
}
@Override
+ public BuilderType mergeFrom(byte[] input, int offset, int length)
+ throws InvalidProtocolBufferException {
+ // BEGIN REGULAR
+ return super.mergeFrom(input, offset, length);
+ // END REGULAR
+ // BEGIN EXPERIMENTAL
+ // copyOnWrite();
+ // try {
+ // Protobuf.getInstance().schemaFor(instance).mergeFrom(
+ // instance, input, offset, offset + length, new ArrayDecoders.Registers());
+ // } catch (InvalidProtocolBufferException e) {
+ // throw e;
+ // } catch (IndexOutOfBoundsException e) {
+ // throw InvalidProtocolBufferException.truncatedMessage();
+ // } catch (IOException e) {
+ // throw new RuntimeException("Reading from byte array should not throw IOException.", e);
+ // }
+ // return (BuilderType) this;
+ // END EXPERIMENTAL
+ }
+
+ @Override
public BuilderType mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws IOException {
copyOnWrite();
try {
+ // BEGIN REGULAR
instance.dynamicMethod(MethodToInvoke.MERGE_FROM_STREAM, input, extensionRegistry);
+ // END REGULAR
+ // BEGIN EXPERIMENTAL
+ // Protobuf.getInstance().schemaFor(instance).mergeFrom(
+ // instance, CodedInputStreamReader.forCodedInput(input), extensionRegistry);
+ // END EXPERIMENTAL
} catch (RuntimeException e) {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
@@ -576,9 +618,7 @@ public abstract class GeneratedMessageLite<
return parseUnknownField(tag, input);
}
- if (extensions.isImmutable()) {
- extensions = extensions.clone();
- }
+ ensureExtensionsAreMutable();
if (packed) {
int length = input.readRawVarint32();
@@ -794,10 +834,18 @@ public abstract class GeneratedMessageLite<
if (subBuilder == null) {
subBuilder = extension.getMessageDefaultInstance().newBuilderForType();
}
- rawBytes.newCodedInput().readMessage(subBuilder, extensionRegistry);
+ subBuilder.mergeFrom(rawBytes, extensionRegistry);
MessageLite value = subBuilder.build();
- extensions.setField(extension.descriptor, extension.singularToFieldSetType(value));
+ ensureExtensionsAreMutable().setField(
+ extension.descriptor, extension.singularToFieldSetType(value));
+ }
+
+ private FieldSet<ExtensionDescriptor> ensureExtensionsAreMutable() {
+ if (extensions.isImmutable()) {
+ extensions = extensions.clone();
+ }
+ return extensions;
}
private void verifyExtensionContainingType(
@@ -869,10 +917,12 @@ public abstract class GeneratedMessageLite<
@Override
protected final void makeImmutable() {
super.makeImmutable();
-
+ // BEGIN REGULAR
extensions.makeImmutable();
+ // END REGULAR
}
+
/**
* Used by subclasses to serialize extensions. Extension ranges may be
* interleaved with field numbers, but we must write them in canonical
@@ -1468,8 +1518,13 @@ public abstract class GeneratedMessageLite<
if (memoizedIsInitialized == 0) {
return false;
}
+ // BEGIN EXPERIMENTAL
+ // boolean isInitialized = Protobuf.getInstance().schemaFor(message).isInitialized(message);
+ // END EXPERIMENTAL
+ // BEGIN REGULAR
boolean isInitialized =
message.dynamicMethod(MethodToInvoke.IS_INITIALIZED, Boolean.FALSE) != null;
+ // END REGULAR
if (shouldMemoize) {
message.dynamicMethod(
MethodToInvoke.SET_MEMOIZED_IS_INITIALIZED, isInitialized ? message : null);
@@ -1477,10 +1532,6 @@ public abstract class GeneratedMessageLite<
return isInitialized;
}
- protected static final <T extends GeneratedMessageLite<T, ?>> void makeImmutable(T message) {
- message.dynamicMethod(MethodToInvoke.MAKE_IMMUTABLE);
- }
-
protected static IntList emptyIntList() {
return IntArrayList.emptyList();
}
@@ -1560,6 +1611,11 @@ public abstract class GeneratedMessageLite<
throws InvalidProtocolBufferException {
return GeneratedMessageLite.parsePartialFrom(defaultInstance, input, extensionRegistry);
}
+
+ @Override
+ public T parsePartialFrom(byte[] input) throws InvalidProtocolBufferException {
+ return GeneratedMessageLite.parsePartialFrom(defaultInstance, input);
+ }
}
/**
@@ -1573,8 +1629,21 @@ public abstract class GeneratedMessageLite<
@SuppressWarnings("unchecked") // Guaranteed by protoc
T result = (T) instance.dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE);
try {
+ // BEGIN REGULAR
result.dynamicMethod(MethodToInvoke.MERGE_FROM_STREAM, input, extensionRegistry);
+ // END REGULAR
+ // BEGIN EXPERIMENTAL
+ // Protobuf.getInstance().schemaFor(result).mergeFrom(
+ // result, CodedInputStreamReader.forCodedInput(input), extensionRegistry);
+ // END EXPERIMENTAL
result.makeImmutable();
+ // BEGIN EXPERIMENTAL
+ // } catch (IOException e) {
+ // if (e.getCause() instanceof InvalidProtocolBufferException) {
+ // throw (InvalidProtocolBufferException) e.getCause();
+ // }
+ // throw new InvalidProtocolBufferException(e.getMessage()).setUnfinishedMessage(result);
+ // END EXPERIMENTAL
} catch (RuntimeException e) {
if (e.getCause() instanceof InvalidProtocolBufferException) {
throw (InvalidProtocolBufferException) e.getCause();
@@ -1584,6 +1653,34 @@ public abstract class GeneratedMessageLite<
return result;
}
+ /** A static helper method for parsing a partial from byte array. */
+ static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom(T instance, byte[] input)
+ throws InvalidProtocolBufferException {
+ // BEGIN REGULAR
+ return parsePartialFrom(instance, input, ExtensionRegistryLite.getEmptyRegistry());
+ // END REGULAR
+ // BEGIN EXPERIMENTAL
+ // @SuppressWarnings("unchecked") // Guaranteed by protoc
+ // T result = (T) instance.dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE);
+ // try {
+ // Protobuf.getInstance().schemaFor(result).mergeFrom(
+ // result, input, 0, input.length, new ArrayDecoders.Registers());
+ // result.makeImmutable();
+ // if (result.memoizedHashCode != 0) {
+ // throw new RuntimeException();
+ // }
+ // } catch (IOException e) {
+ // if (e.getCause() instanceof InvalidProtocolBufferException) {
+ // throw (InvalidProtocolBufferException) e.getCause();
+ // }
+ // throw new InvalidProtocolBufferException(e.getMessage()).setUnfinishedMessage(result);
+ // } catch (IndexOutOfBoundsException e) {
+ // throw InvalidProtocolBufferException.truncatedMessage().setUnfinishedMessage(result);
+ // }
+ // return result;
+ // END EXPERIMENTAL
+ }
+
protected static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom(
T defaultInstance,
CodedInputStream input)
@@ -1680,8 +1777,7 @@ public abstract class GeneratedMessageLite<
protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
T defaultInstance, byte[] data)
throws InvalidProtocolBufferException {
- return checkMessageInitialized(
- parsePartialFrom(defaultInstance, data, ExtensionRegistryLite.getEmptyRegistry()));
+ return checkMessageInitialized(parsePartialFrom(defaultInstance, data));
}
// Validates last 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 aff5c21b..aacd71e1 100644
--- a/java/core/src/main/java/com/google/protobuf/IntArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/IntArrayList.java
@@ -82,6 +82,18 @@ final class IntArrayList extends AbstractProtobufList<Integer>
}
@Override
+ protected void removeRange(int fromIndex, int toIndex) {
+ ensureIsMutable();
+ if (toIndex < fromIndex) {
+ throw new IndexOutOfBoundsException("toIndex < fromIndex");
+ }
+
+ System.arraycopy(array, toIndex, array, fromIndex, size - toIndex);
+ size -= (toIndex - fromIndex);
+ modCount++;
+ }
+
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -246,7 +258,9 @@ final class IntArrayList extends AbstractProtobufList<Integer>
ensureIsMutable();
ensureIndexInRange(index);
int value = array[index];
- System.arraycopy(array, index + 1, array, index, size - index);
+ if (index < size - 1) {
+ System.arraycopy(array, index + 1, array, index, size - index);
+ }
size--;
modCount++;
return value;
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 fc146e23..95945cb7 100644
--- a/java/core/src/main/java/com/google/protobuf/LongArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/LongArrayList.java
@@ -82,6 +82,18 @@ final class LongArrayList extends AbstractProtobufList<Long>
}
@Override
+ protected void removeRange(int fromIndex, int toIndex) {
+ ensureIsMutable();
+ if (toIndex < fromIndex) {
+ throw new IndexOutOfBoundsException("toIndex < fromIndex");
+ }
+
+ System.arraycopy(array, toIndex, array, fromIndex, size - toIndex);
+ size -= (toIndex - fromIndex);
+ modCount++;
+ }
+
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -246,7 +258,9 @@ final class LongArrayList extends AbstractProtobufList<Long>
ensureIsMutable();
ensureIndexInRange(index);
long value = array[index];
- System.arraycopy(array, index + 1, array, index, size - index);
+ if (index < size - 1) {
+ System.arraycopy(array, index + 1, array, index, size - index);
+ }
size--;
modCount++;
return value;
diff --git a/java/core/src/main/java/com/google/protobuf/MessageLiteToString.java b/java/core/src/main/java/com/google/protobuf/MessageLiteToString.java
index 23373ef4..8e265935 100644
--- a/java/core/src/main/java/com/google/protobuf/MessageLiteToString.java
+++ b/java/core/src/main/java/com/google/protobuf/MessageLiteToString.java
@@ -31,6 +31,7 @@
package com.google.protobuf;
import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -38,20 +39,18 @@ import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
-/**
- * Helps generate {@link String} representations of {@link MessageLite} protos.
- */
-// TODO(dweis): Fix map fields.
+/** Helps generate {@link String} representations of {@link MessageLite} protos. */
final class MessageLiteToString {
private static final String LIST_SUFFIX = "List";
private static final String BUILDER_LIST_SUFFIX = "OrBuilderList";
+ private static final String MAP_SUFFIX = "Map";
private static final String BYTES_SUFFIX = "Bytes";
-
+
/**
- * Returns a {@link String} representation of the {@link MessageLite} object. The first line of
+ * Returns a {@link String} representation of the {@link MessageLite} object. The first line of
* the {@code String} representation representation includes a comment string to uniquely identify
- * the objcet instance. This acts as an indicator that this should not be relied on for
+ * the object instance. This acts as an indicator that this should not be relied on for
* comparisons.
*
* <p>For use by generated code only.
@@ -71,8 +70,9 @@ final class MessageLiteToString {
*/
private static void reflectivePrintWithIndent(
MessageLite messageLite, StringBuilder buffer, int indent) {
- // Build a map of method name to method. We're looking for methods like getFoo(), hasFoo(), and
- // getFooList() which might be useful for building an object's string representation.
+ // Build a map of method name to method. We're looking for methods like getFoo(), hasFoo(),
+ // getFooList() and getFooMap() which might be useful for building an object's string
+ // representation.
Map<String, Method> nameToNoArgMethod = new HashMap<String, Method>();
Map<String, Method> nameToMethod = new HashMap<String, Method>();
Set<String> getters = new TreeSet<String>();
@@ -89,12 +89,16 @@ final class MessageLiteToString {
for (String getter : getters) {
String suffix = getter.replaceFirst("get", "");
- if (suffix.endsWith(LIST_SUFFIX) && !suffix.endsWith(BUILDER_LIST_SUFFIX)) {
- String camelCase = suffix.substring(0, 1).toLowerCase()
- + suffix.substring(1, suffix.length() - LIST_SUFFIX.length());
+ if (suffix.endsWith(LIST_SUFFIX)
+ && !suffix.endsWith(BUILDER_LIST_SUFFIX)
+ // Sometimes people have fields named 'list' that aren't repeated.
+ && !suffix.equals(LIST_SUFFIX)) {
+ String camelCase =
+ suffix.substring(0, 1).toLowerCase()
+ + suffix.substring(1, suffix.length() - LIST_SUFFIX.length());
// Try to reflectively get the value and toString() the field as if it were repeated. This
- // only works if the method names have not be proguarded out or renamed.
- Method listMethod = nameToNoArgMethod.get("get" + suffix);
+ // only works if the method names have not been proguarded out or renamed.
+ Method listMethod = nameToNoArgMethod.get(getter);
if (listMethod != null && listMethod.getReturnType().equals(List.class)) {
printField(
buffer,
@@ -104,6 +108,30 @@ final class MessageLiteToString {
continue;
}
}
+ if (suffix.endsWith(MAP_SUFFIX)
+ // Sometimes people have fields named 'map' that aren't maps.
+ && !suffix.equals(MAP_SUFFIX)) {
+ String camelCase =
+ suffix.substring(0, 1).toLowerCase()
+ + suffix.substring(1, suffix.length() - MAP_SUFFIX.length());
+ // Try to reflectively get the value and toString() the field as if it were a map. This only
+ // works if the method names have not been proguarded out or renamed.
+ Method mapMethod = nameToNoArgMethod.get(getter);
+ if (mapMethod != null
+ && mapMethod.getReturnType().equals(Map.class)
+ // Skip the deprecated getter method with no prefix "Map" when the field name ends with
+ // "map".
+ && !mapMethod.isAnnotationPresent(Deprecated.class)
+ // Skip the internal mutable getter method.
+ && Modifier.isPublic(mapMethod.getModifiers())) {
+ printField(
+ buffer,
+ indent,
+ camelCaseToSnakeCase(camelCase),
+ GeneratedMessageLite.invokeOrDie(mapMethod, messageLite));
+ continue;
+ }
+ }
Method setter = nameToMethod.get("set" + suffix);
if (setter == null) {
@@ -119,22 +147,19 @@ final class MessageLiteToString {
String camelCase = suffix.substring(0, 1).toLowerCase() + suffix.substring(1);
// Try to reflectively get the value and toString() the field as if it were optional. This
- // only works if the method names have not be proguarded out or renamed.
+ // only works if the method names have not been proguarded out or renamed.
Method getMethod = nameToNoArgMethod.get("get" + suffix);
Method hasMethod = nameToNoArgMethod.get("has" + suffix);
// TODO(dweis): Fix proto3 semantics.
if (getMethod != null) {
Object value = GeneratedMessageLite.invokeOrDie(getMethod, messageLite);
- final boolean hasValue = hasMethod == null
- ? !isDefaultValue(value)
- : (Boolean) GeneratedMessageLite.invokeOrDie(hasMethod, messageLite);
- // TODO(dweis): This doesn't stop printing oneof case twice: value and enum style.
+ final boolean hasValue =
+ hasMethod == null
+ ? !isDefaultValue(value)
+ : (Boolean) GeneratedMessageLite.invokeOrDie(hasMethod, messageLite);
+ // TODO(dweis): This doesn't stop printing oneof case twice: value and enum style.
if (hasValue) {
- printField(
- buffer,
- indent,
- camelCaseToSnakeCase(camelCase),
- value);
+ printField(buffer, indent, camelCaseToSnakeCase(camelCase), value);
}
continue;
}
@@ -153,7 +178,7 @@ final class MessageLiteToString {
((GeneratedMessageLite<?, ?>) messageLite).unknownFields.printWithIndent(buffer, indent);
}
}
-
+
private static boolean isDefaultValue(Object o) {
if (o instanceof Boolean) {
return !((Boolean) o);
@@ -179,7 +204,7 @@ final class MessageLiteToString {
if (o instanceof java.lang.Enum<?>) { // Catches oneof enums.
return ((java.lang.Enum<?>) o).ordinal() == 0;
}
-
+
return false;
}
@@ -201,6 +226,13 @@ final class MessageLiteToString {
}
return;
}
+ if (object instanceof Map<?, ?>) {
+ Map<?, ?> map = (Map<?, ?>) object;
+ for (Map.Entry<?, ?> entry : map.entrySet()) {
+ printField(buffer, indent, name, entry);
+ }
+ return;
+ }
buffer.append('\n');
for (int i = 0; i < indent; i++) {
@@ -220,11 +252,21 @@ final class MessageLiteToString {
buffer.append(' ');
}
buffer.append("}");
+ } else if (object instanceof Map.Entry<?, ?>) {
+ buffer.append(" {");
+ Map.Entry<?, ?> entry = (Map.Entry<?, ?>) object;
+ printField(buffer, indent + 2, "key", entry.getKey());
+ printField(buffer, indent + 2, "value", entry.getValue());
+ buffer.append("\n");
+ for (int i = 0; i < indent; i++) {
+ buffer.append(' ');
+ }
+ buffer.append("}");
} else {
buffer.append(": ").append(object.toString());
}
}
-
+
private static final String camelCaseToSnakeCase(String camelCase) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < camelCase.length(); i++) {
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 0c8b898c..25c3474f 100644
--- a/java/core/src/main/java/com/google/protobuf/TextFormat.java
+++ b/java/core/src/main/java/com/google/protobuf/TextFormat.java
@@ -987,7 +987,7 @@ public final class TextFormat {
nextToken();
return false;
} else {
- throw parseException("Expected \"true\" or \"false\".");
+ throw parseException("Expected \"true\" or \"false\". Found \"" + currentToken + "\".");
}
}
@@ -1311,13 +1311,17 @@ public final class TextFormat {
}
private final boolean allowUnknownFields;
+ private final boolean allowUnknownEnumValues;
private final SingularOverwritePolicy singularOverwritePolicy;
private TextFormatParseInfoTree.Builder parseInfoTreeBuilder;
private Parser(
- boolean allowUnknownFields, SingularOverwritePolicy singularOverwritePolicy,
+ boolean allowUnknownFields,
+ boolean allowUnknownEnumValues,
+ SingularOverwritePolicy singularOverwritePolicy,
TextFormatParseInfoTree.Builder parseInfoTreeBuilder) {
this.allowUnknownFields = allowUnknownFields;
+ this.allowUnknownEnumValues = allowUnknownEnumValues;
this.singularOverwritePolicy = singularOverwritePolicy;
this.parseInfoTreeBuilder = parseInfoTreeBuilder;
}
@@ -1334,6 +1338,7 @@ public final class TextFormat {
*/
public static class Builder {
private boolean allowUnknownFields = false;
+ private boolean allowUnknownEnumValues = false;
private SingularOverwritePolicy singularOverwritePolicy =
SingularOverwritePolicy.ALLOW_SINGULAR_OVERWRITES;
private TextFormatParseInfoTree.Builder parseInfoTreeBuilder = null;
@@ -1355,7 +1360,10 @@ public final class TextFormat {
public Parser build() {
return new Parser(
- allowUnknownFields, singularOverwritePolicy, parseInfoTreeBuilder);
+ allowUnknownFields,
+ allowUnknownEnumValues,
+ singularOverwritePolicy,
+ parseInfoTreeBuilder);
}
}
@@ -1419,7 +1427,7 @@ public final class TextFormat {
return text;
}
- // Check both unknown fields and unknown extensions and log warming messages
+ // 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 {
@@ -1737,17 +1745,40 @@ public final class TextFormat {
final int number = tokenizer.consumeInt32();
value = enumType.findValueByNumber(number);
if (value == null) {
- throw tokenizer.parseExceptionPreviousToken(
- "Enum type \"" + enumType.getFullName()
- + "\" has no value with number " + number + '.');
+ String unknownValueMsg =
+ "Enum type \""
+ + enumType.getFullName()
+ + "\" has no value with number "
+ + number
+ + '.';
+ if (allowUnknownEnumValues) {
+ logger.warning(unknownValueMsg);
+ return;
+ } else {
+ throw tokenizer.parseExceptionPreviousToken(
+ "Enum type \""
+ + enumType.getFullName()
+ + "\" has no value with number "
+ + number
+ + '.');
+ }
}
} else {
final String id = tokenizer.consumeIdentifier();
value = enumType.findValueByName(id);
if (value == null) {
- throw tokenizer.parseExceptionPreviousToken(
- "Enum type \"" + enumType.getFullName()
- + "\" has no value named \"" + id + "\".");
+ String unknownValueMsg =
+ "Enum type \""
+ + enumType.getFullName()
+ + "\" has no value named \""
+ + id
+ + "\".";
+ if (allowUnknownEnumValues) {
+ logger.warning(unknownValueMsg);
+ return;
+ } else {
+ throw tokenizer.parseExceptionPreviousToken(unknownValueMsg);
+ }
}
}
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 2a614c84..f0b919ad 100644
--- a/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java
+++ b/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java
@@ -295,14 +295,30 @@ public final class UnknownFieldSetLite {
return true;
}
+ private static int hashCode(int[] tags, int count) {
+ int hashCode = 17;
+ for (int i = 0; i < count; ++i) {
+ hashCode = 31 * hashCode + tags[i];
+ }
+ return hashCode;
+ }
+
+ private static int hashCode(Object[] objects, int count) {
+ int hashCode = 17;
+ for (int i = 0; i < count; ++i) {
+ hashCode = 31 * hashCode + objects[i].hashCode();
+ }
+ return hashCode;
+ }
+
@Override
public int hashCode() {
int hashCode = 17;
-
+
hashCode = 31 * hashCode + count;
- hashCode = 31 * hashCode + Arrays.hashCode(tags);
- hashCode = 31 * hashCode + Arrays.deepHashCode(objects);
-
+ hashCode = 31 * hashCode + hashCode(tags, count);
+ hashCode = 31 * hashCode + hashCode(objects, count);
+
return hashCode;
}
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 b09ff673..d84ef3c5 100644
--- a/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
+++ b/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
@@ -71,8 +71,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() {
@@ -83,6 +81,7 @@ final class UnsafeUtil {
return HAS_UNSAFE_BYTEBUFFER_OPERATIONS;
}
+
static long objectFieldOffset(Field field) {
return MEMORY_ACCESSOR.objectFieldOffset(field);
}
@@ -147,10 +146,6 @@ final class UnsafeUtil {
return MEMORY_ACCESSOR.getObject(target, offset);
}
- static void putObject(Object target, long offset, Object value) {
- MEMORY_ACCESSOR.putObject(target, offset, value);
- }
-
static byte getByte(byte[] target, long index) {
return MEMORY_ACCESSOR.getByte(target, BYTE_ARRAY_BASE_OFFSET + index);
}
@@ -260,26 +255,6 @@ final class UnsafeUtil {
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);
}
@@ -287,7 +262,7 @@ final class UnsafeUtil {
/**
* Gets the {@code sun.misc.Unsafe} instance, or {@code null} if not available on this platform.
*/
- private static sun.misc.Unsafe getUnsafe() {
+ static sun.misc.Unsafe getUnsafe() {
sun.misc.Unsafe unsafe = null;
try {
unsafe =
@@ -367,6 +342,10 @@ final class UnsafeUtil {
clazz.getMethod("objectFieldOffset", Field.class);
clazz.getMethod("getLong", Object.class, long.class);
+ if (bufferAddressField() == null) {
+ return false;
+ }
+
clazz.getMethod("getByte", long.class);
clazz.getMethod("putByte", long.class, byte.class);
clazz.getMethod("getInt", long.class);
@@ -387,12 +366,14 @@ final class UnsafeUtil {
/** Finds the address field within a direct {@link Buffer}. */
private static Field bufferAddressField() {
- return field(Buffer.class, "address", long.class);
+ Field field = field(Buffer.class, "address");
+ return field != null && field.getType() == long.class ? field : null;
}
/** Finds the value field within a {@link String}. */
private static Field stringValueField() {
- return field(String.class, "value", char[].class);
+ Field field = field(String.class, "value");
+ return field != null && field.getType() == char[].class ? field : null;
}
/**
@@ -407,14 +388,11 @@ final class UnsafeUtil {
* Gets the field with the given name within the class, or {@code null} if not found. If found,
* the field is made accessible.
*/
- private static Field field(Class<?> clazz, String fieldName, Class<?> expectedType) {
+ private static Field field(Class<?> clazz, String fieldName) {
Field field;
try {
field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
- if (!field.getType().equals(expectedType)) {
- return null;
- }
} catch (Throwable t) {
// Failed to access the fields.
field = null;
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..de75fe6b 100644
--- a/java/core/src/main/java/com/google/protobuf/Utf8.java
+++ b/java/core/src/main/java/com/google/protobuf/Utf8.java
@@ -1474,10 +1474,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 +1550,7 @@ final class Utf8 {
}
}
- if (resultPos < resultArr.length) {
- resultArr = Arrays.copyOf(resultArr, resultPos);
- }
- return UnsafeUtil.moveToString(resultArr);
+ return new String(resultArr, 0, resultPos);
}
@Override
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 18132e9e..4906763c 100644
--- a/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java
@@ -32,6 +32,7 @@ package com.google.protobuf;
import static java.util.Arrays.asList;
+import com.google.protobuf.Internal.BooleanList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
@@ -297,6 +298,20 @@ public class BooleanArrayListTest extends TestCase {
}
}
+ public void testRemoveEndOfCapacity() {
+ BooleanList toRemove = BooleanArrayList.emptyList().mutableCopyWithCapacity(1);
+ toRemove.addBoolean(true);
+ toRemove.remove(0);
+ assertEquals(0, toRemove.size());
+ }
+
+ public void testSublistRemoveEndOfCapacity() {
+ BooleanList toRemove = BooleanArrayList.emptyList().mutableCopyWithCapacity(1);
+ toRemove.addBoolean(true);
+ toRemove.subList(0, 1).clear();
+ assertEquals(0, toRemove.size());
+ }
+
private void assertImmutable(BooleanArrayList list) {
try {
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 cc65d19a..50b87ae3 100644
--- a/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java
+++ b/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java
@@ -34,7 +34,7 @@ import proto2_test_check_utf8.TestCheckUtf8.BytesWrapper;
import proto2_test_check_utf8.TestCheckUtf8.StringWrapper;
import proto2_test_check_utf8_size.TestCheckUtf8Size.BytesWrapperSize;
import proto2_test_check_utf8_size.TestCheckUtf8Size.StringWrapperSize;
-
+import java.io.ByteArrayInputStream;
import junit.framework.TestCase;
/**
@@ -90,14 +90,9 @@ public class CheckUtf8Test extends TestCase {
}
public void testParseRequiredStringWithBadUtf8() throws Exception {
- ByteString serialized =
- BytesWrapper.newBuilder().setReq(NON_UTF8_BYTE_STRING).build().toByteString();
- try {
- StringWrapper.parser().parseFrom(serialized);
- fail("Expected InvalidProtocolBufferException for non UTF-8 byte string.");
- } catch (InvalidProtocolBufferException exception) {
- assertEquals("Protocol message had invalid UTF-8.", exception.getMessage());
- }
+ byte[] serialized =
+ BytesWrapper.newBuilder().setReq(NON_UTF8_BYTE_STRING).build().toByteArray();
+ assertParseBadUtf8(StringWrapper.getDefaultInstance(), serialized);
}
public void testBuildRequiredStringWithBadUtf8Size() throws Exception {
@@ -128,14 +123,36 @@ public class CheckUtf8Test extends TestCase {
}
public void testParseRequiredStringWithBadUtf8Size() throws Exception {
- ByteString serialized =
- BytesWrapperSize.newBuilder().setReq(NON_UTF8_BYTE_STRING).build().toByteString();
+ byte[] serialized =
+ BytesWrapperSize.newBuilder().setReq(NON_UTF8_BYTE_STRING).build().toByteArray();
+ assertParseBadUtf8(StringWrapperSize.getDefaultInstance(), serialized);
+ }
+
+ private void assertParseBadUtf8(MessageLite defaultInstance, byte[] data) throws Exception {
+ // Check combinations of (parser vs. builder) x (byte[] vs. InputStream)
+ try {
+ defaultInstance.getParserForType().parseFrom(data);
+ fail("Expected InvalidProtocolBufferException for non UTF-8 byte string.");
+ } catch (InvalidProtocolBufferException exception) {
+ assertEquals("Protocol message had invalid UTF-8.", exception.getMessage());
+ }
+ try {
+ defaultInstance.newBuilderForType().mergeFrom(data);
+ fail("Expected InvalidProtocolBufferException for non UTF-8 byte string.");
+ } catch (InvalidProtocolBufferException exception) {
+ assertEquals("Protocol message had invalid UTF-8.", exception.getMessage());
+ }
try {
- StringWrapperSize.parser().parseFrom(serialized);
+ defaultInstance.getParserForType().parseFrom(new ByteArrayInputStream(data));
+ fail("Expected InvalidProtocolBufferException for non UTF-8 byte string.");
+ } catch (InvalidProtocolBufferException exception) {
+ assertEquals("Protocol message had invalid UTF-8.", exception.getMessage());
+ }
+ try {
+ defaultInstance.newBuilderForType().mergeFrom(new ByteArrayInputStream(data));
fail("Expected InvalidProtocolBufferException for non UTF-8 byte string.");
} catch (InvalidProtocolBufferException exception) {
assertEquals("Protocol message had invalid UTF-8.", exception.getMessage());
}
}
-
}
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 d8942792..923d7f43 100644
--- a/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java
@@ -32,6 +32,7 @@ package com.google.protobuf;
import static java.util.Arrays.asList;
+import com.google.protobuf.Internal.DoubleList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
@@ -297,6 +298,20 @@ public class DoubleArrayListTest extends TestCase {
}
}
+ public void testRemoveEndOfCapacity() {
+ DoubleList toRemove = DoubleArrayList.emptyList().mutableCopyWithCapacity(1);
+ toRemove.addDouble(3);
+ toRemove.remove(0);
+ assertEquals(0, toRemove.size());
+ }
+
+ public void testSublistRemoveEndOfCapacity() {
+ DoubleList toRemove = DoubleArrayList.emptyList().mutableCopyWithCapacity(1);
+ toRemove.addDouble(3);
+ toRemove.subList(0, 1).clear();
+ assertEquals(0, toRemove.size());
+ }
+
private void assertImmutable(DoubleArrayList 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/FloatArrayListTest.java b/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java
index aa36be49..903a79db 100644
--- a/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java
@@ -32,6 +32,7 @@ package com.google.protobuf;
import static java.util.Arrays.asList;
+import com.google.protobuf.Internal.FloatList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
@@ -297,6 +298,20 @@ public class FloatArrayListTest extends TestCase {
}
}
+ public void testRemoveEndOfCapacity() {
+ FloatList toRemove = FloatArrayList.emptyList().mutableCopyWithCapacity(1);
+ toRemove.addFloat(3);
+ toRemove.remove(0);
+ assertEquals(0, toRemove.size());
+ }
+
+ public void testSublistRemoveEndOfCapacity() {
+ FloatList toRemove = FloatArrayList.emptyList().mutableCopyWithCapacity(1);
+ toRemove.addFloat(3);
+ toRemove.subList(0, 1).clear();
+ assertEquals(0, toRemove.size());
+ }
+
private void assertImmutable(FloatArrayList 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/IntArrayListTest.java b/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java
index 60c85450..d8e97d4f 100644
--- a/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java
@@ -32,6 +32,7 @@ package com.google.protobuf;
import static java.util.Arrays.asList;
+import com.google.protobuf.Internal.IntList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
@@ -297,6 +298,20 @@ public class IntArrayListTest extends TestCase {
}
}
+ public void testRemoveEndOfCapacity() {
+ IntList toRemove = IntArrayList.emptyList().mutableCopyWithCapacity(1);
+ toRemove.addInt(3);
+ toRemove.remove(0);
+ assertEquals(0, toRemove.size());
+ }
+
+ public void testSublistRemoveEndOfCapacity() {
+ IntList toRemove = IntArrayList.emptyList().mutableCopyWithCapacity(1);
+ toRemove.addInt(3);
+ toRemove.subList(0, 1).clear();
+ assertEquals(0, toRemove.size());
+ }
+
private void assertImmutable(IntArrayList 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/LiteTest.java b/java/core/src/test/java/com/google/protobuf/LiteTest.java
index 40b44538..5ab80ca2 100644
--- a/java/core/src/test/java/com/google/protobuf/LiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LiteTest.java
@@ -48,11 +48,15 @@ import com.google.protobuf.UnittestLite.TestAllTypesLite.RepeatedGroup;
import com.google.protobuf.UnittestLite.TestAllTypesLiteOrBuilder;
import com.google.protobuf.UnittestLite.TestHugeFieldNumbersLite;
import com.google.protobuf.UnittestLite.TestNestedExtensionLite;
+import map_lite_test.MapTestProto.TestMap;
+import map_lite_test.MapTestProto.TestMap.MessageValue;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.Bar;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.BarPrime;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.Foo;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.TestOneofEquals;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.TestRecursiveOneof;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.util.ArrayList;
@@ -88,12 +92,11 @@ public class LiteTest extends TestCase {
// stuff to make sure the lite message is actually here and usable.
TestAllTypesLite message =
- TestAllTypesLite.newBuilder()
- .setOptionalInt32(123)
- .addRepeatedString("hello")
- .setOptionalNestedMessage(
- TestAllTypesLite.NestedMessage.newBuilder().setBb(7))
- .build();
+ TestAllTypesLite.newBuilder()
+ .setOptionalInt32(123)
+ .addRepeatedString("hello")
+ .setOptionalNestedMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(7))
+ .build();
ByteString data = message.toByteString();
@@ -105,57 +108,66 @@ public class LiteTest extends TestCase {
assertEquals(7, message2.getOptionalNestedMessage().getBb());
}
+ public void testLite_unknownEnumAtListBoundary() throws Exception {
+ ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
+ CodedOutputStream output = CodedOutputStream.newInstance(byteStream);
+ for (int i = 0; i < AbstractProtobufList.DEFAULT_CAPACITY; i++) {
+ output.writeInt32(TestAllTypesLite.REPEATED_NESTED_ENUM_FIELD_NUMBER, 1);
+ }
+ // 0 is not a valid enum value for NestedEnum
+ output.writeInt32(TestAllTypesLite.REPEATED_NESTED_ENUM_FIELD_NUMBER, 0);
+ output.flush();
+ // This tests a bug we had once with removal right at the boundary of the array. It would throw
+ // at runtime so no need to assert.
+ TestAllTypesLite.parseFrom(new ByteArrayInputStream(byteStream.toByteArray()));
+ }
+
public void testLiteExtensions() throws Exception {
// TODO(kenton): Unlike other features of the lite library, extensions are
// implemented completely differently from the regular library. We
// should probably test them more thoroughly.
TestAllExtensionsLite message =
- TestAllExtensionsLite.newBuilder()
- .setExtension(UnittestLite.optionalInt32ExtensionLite, 123)
- .addExtension(UnittestLite.repeatedStringExtensionLite, "hello")
- .setExtension(UnittestLite.optionalNestedEnumExtensionLite,
- TestAllTypesLite.NestedEnum.BAZ)
- .setExtension(UnittestLite.optionalNestedMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(7).build())
- .build();
+ TestAllExtensionsLite.newBuilder()
+ .setExtension(UnittestLite.optionalInt32ExtensionLite, 123)
+ .addExtension(UnittestLite.repeatedStringExtensionLite, "hello")
+ .setExtension(
+ UnittestLite.optionalNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ)
+ .setExtension(
+ UnittestLite.optionalNestedMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(7).build())
+ .build();
// Test copying a message, since coping extensions actually does use a
// different code path between lite and regular libraries, and as of this
// writing, parsing hasn't been implemented yet.
TestAllExtensionsLite message2 = message.toBuilder().build();
- assertEquals(123, (int) message2.getExtension(
- UnittestLite.optionalInt32ExtensionLite));
- assertEquals(1, message2.getExtensionCount(
- UnittestLite.repeatedStringExtensionLite));
- assertEquals(1, message2.getExtension(
- UnittestLite.repeatedStringExtensionLite).size());
- assertEquals("hello", message2.getExtension(
- UnittestLite.repeatedStringExtensionLite, 0));
- assertEquals(TestAllTypesLite.NestedEnum.BAZ, message2.getExtension(
- UnittestLite.optionalNestedEnumExtensionLite));
- assertEquals(7, message2.getExtension(
- UnittestLite.optionalNestedMessageExtensionLite).getBb());
+ assertEquals(123, (int) message2.getExtension(UnittestLite.optionalInt32ExtensionLite));
+ assertEquals(1, message2.getExtensionCount(UnittestLite.repeatedStringExtensionLite));
+ assertEquals(1, message2.getExtension(UnittestLite.repeatedStringExtensionLite).size());
+ assertEquals("hello", message2.getExtension(UnittestLite.repeatedStringExtensionLite, 0));
+ assertEquals(
+ TestAllTypesLite.NestedEnum.BAZ,
+ message2.getExtension(UnittestLite.optionalNestedEnumExtensionLite));
+ assertEquals(7, message2.getExtension(UnittestLite.optionalNestedMessageExtensionLite).getBb());
}
-
+
public void testClone() {
- TestAllTypesLite.Builder expected = TestAllTypesLite.newBuilder()
- .setOptionalInt32(123);
- assertEquals(
- expected.getOptionalInt32(), expected.clone().getOptionalInt32());
-
- TestAllExtensionsLite.Builder expected2 = TestAllExtensionsLite.newBuilder()
- .setExtension(UnittestLite.optionalInt32ExtensionLite, 123);
+ TestAllTypesLite.Builder expected = TestAllTypesLite.newBuilder().setOptionalInt32(123);
+ assertEquals(expected.getOptionalInt32(), expected.clone().getOptionalInt32());
+
+ TestAllExtensionsLite.Builder expected2 =
+ TestAllExtensionsLite.newBuilder()
+ .setExtension(UnittestLite.optionalInt32ExtensionLite, 123);
assertEquals(
expected2.getExtension(UnittestLite.optionalInt32ExtensionLite),
expected2.clone().getExtension(UnittestLite.optionalInt32ExtensionLite));
}
-
+
public void testAddAll() {
try {
- TestAllTypesLite.newBuilder()
- .addAllRepeatedBytes(null);
+ TestAllTypesLite.newBuilder().addAllRepeatedBytes(null);
fail();
} catch (NullPointerException e) {
// expected.
@@ -186,7 +198,7 @@ public class LiteTest extends TestCase {
// We have to cast to Byte first. Casting to byte causes a type error
assertEquals(1, ((Byte) memo.get(message)).intValue());
}
-
+
public void testSanityCopyOnWrite() throws InvalidProtocolBufferException {
// Since builders are implemented as a thin wrapper around a message
// instance, we attempt to verify that we can't cause the builder to modify
@@ -210,13 +222,11 @@ public class LiteTest extends TestCase {
assertEquals(ByteString.EMPTY, message.getOptionalBytes());
assertEquals(ByteString.copyFromUtf8("hi"), builder.getOptionalBytes());
messageAfterBuild = builder.build();
- assertEquals(
- ByteString.copyFromUtf8("hi"), messageAfterBuild.getOptionalBytes());
+ assertEquals(ByteString.copyFromUtf8("hi"), messageAfterBuild.getOptionalBytes());
assertEquals(ByteString.EMPTY, message.getOptionalBytes());
builder.clearOptionalBytes();
assertEquals(ByteString.EMPTY, builder.getOptionalBytes());
- assertEquals(
- ByteString.copyFromUtf8("hi"), messageAfterBuild.getOptionalBytes());
+ assertEquals(ByteString.copyFromUtf8("hi"), messageAfterBuild.getOptionalBytes());
message = builder.build();
builder.setOptionalCord("hi");
@@ -234,27 +244,23 @@ public class LiteTest extends TestCase {
assertEquals(ByteString.EMPTY, message.getOptionalCordBytes());
assertEquals(ByteString.copyFromUtf8("no"), builder.getOptionalCordBytes());
messageAfterBuild = builder.build();
- assertEquals(
- ByteString.copyFromUtf8("no"),
- messageAfterBuild.getOptionalCordBytes());
+ assertEquals(ByteString.copyFromUtf8("no"), messageAfterBuild.getOptionalCordBytes());
assertEquals(ByteString.EMPTY, message.getOptionalCordBytes());
builder.clearOptionalCord();
assertEquals(ByteString.EMPTY, builder.getOptionalCordBytes());
- assertEquals(
- ByteString.copyFromUtf8("no"),
- messageAfterBuild.getOptionalCordBytes());
-
+ assertEquals(ByteString.copyFromUtf8("no"), messageAfterBuild.getOptionalCordBytes());
+
message = builder.build();
builder.setOptionalDouble(1);
- assertEquals(0D, message.getOptionalDouble());
- assertEquals(1D, builder.getOptionalDouble());
+ assertEquals(0D, message.getOptionalDouble(), 0.0);
+ assertEquals(1D, builder.getOptionalDouble(), 0.0);
messageAfterBuild = builder.build();
- assertEquals(1D, messageAfterBuild.getOptionalDouble());
- assertEquals(0D, message.getOptionalDouble());
+ assertEquals(1D, messageAfterBuild.getOptionalDouble(), 0.0);
+ assertEquals(0D, message.getOptionalDouble(), 0.0);
builder.clearOptionalDouble();
- assertEquals(0D, builder.getOptionalDouble());
- assertEquals(1D, messageAfterBuild.getOptionalDouble());
-
+ assertEquals(0D, builder.getOptionalDouble(), 0.0);
+ assertEquals(1D, messageAfterBuild.getOptionalDouble(), 0.0);
+
message = builder.build();
builder.setOptionalFixed32(1);
assertEquals(0, message.getOptionalFixed32());
@@ -265,7 +271,7 @@ public class LiteTest extends TestCase {
builder.clearOptionalFixed32();
assertEquals(0, builder.getOptionalFixed32());
assertEquals(1, messageAfterBuild.getOptionalFixed32());
-
+
message = builder.build();
builder.setOptionalFixed64(1);
assertEquals(0L, message.getOptionalFixed64());
@@ -279,105 +285,72 @@ public class LiteTest extends TestCase {
message = builder.build();
builder.setOptionalFloat(1);
- assertEquals(0F, message.getOptionalFloat());
- assertEquals(1F, builder.getOptionalFloat());
+ assertEquals(0F, message.getOptionalFloat(), 0.0f);
+ assertEquals(1F, builder.getOptionalFloat(), 0.0f);
messageAfterBuild = builder.build();
- assertEquals(1F, messageAfterBuild.getOptionalFloat());
- assertEquals(0F, message.getOptionalFloat());
+ assertEquals(1F, messageAfterBuild.getOptionalFloat(), 0.0f);
+ assertEquals(0F, message.getOptionalFloat(), 0.0f);
builder.clearOptionalFloat();
- assertEquals(0F, builder.getOptionalFloat());
- assertEquals(1F, messageAfterBuild.getOptionalFloat());
+ assertEquals(0F, builder.getOptionalFloat(), 0.0f);
+ assertEquals(1F, messageAfterBuild.getOptionalFloat(), 0.0f);
message = builder.build();
builder.setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR);
- assertEquals(
- ForeignEnumLite.FOREIGN_LITE_FOO, message.getOptionalForeignEnum());
- assertEquals(
- ForeignEnumLite.FOREIGN_LITE_BAR, builder.getOptionalForeignEnum());
+ assertEquals(ForeignEnumLite.FOREIGN_LITE_FOO, message.getOptionalForeignEnum());
+ assertEquals(ForeignEnumLite.FOREIGN_LITE_BAR, builder.getOptionalForeignEnum());
messageAfterBuild = builder.build();
- assertEquals(
- ForeignEnumLite.FOREIGN_LITE_BAR,
- messageAfterBuild.getOptionalForeignEnum());
- assertEquals(
- ForeignEnumLite.FOREIGN_LITE_FOO, message.getOptionalForeignEnum());
+ assertEquals(ForeignEnumLite.FOREIGN_LITE_BAR, messageAfterBuild.getOptionalForeignEnum());
+ assertEquals(ForeignEnumLite.FOREIGN_LITE_FOO, message.getOptionalForeignEnum());
builder.clearOptionalForeignEnum();
- assertEquals(
- ForeignEnumLite.FOREIGN_LITE_FOO, builder.getOptionalForeignEnum());
- assertEquals(
- ForeignEnumLite.FOREIGN_LITE_BAR,
- messageAfterBuild.getOptionalForeignEnum());
+ assertEquals(ForeignEnumLite.FOREIGN_LITE_FOO, builder.getOptionalForeignEnum());
+ assertEquals(ForeignEnumLite.FOREIGN_LITE_BAR, messageAfterBuild.getOptionalForeignEnum());
message = builder.build();
- ForeignMessageLite foreignMessage = ForeignMessageLite.newBuilder()
- .setC(1)
- .build();
+ ForeignMessageLite foreignMessage = ForeignMessageLite.newBuilder().setC(1).build();
builder.setOptionalForeignMessage(foreignMessage);
- assertEquals(
- ForeignMessageLite.getDefaultInstance(),
- message.getOptionalForeignMessage());
+ assertEquals(ForeignMessageLite.getDefaultInstance(), message.getOptionalForeignMessage());
assertEquals(foreignMessage, builder.getOptionalForeignMessage());
messageAfterBuild = builder.build();
assertEquals(foreignMessage, messageAfterBuild.getOptionalForeignMessage());
- assertEquals(
- ForeignMessageLite.getDefaultInstance(),
- message.getOptionalForeignMessage());
+ assertEquals(ForeignMessageLite.getDefaultInstance(), message.getOptionalForeignMessage());
builder.clearOptionalForeignMessage();
- assertEquals(
- ForeignMessageLite.getDefaultInstance(),
- builder.getOptionalForeignMessage());
+ assertEquals(ForeignMessageLite.getDefaultInstance(), builder.getOptionalForeignMessage());
assertEquals(foreignMessage, messageAfterBuild.getOptionalForeignMessage());
message = builder.build();
- ForeignMessageLite.Builder foreignMessageBuilder =
- ForeignMessageLite.newBuilder()
- .setC(3);
+ ForeignMessageLite.Builder foreignMessageBuilder = ForeignMessageLite.newBuilder().setC(3);
builder.setOptionalForeignMessage(foreignMessageBuilder);
- assertEquals(
- ForeignMessageLite.getDefaultInstance(),
- message.getOptionalForeignMessage());
+ assertEquals(ForeignMessageLite.getDefaultInstance(), message.getOptionalForeignMessage());
assertEquals(foreignMessageBuilder.build(), builder.getOptionalForeignMessage());
messageAfterBuild = builder.build();
assertEquals(foreignMessageBuilder.build(), messageAfterBuild.getOptionalForeignMessage());
- assertEquals(
- ForeignMessageLite.getDefaultInstance(),
- message.getOptionalForeignMessage());
+ assertEquals(ForeignMessageLite.getDefaultInstance(), message.getOptionalForeignMessage());
builder.clearOptionalForeignMessage();
- assertEquals(
- ForeignMessageLite.getDefaultInstance(),
- builder.getOptionalForeignMessage());
+ assertEquals(ForeignMessageLite.getDefaultInstance(), builder.getOptionalForeignMessage());
assertEquals(foreignMessageBuilder.build(), messageAfterBuild.getOptionalForeignMessage());
message = builder.build();
- OptionalGroup optionalGroup = OptionalGroup.newBuilder()
- .setA(1)
- .build();
+ OptionalGroup optionalGroup = OptionalGroup.newBuilder().setA(1).build();
builder.setOptionalGroup(optionalGroup);
- assertEquals(
- OptionalGroup.getDefaultInstance(), message.getOptionalGroup());
+ assertEquals(OptionalGroup.getDefaultInstance(), message.getOptionalGroup());
assertEquals(optionalGroup, builder.getOptionalGroup());
messageAfterBuild = builder.build();
assertEquals(optionalGroup, messageAfterBuild.getOptionalGroup());
- assertEquals(
- OptionalGroup.getDefaultInstance(), message.getOptionalGroup());
+ assertEquals(OptionalGroup.getDefaultInstance(), message.getOptionalGroup());
builder.clearOptionalGroup();
- assertEquals(
- OptionalGroup.getDefaultInstance(), builder.getOptionalGroup());
+ assertEquals(OptionalGroup.getDefaultInstance(), builder.getOptionalGroup());
assertEquals(optionalGroup, messageAfterBuild.getOptionalGroup());
message = builder.build();
- OptionalGroup.Builder optionalGroupBuilder = OptionalGroup.newBuilder()
- .setA(3);
+ OptionalGroup.Builder optionalGroupBuilder = OptionalGroup.newBuilder().setA(3);
builder.setOptionalGroup(optionalGroupBuilder);
- assertEquals(
- OptionalGroup.getDefaultInstance(), message.getOptionalGroup());
+ assertEquals(OptionalGroup.getDefaultInstance(), message.getOptionalGroup());
assertEquals(optionalGroupBuilder.build(), builder.getOptionalGroup());
messageAfterBuild = builder.build();
assertEquals(optionalGroupBuilder.build(), messageAfterBuild.getOptionalGroup());
- assertEquals(
- OptionalGroup.getDefaultInstance(), message.getOptionalGroup());
+ assertEquals(OptionalGroup.getDefaultInstance(), message.getOptionalGroup());
builder.clearOptionalGroup();
- assertEquals(
- OptionalGroup.getDefaultInstance(), builder.getOptionalGroup());
+ assertEquals(OptionalGroup.getDefaultInstance(), builder.getOptionalGroup());
assertEquals(optionalGroupBuilder.build(), messageAfterBuild.getOptionalGroup());
message = builder.build();
@@ -401,43 +374,29 @@ public class LiteTest extends TestCase {
builder.clearOptionalInt64();
assertEquals(0L, builder.getOptionalInt64());
assertEquals(1L, messageAfterBuild.getOptionalInt64());
-
+
message = builder.build();
- NestedMessage nestedMessage = NestedMessage.newBuilder()
- .setBb(1)
- .build();
+ NestedMessage nestedMessage = NestedMessage.newBuilder().setBb(1).build();
builder.setOptionalLazyMessage(nestedMessage);
- assertEquals(
- NestedMessage.getDefaultInstance(),
- message.getOptionalLazyMessage());
+ assertEquals(NestedMessage.getDefaultInstance(), message.getOptionalLazyMessage());
assertEquals(nestedMessage, builder.getOptionalLazyMessage());
messageAfterBuild = builder.build();
assertEquals(nestedMessage, messageAfterBuild.getOptionalLazyMessage());
- assertEquals(
- NestedMessage.getDefaultInstance(),
- message.getOptionalLazyMessage());
+ assertEquals(NestedMessage.getDefaultInstance(), message.getOptionalLazyMessage());
builder.clearOptionalLazyMessage();
- assertEquals(
- NestedMessage.getDefaultInstance(), builder.getOptionalLazyMessage());
+ assertEquals(NestedMessage.getDefaultInstance(), builder.getOptionalLazyMessage());
assertEquals(nestedMessage, messageAfterBuild.getOptionalLazyMessage());
message = builder.build();
- NestedMessage.Builder nestedMessageBuilder =
- NestedMessage.newBuilder()
- .setBb(3);
+ NestedMessage.Builder nestedMessageBuilder = NestedMessage.newBuilder().setBb(3);
builder.setOptionalLazyMessage(nestedMessageBuilder);
- assertEquals(
- NestedMessage.getDefaultInstance(),
- message.getOptionalLazyMessage());
+ assertEquals(NestedMessage.getDefaultInstance(), message.getOptionalLazyMessage());
assertEquals(nestedMessageBuilder.build(), builder.getOptionalLazyMessage());
messageAfterBuild = builder.build();
assertEquals(nestedMessageBuilder.build(), messageAfterBuild.getOptionalLazyMessage());
- assertEquals(
- NestedMessage.getDefaultInstance(),
- message.getOptionalLazyMessage());
+ assertEquals(NestedMessage.getDefaultInstance(), message.getOptionalLazyMessage());
builder.clearOptionalLazyMessage();
- assertEquals(
- NestedMessage.getDefaultInstance(), builder.getOptionalLazyMessage());
+ assertEquals(NestedMessage.getDefaultInstance(), builder.getOptionalLazyMessage());
assertEquals(nestedMessageBuilder.build(), messageAfterBuild.getOptionalLazyMessage());
message = builder.build();
@@ -497,19 +456,14 @@ public class LiteTest extends TestCase {
message = builder.build();
builder.setOptionalStringBytes(ByteString.copyFromUtf8("no"));
assertEquals(ByteString.EMPTY, message.getOptionalStringBytes());
- assertEquals(
- ByteString.copyFromUtf8("no"), builder.getOptionalStringBytes());
+ assertEquals(ByteString.copyFromUtf8("no"), builder.getOptionalStringBytes());
messageAfterBuild = builder.build();
- assertEquals(
- ByteString.copyFromUtf8("no"),
- messageAfterBuild.getOptionalStringBytes());
+ assertEquals(ByteString.copyFromUtf8("no"), messageAfterBuild.getOptionalStringBytes());
assertEquals(ByteString.EMPTY, message.getOptionalStringBytes());
builder.clearOptionalString();
assertEquals(ByteString.EMPTY, builder.getOptionalStringBytes());
- assertEquals(
- ByteString.copyFromUtf8("no"),
- messageAfterBuild.getOptionalStringBytes());
-
+ assertEquals(ByteString.copyFromUtf8("no"), messageAfterBuild.getOptionalStringBytes());
+
message = builder.build();
builder.setOptionalStringPiece("hi");
assertEquals("", message.getOptionalStringPiece());
@@ -524,18 +478,13 @@ public class LiteTest extends TestCase {
message = builder.build();
builder.setOptionalStringPieceBytes(ByteString.copyFromUtf8("no"));
assertEquals(ByteString.EMPTY, message.getOptionalStringPieceBytes());
- assertEquals(
- ByteString.copyFromUtf8("no"), builder.getOptionalStringPieceBytes());
+ assertEquals(ByteString.copyFromUtf8("no"), builder.getOptionalStringPieceBytes());
messageAfterBuild = builder.build();
- assertEquals(
- ByteString.copyFromUtf8("no"),
- messageAfterBuild.getOptionalStringPieceBytes());
+ assertEquals(ByteString.copyFromUtf8("no"), messageAfterBuild.getOptionalStringPieceBytes());
assertEquals(ByteString.EMPTY, message.getOptionalStringPieceBytes());
builder.clearOptionalStringPiece();
assertEquals(ByteString.EMPTY, builder.getOptionalStringPieceBytes());
- assertEquals(
- ByteString.copyFromUtf8("no"),
- messageAfterBuild.getOptionalStringPieceBytes());
+ assertEquals(ByteString.copyFromUtf8("no"), messageAfterBuild.getOptionalStringPieceBytes());
message = builder.build();
builder.setOptionalUint32(1);
@@ -572,16 +521,13 @@ public class LiteTest extends TestCase {
message = builder.build();
builder.addAllRepeatedBytes(singletonList(ByteString.copyFromUtf8("hi")));
assertEquals(emptyList(), message.getRepeatedBytesList());
- assertEquals(
- singletonList(ByteString.copyFromUtf8("hi")),
- builder.getRepeatedBytesList());
+ assertEquals(singletonList(ByteString.copyFromUtf8("hi")), builder.getRepeatedBytesList());
assertEquals(emptyList(), message.getRepeatedBytesList());
messageAfterBuild = builder.build();
builder.clearRepeatedBytes();
assertEquals(emptyList(), builder.getRepeatedBytesList());
assertEquals(
- singletonList(ByteString.copyFromUtf8("hi")),
- messageAfterBuild.getRepeatedBytesList());
+ singletonList(ByteString.copyFromUtf8("hi")), messageAfterBuild.getRepeatedBytesList());
message = builder.build();
builder.addAllRepeatedCord(singletonList("hi"));
@@ -634,12 +580,10 @@ public class LiteTest extends TestCase {
assertEquals(singletonList(1F), messageAfterBuild.getRepeatedFloatList());
message = builder.build();
- builder.addAllRepeatedForeignEnum(
- singletonList(ForeignEnumLite.FOREIGN_LITE_BAR));
+ builder.addAllRepeatedForeignEnum(singletonList(ForeignEnumLite.FOREIGN_LITE_BAR));
assertEquals(emptyList(), message.getRepeatedForeignEnumList());
assertEquals(
- singletonList(ForeignEnumLite.FOREIGN_LITE_BAR),
- builder.getRepeatedForeignEnumList());
+ singletonList(ForeignEnumLite.FOREIGN_LITE_BAR), builder.getRepeatedForeignEnumList());
assertEquals(emptyList(), message.getRepeatedForeignEnumList());
messageAfterBuild = builder.build();
builder.clearRepeatedForeignEnum();
@@ -651,23 +595,17 @@ public class LiteTest extends TestCase {
message = builder.build();
builder.addAllRepeatedForeignMessage(singletonList(foreignMessage));
assertEquals(emptyList(), message.getRepeatedForeignMessageList());
- assertEquals(
- singletonList(foreignMessage), builder.getRepeatedForeignMessageList());
+ assertEquals(singletonList(foreignMessage), builder.getRepeatedForeignMessageList());
assertEquals(emptyList(), message.getRepeatedForeignMessageList());
messageAfterBuild = builder.build();
builder.clearRepeatedForeignMessage();
assertEquals(emptyList(), builder.getRepeatedForeignMessageList());
- assertEquals(
- singletonList(foreignMessage),
- messageAfterBuild.getRepeatedForeignMessageList());
+ assertEquals(singletonList(foreignMessage), messageAfterBuild.getRepeatedForeignMessageList());
message = builder.build();
- builder.addAllRepeatedGroup(
- singletonList(RepeatedGroup.getDefaultInstance()));
+ builder.addAllRepeatedGroup(singletonList(RepeatedGroup.getDefaultInstance()));
assertEquals(emptyList(), message.getRepeatedGroupList());
- assertEquals(
- singletonList(RepeatedGroup.getDefaultInstance()),
- builder.getRepeatedGroupList());
+ assertEquals(singletonList(RepeatedGroup.getDefaultInstance()), builder.getRepeatedGroupList());
assertEquals(emptyList(), message.getRepeatedGroupList());
messageAfterBuild = builder.build();
builder.clearRepeatedGroup();
@@ -699,15 +637,12 @@ public class LiteTest extends TestCase {
message = builder.build();
builder.addAllRepeatedLazyMessage(singletonList(nestedMessage));
assertEquals(emptyList(), message.getRepeatedLazyMessageList());
- assertEquals(
- singletonList(nestedMessage), builder.getRepeatedLazyMessageList());
+ assertEquals(singletonList(nestedMessage), builder.getRepeatedLazyMessageList());
assertEquals(emptyList(), message.getRepeatedLazyMessageList());
messageAfterBuild = builder.build();
builder.clearRepeatedLazyMessage();
assertEquals(emptyList(), builder.getRepeatedLazyMessageList());
- assertEquals(
- singletonList(nestedMessage),
- messageAfterBuild.getRepeatedLazyMessageList());
+ assertEquals(singletonList(nestedMessage), messageAfterBuild.getRepeatedLazyMessageList());
message = builder.build();
builder.addAllRepeatedSfixed32(singletonList(1));
@@ -727,8 +662,7 @@ public class LiteTest extends TestCase {
messageAfterBuild = builder.build();
builder.clearRepeatedSfixed64();
assertEquals(emptyList(), builder.getRepeatedSfixed64List());
- assertEquals(
- singletonList(1L), messageAfterBuild.getRepeatedSfixed64List());
+ assertEquals(singletonList(1L), messageAfterBuild.getRepeatedSfixed64List());
message = builder.build();
builder.addAllRepeatedSint32(singletonList(1));
@@ -758,8 +692,7 @@ public class LiteTest extends TestCase {
messageAfterBuild = builder.build();
builder.clearRepeatedString();
assertEquals(emptyList(), builder.getRepeatedStringList());
- assertEquals(
- singletonList("hi"), messageAfterBuild.getRepeatedStringList());
+ assertEquals(singletonList("hi"), messageAfterBuild.getRepeatedStringList());
message = builder.build();
builder.addAllRepeatedStringPiece(singletonList("hi"));
@@ -769,8 +702,7 @@ public class LiteTest extends TestCase {
messageAfterBuild = builder.build();
builder.clearRepeatedStringPiece();
assertEquals(emptyList(), builder.getRepeatedStringPieceList());
- assertEquals(
- singletonList("hi"), messageAfterBuild.getRepeatedStringPieceList());
+ assertEquals(singletonList("hi"), messageAfterBuild.getRepeatedStringPieceList());
message = builder.build();
builder.addAllRepeatedUint32(singletonList(1));
@@ -805,16 +737,13 @@ public class LiteTest extends TestCase {
message = builder.build();
builder.addRepeatedBytes(ByteString.copyFromUtf8("hi"));
assertEquals(emptyList(), message.getRepeatedBytesList());
- assertEquals(
- singletonList(ByteString.copyFromUtf8("hi")),
- builder.getRepeatedBytesList());
+ assertEquals(singletonList(ByteString.copyFromUtf8("hi")), builder.getRepeatedBytesList());
assertEquals(emptyList(), message.getRepeatedBytesList());
messageAfterBuild = builder.build();
builder.clearRepeatedBytes();
assertEquals(emptyList(), builder.getRepeatedBytesList());
assertEquals(
- singletonList(ByteString.copyFromUtf8("hi")),
- messageAfterBuild.getRepeatedBytesList());
+ singletonList(ByteString.copyFromUtf8("hi")), messageAfterBuild.getRepeatedBytesList());
message = builder.build();
builder.addRepeatedCord("hi");
@@ -870,8 +799,7 @@ public class LiteTest extends TestCase {
builder.addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR);
assertEquals(emptyList(), message.getRepeatedForeignEnumList());
assertEquals(
- singletonList(ForeignEnumLite.FOREIGN_LITE_BAR),
- builder.getRepeatedForeignEnumList());
+ singletonList(ForeignEnumLite.FOREIGN_LITE_BAR), builder.getRepeatedForeignEnumList());
assertEquals(emptyList(), message.getRepeatedForeignEnumList());
messageAfterBuild = builder.build();
builder.clearRepeatedForeignEnum();
@@ -883,22 +811,17 @@ public class LiteTest extends TestCase {
message = builder.build();
builder.addRepeatedForeignMessage(foreignMessage);
assertEquals(emptyList(), message.getRepeatedForeignMessageList());
- assertEquals(
- singletonList(foreignMessage), builder.getRepeatedForeignMessageList());
+ assertEquals(singletonList(foreignMessage), builder.getRepeatedForeignMessageList());
assertEquals(emptyList(), message.getRepeatedForeignMessageList());
messageAfterBuild = builder.build();
builder.removeRepeatedForeignMessage(0);
assertEquals(emptyList(), builder.getRepeatedForeignMessageList());
- assertEquals(
- singletonList(foreignMessage),
- messageAfterBuild.getRepeatedForeignMessageList());
+ assertEquals(singletonList(foreignMessage), messageAfterBuild.getRepeatedForeignMessageList());
message = builder.build();
builder.addRepeatedGroup(RepeatedGroup.getDefaultInstance());
assertEquals(emptyList(), message.getRepeatedGroupList());
- assertEquals(
- singletonList(RepeatedGroup.getDefaultInstance()),
- builder.getRepeatedGroupList());
+ assertEquals(singletonList(RepeatedGroup.getDefaultInstance()), builder.getRepeatedGroupList());
assertEquals(emptyList(), message.getRepeatedGroupList());
messageAfterBuild = builder.build();
builder.removeRepeatedGroup(0);
@@ -930,15 +853,12 @@ public class LiteTest extends TestCase {
message = builder.build();
builder.addRepeatedLazyMessage(nestedMessage);
assertEquals(emptyList(), message.getRepeatedLazyMessageList());
- assertEquals(
- singletonList(nestedMessage), builder.getRepeatedLazyMessageList());
+ assertEquals(singletonList(nestedMessage), builder.getRepeatedLazyMessageList());
assertEquals(emptyList(), message.getRepeatedLazyMessageList());
messageAfterBuild = builder.build();
builder.removeRepeatedLazyMessage(0);
assertEquals(emptyList(), builder.getRepeatedLazyMessageList());
- assertEquals(
- singletonList(nestedMessage),
- messageAfterBuild.getRepeatedLazyMessageList());
+ assertEquals(singletonList(nestedMessage), messageAfterBuild.getRepeatedLazyMessageList());
message = builder.build();
builder.addRepeatedSfixed32(1);
@@ -958,8 +878,7 @@ public class LiteTest extends TestCase {
messageAfterBuild = builder.build();
builder.clearRepeatedSfixed64();
assertEquals(emptyList(), builder.getRepeatedSfixed64List());
- assertEquals(
- singletonList(1L), messageAfterBuild.getRepeatedSfixed64List());
+ assertEquals(singletonList(1L), messageAfterBuild.getRepeatedSfixed64List());
message = builder.build();
builder.addRepeatedSint32(1);
@@ -989,8 +908,7 @@ public class LiteTest extends TestCase {
messageAfterBuild = builder.build();
builder.clearRepeatedString();
assertEquals(emptyList(), builder.getRepeatedStringList());
- assertEquals(
- singletonList("hi"), messageAfterBuild.getRepeatedStringList());
+ assertEquals(singletonList("hi"), messageAfterBuild.getRepeatedStringList());
message = builder.build();
builder.addRepeatedStringPiece("hi");
@@ -1000,8 +918,7 @@ public class LiteTest extends TestCase {
messageAfterBuild = builder.build();
builder.clearRepeatedStringPiece();
assertEquals(emptyList(), builder.getRepeatedStringPieceList());
- assertEquals(
- singletonList("hi"), messageAfterBuild.getRepeatedStringPieceList());
+ assertEquals(singletonList("hi"), messageAfterBuild.getRepeatedStringPieceList());
message = builder.build();
builder.addRepeatedUint32(1);
@@ -1022,7 +939,7 @@ public class LiteTest extends TestCase {
builder.clearRepeatedUint64();
assertEquals(emptyList(), builder.getRepeatedUint64List());
assertEquals(singletonList(1L), messageAfterBuild.getRepeatedUint64List());
-
+
message = builder.build();
builder.addRepeatedBool(true);
messageAfterBuild = builder.build();
@@ -1031,14 +948,13 @@ public class LiteTest extends TestCase {
assertEquals(true, messageAfterBuild.getRepeatedBool(0));
assertEquals(false, builder.getRepeatedBool(0));
builder.clearRepeatedBool();
-
+
message = builder.build();
builder.addRepeatedBytes(ByteString.copyFromUtf8("hi"));
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedBytesCount());
builder.setRepeatedBytes(0, ByteString.EMPTY);
- assertEquals(
- ByteString.copyFromUtf8("hi"), messageAfterBuild.getRepeatedBytes(0));
+ assertEquals(ByteString.copyFromUtf8("hi"), messageAfterBuild.getRepeatedBytes(0));
assertEquals(ByteString.EMPTY, builder.getRepeatedBytes(0));
builder.clearRepeatedBytes();
@@ -1056,8 +972,7 @@ public class LiteTest extends TestCase {
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedCordCount());
builder.setRepeatedCord(0, "");
- assertEquals(
- ByteString.copyFromUtf8("hi"), messageAfterBuild.getRepeatedCordBytes(0));
+ assertEquals(ByteString.copyFromUtf8("hi"), messageAfterBuild.getRepeatedCordBytes(0));
assertEquals(ByteString.EMPTY, builder.getRepeatedCordBytes(0));
builder.clearRepeatedCord();
@@ -1066,8 +981,8 @@ public class LiteTest extends TestCase {
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedDoubleCount());
builder.setRepeatedDouble(0, 0D);
- assertEquals(1D, messageAfterBuild.getRepeatedDouble(0));
- assertEquals(0D, builder.getRepeatedDouble(0));
+ assertEquals(1D, messageAfterBuild.getRepeatedDouble(0), 0.0);
+ assertEquals(0D, builder.getRepeatedDouble(0), 0.0);
builder.clearRepeatedDouble();
message = builder.build();
@@ -1093,8 +1008,8 @@ public class LiteTest extends TestCase {
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedFloatCount());
builder.setRepeatedFloat(0, 0F);
- assertEquals(1F, messageAfterBuild.getRepeatedFloat(0));
- assertEquals(0F, builder.getRepeatedFloat(0));
+ assertEquals(1F, messageAfterBuild.getRepeatedFloat(0), 0.0f);
+ assertEquals(0F, builder.getRepeatedFloat(0), 0.0f);
builder.clearRepeatedFloat();
message = builder.build();
@@ -1102,36 +1017,26 @@ public class LiteTest extends TestCase {
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedForeignEnumCount());
builder.setRepeatedForeignEnum(0, ForeignEnumLite.FOREIGN_LITE_FOO);
- assertEquals(
- ForeignEnumLite.FOREIGN_LITE_BAR,
- messageAfterBuild.getRepeatedForeignEnum(0));
- assertEquals(
- ForeignEnumLite.FOREIGN_LITE_FOO, builder.getRepeatedForeignEnum(0));
+ assertEquals(ForeignEnumLite.FOREIGN_LITE_BAR, messageAfterBuild.getRepeatedForeignEnum(0));
+ assertEquals(ForeignEnumLite.FOREIGN_LITE_FOO, builder.getRepeatedForeignEnum(0));
builder.clearRepeatedForeignEnum();
message = builder.build();
builder.addRepeatedForeignMessage(foreignMessage);
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedForeignMessageCount());
- builder.setRepeatedForeignMessage(
- 0, ForeignMessageLite.getDefaultInstance());
- assertEquals(
- foreignMessage, messageAfterBuild.getRepeatedForeignMessage(0));
- assertEquals(
- ForeignMessageLite.getDefaultInstance(),
- builder.getRepeatedForeignMessage(0));
+ builder.setRepeatedForeignMessage(0, ForeignMessageLite.getDefaultInstance());
+ assertEquals(foreignMessage, messageAfterBuild.getRepeatedForeignMessage(0));
+ assertEquals(ForeignMessageLite.getDefaultInstance(), builder.getRepeatedForeignMessage(0));
builder.clearRepeatedForeignMessage();
-
+
message = builder.build();
builder.addRepeatedForeignMessage(foreignMessageBuilder);
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedForeignMessageCount());
- builder.setRepeatedForeignMessage(
- 0, ForeignMessageLite.getDefaultInstance());
+ builder.setRepeatedForeignMessage(0, ForeignMessageLite.getDefaultInstance());
assertEquals(foreignMessageBuilder.build(), messageAfterBuild.getRepeatedForeignMessage(0));
- assertEquals(
- ForeignMessageLite.getDefaultInstance(),
- builder.getRepeatedForeignMessage(0));
+ assertEquals(ForeignMessageLite.getDefaultInstance(), builder.getRepeatedForeignMessage(0));
builder.clearRepeatedForeignMessage();
message = builder.build();
@@ -1139,54 +1044,46 @@ public class LiteTest extends TestCase {
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedForeignMessageCount());
builder.setRepeatedForeignMessage(0, foreignMessageBuilder);
- assertEquals(
- foreignMessage, messageAfterBuild.getRepeatedForeignMessage(0));
+ assertEquals(foreignMessage, messageAfterBuild.getRepeatedForeignMessage(0));
assertEquals(foreignMessageBuilder.build(), builder.getRepeatedForeignMessage(0));
builder.clearRepeatedForeignMessage();
message = builder.build();
- RepeatedGroup repeatedGroup = RepeatedGroup.newBuilder()
- .setA(1)
- .build();
+ RepeatedGroup repeatedGroup = RepeatedGroup.newBuilder().setA(1).build();
builder.addRepeatedGroup(repeatedGroup);
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedGroupCount());
builder.setRepeatedGroup(0, RepeatedGroup.getDefaultInstance());
assertEquals(repeatedGroup, messageAfterBuild.getRepeatedGroup(0));
- assertEquals(
- RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0));
+ assertEquals(RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0));
builder.clearRepeatedGroup();
-
+
message = builder.build();
builder.addRepeatedGroup(0, repeatedGroup);
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedGroupCount());
builder.setRepeatedGroup(0, RepeatedGroup.getDefaultInstance());
assertEquals(repeatedGroup, messageAfterBuild.getRepeatedGroup(0));
- assertEquals(
- RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0));
+ assertEquals(RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0));
builder.clearRepeatedGroup();
-
+
message = builder.build();
- RepeatedGroup.Builder repeatedGroupBuilder = RepeatedGroup.newBuilder()
- .setA(3);
+ RepeatedGroup.Builder repeatedGroupBuilder = RepeatedGroup.newBuilder().setA(3);
builder.addRepeatedGroup(repeatedGroupBuilder);
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedGroupCount());
builder.setRepeatedGroup(0, RepeatedGroup.getDefaultInstance());
assertEquals(repeatedGroupBuilder.build(), messageAfterBuild.getRepeatedGroup(0));
- assertEquals(
- RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0));
+ assertEquals(RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0));
builder.clearRepeatedGroup();
-
+
message = builder.build();
builder.addRepeatedGroup(0, repeatedGroupBuilder);
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedGroupCount());
builder.setRepeatedGroup(0, RepeatedGroup.getDefaultInstance());
assertEquals(repeatedGroupBuilder.build(), messageAfterBuild.getRepeatedGroup(0));
- assertEquals(
- RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0));
+ assertEquals(RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0));
builder.clearRepeatedGroup();
message = builder.build();
@@ -1206,45 +1103,41 @@ public class LiteTest extends TestCase {
assertEquals(1L, messageAfterBuild.getRepeatedInt64(0));
assertEquals(0L, builder.getRepeatedInt64(0));
builder.clearRepeatedInt64();
-
+
message = builder.build();
builder.addRepeatedLazyMessage(nestedMessage);
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedLazyMessageCount());
builder.setRepeatedLazyMessage(0, NestedMessage.getDefaultInstance());
assertEquals(nestedMessage, messageAfterBuild.getRepeatedLazyMessage(0));
- assertEquals(
- NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0));
+ assertEquals(NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0));
builder.clearRepeatedLazyMessage();
-
+
message = builder.build();
builder.addRepeatedLazyMessage(0, nestedMessage);
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedLazyMessageCount());
builder.setRepeatedLazyMessage(0, NestedMessage.getDefaultInstance());
assertEquals(nestedMessage, messageAfterBuild.getRepeatedLazyMessage(0));
- assertEquals(
- NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0));
+ assertEquals(NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0));
builder.clearRepeatedLazyMessage();
-
+
message = builder.build();
builder.addRepeatedLazyMessage(nestedMessageBuilder);
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedLazyMessageCount());
builder.setRepeatedLazyMessage(0, NestedMessage.getDefaultInstance());
assertEquals(nestedMessageBuilder.build(), messageAfterBuild.getRepeatedLazyMessage(0));
- assertEquals(
- NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0));
+ assertEquals(NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0));
builder.clearRepeatedLazyMessage();
-
+
message = builder.build();
builder.addRepeatedLazyMessage(0, nestedMessageBuilder);
messageAfterBuild = builder.build();
assertEquals(0, message.getRepeatedLazyMessageCount());
builder.setRepeatedLazyMessage(0, NestedMessage.getDefaultInstance());
assertEquals(nestedMessageBuilder.build(), messageAfterBuild.getRepeatedLazyMessage(0));
- assertEquals(
- NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0));
+ assertEquals(NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0));
builder.clearRepeatedLazyMessage();
message = builder.build();
@@ -1297,9 +1190,7 @@ public class LiteTest extends TestCase {
messageAfterBuild = builder.build();
assertEquals(0L, message.getRepeatedStringCount());
builder.setRepeatedString(0, "");
- assertEquals(
- ByteString.copyFromUtf8("hi"),
- messageAfterBuild.getRepeatedStringBytes(0));
+ assertEquals(ByteString.copyFromUtf8("hi"), messageAfterBuild.getRepeatedStringBytes(0));
assertEquals(ByteString.EMPTY, builder.getRepeatedStringBytes(0));
builder.clearRepeatedString();
@@ -1317,9 +1208,7 @@ public class LiteTest extends TestCase {
messageAfterBuild = builder.build();
assertEquals(0L, message.getRepeatedStringPieceCount());
builder.setRepeatedStringPiece(0, "");
- assertEquals(
- ByteString.copyFromUtf8("hi"),
- messageAfterBuild.getRepeatedStringPieceBytes(0));
+ assertEquals(ByteString.copyFromUtf8("hi"), messageAfterBuild.getRepeatedStringPieceBytes(0));
assertEquals(ByteString.EMPTY, builder.getRepeatedStringPieceBytes(0));
builder.clearRepeatedStringPiece();
@@ -1343,18 +1232,14 @@ public class LiteTest extends TestCase {
message = builder.build();
assertEquals(0, message.getSerializedSize());
- builder.mergeFrom(TestAllTypesLite.newBuilder()
- .setOptionalBool(true)
- .build());
+ builder.mergeFrom(TestAllTypesLite.newBuilder().setOptionalBool(true).build());
assertEquals(0, message.getSerializedSize());
assertEquals(true, builder.build().getOptionalBool());
builder.clearOptionalBool();
message = builder.build();
assertEquals(0, message.getSerializedSize());
- builder.mergeFrom(TestAllTypesLite.newBuilder()
- .setOptionalBool(true)
- .build());
+ builder.mergeFrom(TestAllTypesLite.newBuilder().setOptionalBool(true).build());
assertEquals(0, message.getSerializedSize());
assertEquals(true, builder.build().getOptionalBool());
builder.clear();
@@ -1364,93 +1249,68 @@ public class LiteTest extends TestCase {
assertEquals(0, message.getSerializedSize());
builder.mergeOptionalForeignMessage(foreignMessage);
assertEquals(0, message.getSerializedSize());
- assertEquals(
- foreignMessage.getC(),
- builder.build().getOptionalForeignMessage().getC());
+ assertEquals(foreignMessage.getC(), builder.build().getOptionalForeignMessage().getC());
builder.clearOptionalForeignMessage();
message = builder.build();
assertEquals(0, message.getSerializedSize());
builder.mergeOptionalLazyMessage(nestedMessage);
assertEquals(0, message.getSerializedSize());
- assertEquals(
- nestedMessage.getBb(),
- builder.build().getOptionalLazyMessage().getBb());
+ assertEquals(nestedMessage.getBb(), builder.build().getOptionalLazyMessage().getBb());
builder.clearOptionalLazyMessage();
-
+
message = builder.build();
builder.setOneofString("hi");
- assertEquals(
- OneofFieldCase.ONEOFFIELD_NOT_SET, message.getOneofFieldCase());
+ assertEquals(OneofFieldCase.ONEOFFIELD_NOT_SET, message.getOneofFieldCase());
assertEquals(OneofFieldCase.ONEOF_STRING, builder.getOneofFieldCase());
assertEquals("hi", builder.getOneofString());
messageAfterBuild = builder.build();
- assertEquals(
- OneofFieldCase.ONEOF_STRING, messageAfterBuild.getOneofFieldCase());
+ assertEquals(OneofFieldCase.ONEOF_STRING, messageAfterBuild.getOneofFieldCase());
assertEquals("hi", messageAfterBuild.getOneofString());
builder.setOneofUint32(1);
- assertEquals(
- OneofFieldCase.ONEOF_STRING, messageAfterBuild.getOneofFieldCase());
+ assertEquals(OneofFieldCase.ONEOF_STRING, messageAfterBuild.getOneofFieldCase());
assertEquals("hi", messageAfterBuild.getOneofString());
assertEquals(OneofFieldCase.ONEOF_UINT32, builder.getOneofFieldCase());
assertEquals(1, builder.getOneofUint32());
TestAllTypesLiteOrBuilder messageOrBuilder = builder;
assertEquals(OneofFieldCase.ONEOF_UINT32, messageOrBuilder.getOneofFieldCase());
-
- TestAllExtensionsLite.Builder extendableMessageBuilder =
- TestAllExtensionsLite.newBuilder();
+
+ TestAllExtensionsLite.Builder extendableMessageBuilder = TestAllExtensionsLite.newBuilder();
TestAllExtensionsLite extendableMessage = extendableMessageBuilder.build();
- extendableMessageBuilder.setExtension(
- UnittestLite.optionalInt32ExtensionLite, 1);
- assertFalse(extendableMessage.hasExtension(
- UnittestLite.optionalInt32ExtensionLite));
+ extendableMessageBuilder.setExtension(UnittestLite.optionalInt32ExtensionLite, 1);
+ assertFalse(extendableMessage.hasExtension(UnittestLite.optionalInt32ExtensionLite));
extendableMessage = extendableMessageBuilder.build();
assertEquals(
- 1, (int) extendableMessageBuilder.getExtension(
- UnittestLite.optionalInt32ExtensionLite));
+ 1, (int) extendableMessageBuilder.getExtension(UnittestLite.optionalInt32ExtensionLite));
+ assertEquals(1, (int) extendableMessage.getExtension(UnittestLite.optionalInt32ExtensionLite));
+ extendableMessageBuilder.setExtension(UnittestLite.optionalInt32ExtensionLite, 3);
assertEquals(
- 1, (int) extendableMessage.getExtension(
- UnittestLite.optionalInt32ExtensionLite));
- extendableMessageBuilder.setExtension(
- UnittestLite.optionalInt32ExtensionLite, 3);
- assertEquals(
- 3, (int) extendableMessageBuilder.getExtension(
- UnittestLite.optionalInt32ExtensionLite));
- assertEquals(
- 1, (int) extendableMessage.getExtension(
- UnittestLite.optionalInt32ExtensionLite));
+ 3, (int) extendableMessageBuilder.getExtension(UnittestLite.optionalInt32ExtensionLite));
+ assertEquals(1, (int) extendableMessage.getExtension(UnittestLite.optionalInt32ExtensionLite));
extendableMessage = extendableMessageBuilder.build();
assertEquals(
- 3, (int) extendableMessageBuilder.getExtension(
- UnittestLite.optionalInt32ExtensionLite));
- assertEquals(
- 3, (int) extendableMessage.getExtension(
- UnittestLite.optionalInt32ExtensionLite));
-
+ 3, (int) extendableMessageBuilder.getExtension(UnittestLite.optionalInt32ExtensionLite));
+ assertEquals(3, (int) extendableMessage.getExtension(UnittestLite.optionalInt32ExtensionLite));
+
// No extension registry, so it should be in unknown fields.
- extendableMessage =
- TestAllExtensionsLite.parseFrom(extendableMessage.toByteArray());
- assertFalse(extendableMessage.hasExtension(
- UnittestLite.optionalInt32ExtensionLite));
-
+ extendableMessage = TestAllExtensionsLite.parseFrom(extendableMessage.toByteArray());
+ assertFalse(extendableMessage.hasExtension(UnittestLite.optionalInt32ExtensionLite));
+
extendableMessageBuilder = extendableMessage.toBuilder();
- extendableMessageBuilder.mergeFrom(TestAllExtensionsLite.newBuilder()
- .setExtension(UnittestLite.optionalFixed32ExtensionLite, 11)
- .build());
-
+ extendableMessageBuilder.mergeFrom(
+ TestAllExtensionsLite.newBuilder()
+ .setExtension(UnittestLite.optionalFixed32ExtensionLite, 11)
+ .build());
+
extendableMessage = extendableMessageBuilder.build();
ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance();
UnittestLite.registerAllExtensions(registry);
- extendableMessage = TestAllExtensionsLite.parseFrom(
- extendableMessage.toByteArray(), registry);
-
+ extendableMessage = TestAllExtensionsLite.parseFrom(extendableMessage.toByteArray(), registry);
+
// The unknown field was preserved.
+ assertEquals(3, (int) extendableMessage.getExtension(UnittestLite.optionalInt32ExtensionLite));
assertEquals(
- 3, (int) extendableMessage.getExtension(
- UnittestLite.optionalInt32ExtensionLite));
- assertEquals(
- 11, (int) extendableMessage.getExtension(
- UnittestLite.optionalFixed32ExtensionLite));
+ 11, (int) extendableMessage.getExtension(UnittestLite.optionalFixed32ExtensionLite));
}
public void testBuilderMergeFromNull() throws Exception {
@@ -1497,140 +1357,174 @@ public class LiteTest extends TestCase {
}
public void testToStringScalarFieldsSuffixedWithList() throws Exception {
- assertToStringEquals("deceptively_named_list: 7", TestAllTypesLite.newBuilder()
- .setDeceptivelyNamedList(7)
- .build());
+ assertToStringEquals(
+ "deceptively_named_list: 7",
+ TestAllTypesLite.newBuilder().setDeceptivelyNamedList(7).build());
}
public void testToStringPrimitives() throws Exception {
- TestAllTypesLite proto = TestAllTypesLite.newBuilder()
- .setOptionalInt32(1)
- .setOptionalInt64(9223372036854775807L)
- .build();
+ TestAllTypesLite proto =
+ TestAllTypesLite.newBuilder()
+ .setOptionalInt32(1)
+ .setOptionalInt64(9223372036854775807L)
+ .build();
assertToStringEquals("optional_int32: 1\noptional_int64: 9223372036854775807", proto);
- proto = TestAllTypesLite.newBuilder()
- .setOptionalBool(true)
- .setOptionalNestedEnum(TestAllTypesLite.NestedEnum.BAZ)
- .build();
+ proto =
+ TestAllTypesLite.newBuilder()
+ .setOptionalBool(true)
+ .setOptionalNestedEnum(TestAllTypesLite.NestedEnum.BAZ)
+ .build();
assertToStringEquals("optional_bool: true\noptional_nested_enum: BAZ", proto);
- proto = TestAllTypesLite.newBuilder()
- .setOptionalFloat(2.72f)
- .setOptionalDouble(3.14)
- .build();
+ proto = TestAllTypesLite.newBuilder().setOptionalFloat(2.72f).setOptionalDouble(3.14).build();
assertToStringEquals("optional_double: 3.14\noptional_float: 2.72", proto);
}
public void testToStringStringFields() throws Exception {
- TestAllTypesLite proto = TestAllTypesLite.newBuilder()
- .setOptionalString("foo\"bar\nbaz\\")
- .build();
+ TestAllTypesLite proto =
+ TestAllTypesLite.newBuilder().setOptionalString("foo\"bar\nbaz\\").build();
assertToStringEquals("optional_string: \"foo\\\"bar\\nbaz\\\\\"", proto);
- proto = TestAllTypesLite.newBuilder()
- .setOptionalString("\u6587")
- .build();
+ proto = TestAllTypesLite.newBuilder().setOptionalString("\u6587").build();
assertToStringEquals("optional_string: \"\\346\\226\\207\"", proto);
}
public void testToStringNestedMessage() throws Exception {
- TestAllTypesLite proto = TestAllTypesLite.newBuilder()
- .setOptionalNestedMessage(TestAllTypesLite.NestedMessage.getDefaultInstance())
- .build();
+ TestAllTypesLite proto =
+ TestAllTypesLite.newBuilder()
+ .setOptionalNestedMessage(TestAllTypesLite.NestedMessage.getDefaultInstance())
+ .build();
assertToStringEquals("optional_nested_message {\n}", proto);
- proto = TestAllTypesLite.newBuilder()
- .setOptionalNestedMessage(
- TestAllTypesLite.NestedMessage.newBuilder().setBb(7))
- .build();
+ proto =
+ TestAllTypesLite.newBuilder()
+ .setOptionalNestedMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(7))
+ .build();
assertToStringEquals("optional_nested_message {\n bb: 7\n}", proto);
}
public void testToStringRepeatedFields() throws Exception {
- TestAllTypesLite proto = TestAllTypesLite.newBuilder()
- .addRepeatedInt32(32)
- .addRepeatedInt32(32)
- .addRepeatedInt64(64)
- .build();
+ TestAllTypesLite proto =
+ TestAllTypesLite.newBuilder()
+ .addRepeatedInt32(32)
+ .addRepeatedInt32(32)
+ .addRepeatedInt64(64)
+ .build();
assertToStringEquals("repeated_int32: 32\nrepeated_int32: 32\nrepeated_int64: 64", proto);
- proto = TestAllTypesLite.newBuilder()
- .addRepeatedLazyMessage(
- TestAllTypesLite.NestedMessage.newBuilder().setBb(7))
- .addRepeatedLazyMessage(
- TestAllTypesLite.NestedMessage.newBuilder().setBb(8))
- .build();
+ proto =
+ TestAllTypesLite.newBuilder()
+ .addRepeatedLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(7))
+ .addRepeatedLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(8))
+ .build();
assertToStringEquals(
- "repeated_lazy_message {\n bb: 7\n}\nrepeated_lazy_message {\n bb: 8\n}",
- proto);
+ "repeated_lazy_message {\n bb: 7\n}\nrepeated_lazy_message {\n bb: 8\n}", proto);
}
public void testToStringForeignFields() throws Exception {
- TestAllTypesLite proto = TestAllTypesLite.newBuilder()
- .setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR)
- .setOptionalForeignMessage(
- ForeignMessageLite.newBuilder()
- .setC(3))
- .build();
+ TestAllTypesLite proto =
+ TestAllTypesLite.newBuilder()
+ .setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR)
+ .setOptionalForeignMessage(ForeignMessageLite.newBuilder().setC(3))
+ .build();
assertToStringEquals(
- "optional_foreign_enum: FOREIGN_LITE_BAR\noptional_foreign_message {\n c: 3\n}",
- proto);
+ "optional_foreign_enum: FOREIGN_LITE_BAR\noptional_foreign_message {\n c: 3\n}", proto);
}
public void testToStringExtensions() throws Exception {
- TestAllExtensionsLite message = TestAllExtensionsLite.newBuilder()
- .setExtension(UnittestLite.optionalInt32ExtensionLite, 123)
- .addExtension(UnittestLite.repeatedStringExtensionLite, "spam")
- .addExtension(UnittestLite.repeatedStringExtensionLite, "eggs")
- .setExtension(UnittestLite.optionalNestedEnumExtensionLite,
- TestAllTypesLite.NestedEnum.BAZ)
- .setExtension(UnittestLite.optionalNestedMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(7).build())
- .build();
+ TestAllExtensionsLite message =
+ TestAllExtensionsLite.newBuilder()
+ .setExtension(UnittestLite.optionalInt32ExtensionLite, 123)
+ .addExtension(UnittestLite.repeatedStringExtensionLite, "spam")
+ .addExtension(UnittestLite.repeatedStringExtensionLite, "eggs")
+ .setExtension(
+ UnittestLite.optionalNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ)
+ .setExtension(
+ UnittestLite.optionalNestedMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(7).build())
+ .build();
assertToStringEquals(
- "[1]: 123\n[18] {\n bb: 7\n}\n[21]: 3\n[44]: \"spam\"\n[44]: \"eggs\"",
- message);
+ "[1]: 123\n[18] {\n bb: 7\n}\n[21]: 3\n[44]: \"spam\"\n[44]: \"eggs\"", message);
}
public void testToStringUnknownFields() throws Exception {
- TestAllExtensionsLite messageWithExtensions = TestAllExtensionsLite.newBuilder()
- .setExtension(UnittestLite.optionalInt32ExtensionLite, 123)
- .addExtension(UnittestLite.repeatedStringExtensionLite, "spam")
- .addExtension(UnittestLite.repeatedStringExtensionLite, "eggs")
- .setExtension(UnittestLite.optionalNestedEnumExtensionLite,
- TestAllTypesLite.NestedEnum.BAZ)
- .setExtension(UnittestLite.optionalNestedMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(7).build())
- .build();
- TestAllExtensionsLite messageWithUnknownFields = TestAllExtensionsLite.parseFrom(
- messageWithExtensions.toByteArray());
+ TestAllExtensionsLite messageWithExtensions =
+ TestAllExtensionsLite.newBuilder()
+ .setExtension(UnittestLite.optionalInt32ExtensionLite, 123)
+ .addExtension(UnittestLite.repeatedStringExtensionLite, "spam")
+ .addExtension(UnittestLite.repeatedStringExtensionLite, "eggs")
+ .setExtension(
+ UnittestLite.optionalNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ)
+ .setExtension(
+ UnittestLite.optionalNestedMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(7).build())
+ .build();
+ TestAllExtensionsLite messageWithUnknownFields =
+ TestAllExtensionsLite.parseFrom(messageWithExtensions.toByteArray());
assertToStringEquals(
- "1: 123\n18: \"\\b\\a\"\n21: 3\n44: \"spam\"\n44: \"eggs\"",
- messageWithUnknownFields);
+ "1: 123\n18: \"\\b\\a\"\n21: 3\n44: \"spam\"\n44: \"eggs\"", messageWithUnknownFields);
}
-
+
public void testToStringLazyMessage() throws Exception {
- TestAllTypesLite message = TestAllTypesLite.newBuilder()
- .setOptionalLazyMessage(NestedMessage.newBuilder().setBb(1).build())
- .build();
+ TestAllTypesLite message =
+ TestAllTypesLite.newBuilder()
+ .setOptionalLazyMessage(NestedMessage.newBuilder().setBb(1).build())
+ .build();
assertToStringEquals("optional_lazy_message {\n bb: 1\n}", message);
}
-
+
public void testToStringGroup() throws Exception {
- TestAllTypesLite message = TestAllTypesLite.newBuilder()
- .setOptionalGroup(OptionalGroup.newBuilder().setA(1).build())
- .build();
+ TestAllTypesLite message =
+ TestAllTypesLite.newBuilder()
+ .setOptionalGroup(OptionalGroup.newBuilder().setA(1).build())
+ .build();
assertToStringEquals("optional_group {\n a: 1\n}", message);
}
-
+
public void testToStringOneof() throws Exception {
- TestAllTypesLite message = TestAllTypesLite.newBuilder()
- .setOneofString("hello")
- .build();
+ TestAllTypesLite message = TestAllTypesLite.newBuilder().setOneofString("hello").build();
assertToStringEquals("oneof_string: \"hello\"", message);
}
+ public void testToStringMapFields() throws Exception {
+ TestMap message1 =
+ TestMap.newBuilder()
+ .putInt32ToStringField(1, "alpha")
+ .putInt32ToStringField(2, "beta")
+ .build();
+ assertToStringEquals(
+ "int32_to_string_field {\n"
+ + " key: 1\n"
+ + " value: \"alpha\"\n"
+ + "}\n"
+ + "int32_to_string_field {\n"
+ + " key: 2\n"
+ + " value: \"beta\"\n"
+ + "}",
+ message1);
+
+ TestMap message2 =
+ TestMap.newBuilder()
+ .putInt32ToMessageField(1, MessageValue.newBuilder().setValue(10).build())
+ .putInt32ToMessageField(2, MessageValue.newBuilder().setValue(20).build())
+ .build();
+ assertToStringEquals(
+ "int32_to_message_field {\n"
+ + " key: 1\n"
+ + " value {\n"
+ + " value: 10\n"
+ + " }\n"
+ + "}\n"
+ + "int32_to_message_field {\n"
+ + " key: 2\n"
+ + " value {\n"
+ + " value: 20\n"
+ + " }\n"
+ + "}",
+ message2);
+ }
+
// Asserts that the toString() representation of the message matches the expected. This verifies
// the first line starts with a comment; but, does not factor in said comment as part of the
// comparison as it contains unstable addresses.
@@ -1644,38 +1538,38 @@ public class LiteTest extends TestCase {
}
assertEquals(expected, toString);
}
-
+
public void testParseLazy() throws Exception {
- ByteString bb = TestAllTypesLite.newBuilder()
- .setOptionalLazyMessage(NestedMessage.newBuilder()
- .setBb(11)
- .build())
- .build().toByteString();
- ByteString cc = TestAllTypesLite.newBuilder()
- .setOptionalLazyMessage(NestedMessage.newBuilder()
- .setCc(22)
- .build())
- .build().toByteString();
-
+ ByteString bb =
+ TestAllTypesLite.newBuilder()
+ .setOptionalLazyMessage(NestedMessage.newBuilder().setBb(11).build())
+ .build()
+ .toByteString();
+ ByteString cc =
+ TestAllTypesLite.newBuilder()
+ .setOptionalLazyMessage(NestedMessage.newBuilder().setCc(22).build())
+ .build()
+ .toByteString();
+
ByteString concat = bb.concat(cc);
TestAllTypesLite message = TestAllTypesLite.parseFrom(concat);
assertEquals(11, message.getOptionalLazyMessage().getBb());
assertEquals(22L, message.getOptionalLazyMessage().getCc());
}
-
+
public void testParseLazy_oneOf() throws Exception {
- ByteString bb = TestAllTypesLite.newBuilder()
- .setOneofLazyNestedMessage(NestedMessage.newBuilder()
- .setBb(11)
- .build())
- .build().toByteString();
- ByteString cc = TestAllTypesLite.newBuilder()
- .setOneofLazyNestedMessage(NestedMessage.newBuilder()
- .setCc(22)
- .build())
- .build().toByteString();
-
+ ByteString bb =
+ TestAllTypesLite.newBuilder()
+ .setOneofLazyNestedMessage(NestedMessage.newBuilder().setBb(11).build())
+ .build()
+ .toByteString();
+ ByteString cc =
+ TestAllTypesLite.newBuilder()
+ .setOneofLazyNestedMessage(NestedMessage.newBuilder().setCc(22).build())
+ .build()
+ .toByteString();
+
ByteString concat = bb.concat(cc);
TestAllTypesLite message = TestAllTypesLite.parseFrom(concat);
@@ -1684,27 +1578,26 @@ public class LiteTest extends TestCase {
}
public void testMergeFromStream_repeatedField() throws Exception {
- TestAllTypesLite.Builder builder = TestAllTypesLite.newBuilder()
- .addRepeatedString("hello");
+ TestAllTypesLite.Builder builder = TestAllTypesLite.newBuilder().addRepeatedString("hello");
builder.mergeFrom(CodedInputStream.newInstance(builder.build().toByteArray()));
assertEquals(2, builder.getRepeatedStringCount());
}
public void testMergeFromStream_invalidBytes() throws Exception {
- TestAllTypesLite.Builder builder = TestAllTypesLite.newBuilder()
- .setDefaultBool(true);
+ TestAllTypesLite.Builder builder = TestAllTypesLite.newBuilder().setDefaultBool(true);
try {
builder.mergeFrom(CodedInputStream.newInstance("Invalid bytes".getBytes(Internal.UTF_8)));
fail();
- } catch (InvalidProtocolBufferException expected) {}
+ } catch (InvalidProtocolBufferException expected) {
+ }
}
public void testMergeFrom_sanity() throws Exception {
TestAllTypesLite one = TestUtilLite.getAllLiteSetBuilder().build();
byte[] bytes = one.toByteArray();
TestAllTypesLite two = TestAllTypesLite.parseFrom(bytes);
-
+
one = one.toBuilder().mergeFrom(one).build();
two = two.toBuilder().mergeFrom(bytes).build();
assertEquals(one, two);
@@ -1713,14 +1606,14 @@ public class LiteTest extends TestCase {
}
public void testMergeFromNoLazyFieldSharing() throws Exception {
- TestAllTypesLite.Builder sourceBuilder = TestAllTypesLite.newBuilder().setOptionalLazyMessage(
- TestAllTypesLite.NestedMessage.newBuilder().setBb(1));
+ TestAllTypesLite.Builder sourceBuilder =
+ TestAllTypesLite.newBuilder()
+ .setOptionalLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(1));
TestAllTypesLite.Builder targetBuilder =
TestAllTypesLite.newBuilder().mergeFrom(sourceBuilder.build());
assertEquals(1, sourceBuilder.getOptionalLazyMessage().getBb());
// now change the sourceBuilder, and target value shouldn't be affected.
- sourceBuilder.setOptionalLazyMessage(
- TestAllTypesLite.NestedMessage.newBuilder().setBb(2));
+ sourceBuilder.setOptionalLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(2));
assertEquals(1, targetBuilder.getOptionalLazyMessage().getBb());
}
@@ -1728,508 +1621,373 @@ public class LiteTest extends TestCase {
TestAllTypesLite one = TestUtilLite.getAllLiteSetBuilder().build();
byte[] bytes = one.toByteArray();
TestAllTypesLite two = one.toBuilder().mergeFrom(one).mergeFrom(bytes).build();
-
+
assertFalse(one.equals(two));
assertFalse(two.equals(one));
-
+
assertFalse(one.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(one));
-
- TestAllTypesLite oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultBool(true)
- .build();
+
+ TestAllTypesLite oneFieldSet = TestAllTypesLite.newBuilder().setDefaultBool(true).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultBytes(ByteString.EMPTY)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultBytes(ByteString.EMPTY).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultCord("")
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultCord("").build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultCordBytes(ByteString.EMPTY)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultCordBytes(ByteString.EMPTY).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultDouble(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultDouble(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultFixed32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultFixed32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultFixed64(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultFixed64(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultFloat(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultFloat(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR)
- .build();
+
+ oneFieldSet =
+ TestAllTypesLite.newBuilder()
+ .setDefaultForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR)
+ .build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultImportEnum(ImportEnumLite.IMPORT_LITE_BAR)
- .build();
+
+ oneFieldSet =
+ TestAllTypesLite.newBuilder().setDefaultImportEnum(ImportEnumLite.IMPORT_LITE_BAR).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultInt32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultInt32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultInt64(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultInt64(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultNestedEnum(NestedEnum.BAR)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultNestedEnum(NestedEnum.BAR).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultSfixed32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultSfixed32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultSfixed64(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultSfixed64(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultSint32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultSint32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultSint64(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultSint64(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultString("")
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultString("").build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultStringBytes(ByteString.EMPTY)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultStringBytes(ByteString.EMPTY).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultStringPiece("")
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultStringPiece("").build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultStringPieceBytes(ByteString.EMPTY)
- .build();
+
+ oneFieldSet =
+ TestAllTypesLite.newBuilder().setDefaultStringPieceBytes(ByteString.EMPTY).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultUint32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultUint32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setDefaultUint64(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setDefaultUint64(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedBool(true)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedBool(true).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedBytes(ByteString.EMPTY)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedBytes(ByteString.EMPTY).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedCord("")
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedCord("").build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedCordBytes(ByteString.EMPTY)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedCordBytes(ByteString.EMPTY).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedDouble(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedDouble(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedFixed32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedFixed32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedFixed64(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedFixed64(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedFloat(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedFloat(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR)
- .build();
+
+ oneFieldSet =
+ TestAllTypesLite.newBuilder()
+ .addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR)
+ .build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedImportEnum(ImportEnumLite.IMPORT_LITE_BAR)
- .build();
+
+ oneFieldSet =
+ TestAllTypesLite.newBuilder().addRepeatedImportEnum(ImportEnumLite.IMPORT_LITE_BAR).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedInt32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedInt32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedInt64(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedInt64(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedNestedEnum(NestedEnum.BAR)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedNestedEnum(NestedEnum.BAR).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedSfixed32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedSfixed32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedSfixed64(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedSfixed64(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedSint32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedSint32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedSint64(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedSint64(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedString("")
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedString("").build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedStringBytes(ByteString.EMPTY)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedStringBytes(ByteString.EMPTY).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedStringPiece("")
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedStringPiece("").build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedStringPieceBytes(ByteString.EMPTY)
- .build();
+
+ oneFieldSet =
+ TestAllTypesLite.newBuilder().addRepeatedStringPieceBytes(ByteString.EMPTY).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedUint32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedUint32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedUint64(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedUint64(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalBool(true)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalBool(true).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalBytes(ByteString.EMPTY)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalBytes(ByteString.EMPTY).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalCord("")
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalCord("").build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalCordBytes(ByteString.EMPTY)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalCordBytes(ByteString.EMPTY).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalDouble(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalDouble(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalFixed32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalFixed32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalFixed64(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalFixed64(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalFloat(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalFloat(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR)
- .build();
+
+ oneFieldSet =
+ TestAllTypesLite.newBuilder()
+ .setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR)
+ .build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalImportEnum(ImportEnumLite.IMPORT_LITE_BAR)
- .build();
+
+ oneFieldSet =
+ TestAllTypesLite.newBuilder().setOptionalImportEnum(ImportEnumLite.IMPORT_LITE_BAR).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalInt32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalInt32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalInt64(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalInt64(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalNestedEnum(NestedEnum.BAR)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalNestedEnum(NestedEnum.BAR).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalSfixed32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalSfixed32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalSfixed64(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalSfixed64(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalSint32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalSint32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalSint64(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalSint64(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalString("")
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalString("").build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalStringBytes(ByteString.EMPTY)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalStringBytes(ByteString.EMPTY).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalStringPiece("")
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalStringPiece("").build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalStringPieceBytes(ByteString.EMPTY)
- .build();
+
+ oneFieldSet =
+ TestAllTypesLite.newBuilder().setOptionalStringPieceBytes(ByteString.EMPTY).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalUint32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalUint32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalUint64(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOptionalUint64(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOneofBytes(ByteString.EMPTY)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOneofBytes(ByteString.EMPTY).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOneofLazyNestedMessage(NestedMessage.getDefaultInstance())
- .build();
+
+ oneFieldSet =
+ TestAllTypesLite.newBuilder()
+ .setOneofLazyNestedMessage(NestedMessage.getDefaultInstance())
+ .build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOneofNestedMessage(NestedMessage.getDefaultInstance())
- .build();
+
+ oneFieldSet =
+ TestAllTypesLite.newBuilder()
+ .setOneofNestedMessage(NestedMessage.getDefaultInstance())
+ .build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOneofString("")
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOneofString("").build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOneofStringBytes(ByteString.EMPTY)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOneofStringBytes(ByteString.EMPTY).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
-
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOneofUint32(0)
- .build();
+
+ oneFieldSet = TestAllTypesLite.newBuilder().setOneofUint32(0).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalForeignMessage(ForeignMessageLite.getDefaultInstance())
- .build();
+ oneFieldSet =
+ TestAllTypesLite.newBuilder()
+ .setOptionalForeignMessage(ForeignMessageLite.getDefaultInstance())
+ .build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalGroup(OptionalGroup.getDefaultInstance())
- .build();
+ oneFieldSet =
+ TestAllTypesLite.newBuilder().setOptionalGroup(OptionalGroup.getDefaultInstance()).build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalPublicImportMessage(PublicImportMessageLite.getDefaultInstance())
- .build();
+ oneFieldSet =
+ TestAllTypesLite.newBuilder()
+ .setOptionalPublicImportMessage(PublicImportMessageLite.getDefaultInstance())
+ .build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
- oneFieldSet = TestAllTypesLite.newBuilder()
- .setOptionalLazyMessage(NestedMessage.getDefaultInstance())
- .build();
+ oneFieldSet =
+ TestAllTypesLite.newBuilder()
+ .setOptionalLazyMessage(NestedMessage.getDefaultInstance())
+ .build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
-
+
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
- oneFieldSet = TestAllTypesLite.newBuilder()
- .addRepeatedLazyMessage(NestedMessage.getDefaultInstance())
- .build();
+ oneFieldSet =
+ TestAllTypesLite.newBuilder()
+ .addRepeatedLazyMessage(NestedMessage.getDefaultInstance())
+ .build();
assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance()));
assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet));
}
public void testEquals() throws Exception {
// Check that two identical objs are equal.
- Foo foo1a = Foo.newBuilder()
- .setValue(1)
- .addBar(Bar.newBuilder().setName("foo1"))
- .build();
- Foo foo1b = Foo.newBuilder()
- .setValue(1)
- .addBar(Bar.newBuilder().setName("foo1"))
- .build();
- Foo foo2 = Foo.newBuilder()
- .setValue(1)
- .addBar(Bar.newBuilder().setName("foo2"))
- .build();
+ Foo foo1a = Foo.newBuilder().setValue(1).addBar(Bar.newBuilder().setName("foo1")).build();
+ Foo foo1b = Foo.newBuilder().setValue(1).addBar(Bar.newBuilder().setName("foo1")).build();
+ Foo foo2 = Foo.newBuilder().setValue(1).addBar(Bar.newBuilder().setName("foo2")).build();
// Check that equals is doing value rather than object equality.
assertEquals(foo1a, foo1b);
@@ -2246,17 +2004,10 @@ public class LiteTest extends TestCase {
}
public void testEqualsAndHashCodeForTrickySchemaTypes() {
- Foo foo1 = Foo.newBuilder()
- .build();
- Foo foo2 = Foo.newBuilder()
- .setSint64(1)
- .build();
- Foo foo3 = Foo.newBuilder()
- .putMyMap("key", "value2")
- .build();
- Foo foo4 = Foo.newBuilder()
- .setMyGroup(Foo.MyGroup.newBuilder().setValue(4).build())
- .build();
+ Foo foo1 = Foo.getDefaultInstance();
+ Foo foo2 = Foo.newBuilder().setSint64(1).build();
+ Foo foo3 = Foo.newBuilder().putMyMap("key", "value2").build();
+ Foo foo4 = Foo.newBuilder().setMyGroup(Foo.MyGroup.newBuilder().setValue(4).build()).build();
assertEqualsAndHashCodeAreFalse(foo1, foo2);
assertEqualsAndHashCodeAreFalse(foo1, foo3);
@@ -2272,29 +2023,27 @@ public class LiteTest extends TestCase {
TestOneofEquals message2 = builder.build();
assertFalse(message1.equals(message2));
}
-
+
public void testEquals_sanity() throws Exception {
TestAllTypesLite one = TestUtilLite.getAllLiteSetBuilder().build();
TestAllTypesLite two = TestAllTypesLite.parseFrom(one.toByteArray());
assertEquals(one, two);
assertEquals(one.hashCode(), two.hashCode());
-
+
assertEquals(
one.toBuilder().mergeFrom(two).build(),
two.toBuilder().mergeFrom(two.toByteArray()).build());
}
public void testEqualsAndHashCodeWithUnknownFields() throws InvalidProtocolBufferException {
- Foo fooWithOnlyValue = Foo.newBuilder()
- .setValue(1)
- .build();
+ Foo fooWithOnlyValue = Foo.newBuilder().setValue(1).build();
- Foo fooWithValueAndExtension = fooWithOnlyValue.toBuilder()
- .setValue(1)
- .setExtension(Bar.fooExt, Bar.newBuilder()
- .setName("name")
- .build())
- .build();
+ Foo fooWithValueAndExtension =
+ fooWithOnlyValue
+ .toBuilder()
+ .setValue(1)
+ .setExtension(Bar.fooExt, Bar.newBuilder().setName("name").build())
+ .build();
Foo fooWithValueAndUnknownFields = Foo.parseFrom(fooWithValueAndExtension.toByteArray());
@@ -2303,30 +2052,27 @@ public class LiteTest extends TestCase {
}
public void testEqualsAndHashCodeWithExtensions() throws InvalidProtocolBufferException {
- Foo fooWithOnlyValue = Foo.newBuilder()
- .setValue(1)
- .build();
+ Foo fooWithOnlyValue = Foo.newBuilder().setValue(1).build();
- Foo fooWithValueAndExtension = fooWithOnlyValue.toBuilder()
- .setValue(1)
- .setExtension(Bar.fooExt, Bar.newBuilder()
- .setName("name")
- .build())
- .build();
+ Foo fooWithValueAndExtension =
+ fooWithOnlyValue
+ .toBuilder()
+ .setValue(1)
+ .setExtension(Bar.fooExt, Bar.newBuilder().setName("name").build())
+ .build();
assertEqualsAndHashCodeAreFalse(fooWithOnlyValue, fooWithValueAndExtension);
}
-
+
// Test to ensure we avoid a class cast exception with oneofs.
public void testEquals_oneOfMessages() {
- TestAllTypesLite mine = TestAllTypesLite.newBuilder()
- .setOneofString("Hello")
- .build();
-
- TestAllTypesLite other = TestAllTypesLite.newBuilder()
- .setOneofNestedMessage(NestedMessage.getDefaultInstance())
- .build();
-
+ TestAllTypesLite mine = TestAllTypesLite.newBuilder().setOneofString("Hello").build();
+
+ TestAllTypesLite other =
+ TestAllTypesLite.newBuilder()
+ .setOneofNestedMessage(NestedMessage.getDefaultInstance())
+ .build();
+
assertFalse(mine.equals(other));
assertFalse(other.equals(mine));
}
@@ -2376,16 +2122,13 @@ public class LiteTest extends TestCase {
public void testParseFromByteBufferThrows() {
try {
- TestAllTypesLite.parseFrom(ByteBuffer.wrap(new byte[] { 0x5 }));
+ TestAllTypesLite.parseFrom(ByteBuffer.wrap(new byte[] {0x5}));
fail();
} catch (InvalidProtocolBufferException expected) {
}
TestAllTypesLite message =
- TestAllTypesLite.newBuilder()
- .setOptionalInt32(123)
- .addRepeatedString("hello")
- .build();
+ TestAllTypesLite.newBuilder().setOptionalInt32(123).addRepeatedString("hello").build();
ByteBuffer buffer = ByteBuffer.wrap(message.toByteArray(), 0, message.getSerializedSize() - 1);
try {
@@ -2393,9 +2136,7 @@ public class LiteTest extends TestCase {
fail();
} catch (InvalidProtocolBufferException expected) {
assertEquals(
- TestAllTypesLite.newBuilder()
- .setOptionalInt32(123)
- .build(),
+ TestAllTypesLite.newBuilder().setOptionalInt32(123).build(),
expected.getUnfinishedMessage());
}
}
@@ -2425,7 +2166,7 @@ public class LiteTest extends TestCase {
ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance();
UnittestLite.registerAllExtensions(registry);
try {
- TestAllExtensionsLite.parseFrom(ByteBuffer.wrap(new byte[] { 0x5 }), registry);
+ TestAllExtensionsLite.parseFrom(ByteBuffer.wrap(new byte[] {0x5}), registry);
fail();
} catch (InvalidProtocolBufferException expected) {
}
@@ -2466,26 +2207,24 @@ public class LiteTest extends TestCase {
}
public void testAddAllIteratesOnce() {
- TestAllTypesLite message =
- TestAllTypesLite.newBuilder()
- .addAllRepeatedBool(new OneTimeIterableList(false))
- .addAllRepeatedInt32(new OneTimeIterableList(0))
- .addAllRepeatedInt64(new OneTimeIterableList(0L))
- .addAllRepeatedFloat(new OneTimeIterableList(0f))
- .addAllRepeatedDouble(new OneTimeIterableList(0d))
- .addAllRepeatedBytes(new OneTimeIterableList(ByteString.EMPTY))
- .addAllRepeatedString(new OneTimeIterableList(""))
- .addAllRepeatedNestedMessage(
- new OneTimeIterableList(NestedMessage.getDefaultInstance()))
- .addAllRepeatedBool(new OneTimeIterable(false))
- .addAllRepeatedInt32(new OneTimeIterable(0))
- .addAllRepeatedInt64(new OneTimeIterable(0L))
- .addAllRepeatedFloat(new OneTimeIterable(0f))
- .addAllRepeatedDouble(new OneTimeIterable(0d))
- .addAllRepeatedBytes(new OneTimeIterable(ByteString.EMPTY))
- .addAllRepeatedString(new OneTimeIterable(""))
- .addAllRepeatedNestedMessage(new OneTimeIterable(NestedMessage.getDefaultInstance()))
- .build();
+ TestAllTypesLite.newBuilder()
+ .addAllRepeatedBool(new OneTimeIterableList(false))
+ .addAllRepeatedInt32(new OneTimeIterableList(0))
+ .addAllRepeatedInt64(new OneTimeIterableList(0L))
+ .addAllRepeatedFloat(new OneTimeIterableList(0f))
+ .addAllRepeatedDouble(new OneTimeIterableList(0d))
+ .addAllRepeatedBytes(new OneTimeIterableList(ByteString.EMPTY))
+ .addAllRepeatedString(new OneTimeIterableList(""))
+ .addAllRepeatedNestedMessage(new OneTimeIterableList(NestedMessage.getDefaultInstance()))
+ .addAllRepeatedBool(new OneTimeIterable(false))
+ .addAllRepeatedInt32(new OneTimeIterable(0))
+ .addAllRepeatedInt64(new OneTimeIterable(0L))
+ .addAllRepeatedFloat(new OneTimeIterable(0f))
+ .addAllRepeatedDouble(new OneTimeIterable(0d))
+ .addAllRepeatedBytes(new OneTimeIterable(ByteString.EMPTY))
+ .addAllRepeatedString(new OneTimeIterable(""))
+ .addAllRepeatedNestedMessage(new OneTimeIterable(NestedMessage.getDefaultInstance()))
+ .build();
}
public void testAddAllIteratesOnce_throwsOnNull() {
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 6bbdfcaa..e50c7d1e 100644
--- a/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java
@@ -32,6 +32,7 @@ package com.google.protobuf;
import static java.util.Arrays.asList;
+import com.google.protobuf.Internal.LongList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
@@ -297,6 +298,20 @@ public class LongArrayListTest extends TestCase {
}
}
+ public void testRemoveEndOfCapacity() {
+ LongList toRemove = LongArrayList.emptyList().mutableCopyWithCapacity(1);
+ toRemove.addLong(3);
+ toRemove.remove(0);
+ assertEquals(0, toRemove.size());
+ }
+
+ public void testSublistRemoveEndOfCapacity() {
+ LongList toRemove = LongArrayList.emptyList().mutableCopyWithCapacity(1);
+ toRemove.addLong(3);
+ toRemove.subList(0, 1).clear();
+ assertEquals(0, toRemove.size());
+ }
+
private void assertImmutable(LongArrayList 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/MapForProto2Test.java b/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java
index 37827f76..bcfd927c 100644
--- a/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java
+++ b/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java
@@ -788,6 +788,24 @@ public class MapForProto2Test extends TestCase {
assertEquals(message.hashCode(), dynamicMessage.hashCode());
}
+ // Check that DynamicMessage handles map field serialization the same way as generated code
+ // regarding unset key and value field in a map entry.
+ public void testDynamicMessageUnsetKeyAndValue() throws Exception {
+ FieldDescriptor field = f("int32_to_int32_field");
+
+ 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());
+ Message message = builder.build();
+ ByteString bytes = message.toByteString();
+ // Parse it back to the same generated type.
+ Message generatedMessage = TestMap.parseFrom(bytes);
+ // Assert the serialized bytes are equivalent.
+ assertEquals(generatedMessage.toByteString(), bytes);
+ }
+
public void testReflectionEqualsAndHashCode() throws Exception {
// Test that generated equals() and hashCode() will disregard the order
// of map entries when comparing/hashing map fields.
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 64ae4435..58efce92 100644
--- a/java/core/src/test/java/com/google/protobuf/MapTest.java
+++ b/java/core/src/test/java/com/google/protobuf/MapTest.java
@@ -893,6 +893,24 @@ public class MapTest extends TestCase {
assertEquals(message.hashCode(), dynamicMessage.hashCode());
}
+ // Check that DynamicMessage handles map field serialization the same way as generated code
+ // regarding unset key and value field in a map entry.
+ public void testDynamicMessageUnsetKeyAndValue() throws Exception {
+ FieldDescriptor field = f("int32_to_int32_field");
+
+ 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());
+ Message message = builder.build();
+ ByteString bytes = message.toByteString();
+ // Parse it back to the same generated type.
+ Message generatedMessage = TestMap.parseFrom(bytes);
+ // Assert the serialized bytes are equivalent.
+ assertEquals(generatedMessage.toByteString(), bytes);
+ }
+
public void testReflectionEqualsAndHashCode() throws Exception {
// Test that generated equals() and hashCode() will disregard the order
// of map entries when comparing/hashing map fields.
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 5d38ca51..720061d2 100644
--- a/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
+++ b/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
@@ -61,12 +61,11 @@ import junit.framework.TestCase;
public class TextFormatTest extends TestCase {
// A basic string with different escapable characters for testing.
- private final static String kEscapeTestString =
- "\"A string with ' characters \n and \r newlines and \t tabs and \001 "
- + "slashes \\";
+ private static final String ESCAPE_TEST_STRING =
+ "\"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 final static String kEscapeTestStringEscaped =
+ private static final String ESCAPE_TEST_STRING_ESCAPED =
"\\\"A string with \\' characters \\n and \\r newlines "
+ "and \\t tabs and \\001 slashes \\\\";
@@ -576,10 +575,10 @@ public class TextFormatTest extends TestCase {
"integer: 82301481290849012385230157",
"optional_int32: 82301481290849012385230157");
assertParseError(
- "1:16: Expected \"true\" or \"false\".",
+ "1:16: Expected \"true\" or \"false\". Found \"maybe\".",
"optional_bool: maybe");
assertParseError(
- "1:16: Expected \"true\" or \"false\".",
+ "1:16: Expected \"true\" or \"false\". Found \"2\".",
"optional_bool: 2");
assertParseError(
"1:18: Expected string.",
@@ -643,10 +642,8 @@ public class TextFormatTest extends TestCase {
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(kEscapeTestStringEscaped,
- TextFormat.escapeText(kEscapeTestString));
- assertEquals(kEscapeTestString,
- TextFormat.unescapeText(kEscapeTestStringEscaped));
+ assertEquals(ESCAPE_TEST_STRING_ESCAPED, TextFormat.escapeText(ESCAPE_TEST_STRING));
+ assertEquals(ESCAPE_TEST_STRING, TextFormat.unescapeText(ESCAPE_TEST_STRING_ESCAPED));
// Invariant
assertEquals("hello",
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 9928d44a..8ce0ca73 100644
--- a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java
@@ -30,6 +30,8 @@
package com.google.protobuf;
+import static junit.framework.TestCase.assertEquals;
+
import com.google.protobuf.UnittestLite.TestAllExtensionsLite;
import com.google.protobuf.UnittestLite.TestAllTypesLite;
import protobuf_unittest.UnittestProto;
@@ -133,6 +135,25 @@ public class UnknownFieldSetLiteTest extends TestCase {
assertEquals(foo.toByteString().size(), instance.getSerializedSize());
}
+ public void testHashCodeAfterDeserialization() throws IOException {
+ Foo foo = Foo.newBuilder()
+ .setValue(2)
+ .build();
+
+ Foo fooDeserialized = Foo.parseFrom(foo.toByteArray());
+
+ assertEquals(fooDeserialized, foo);
+ assertEquals(foo.hashCode(), fooDeserialized.hashCode());
+ }
+
+ public void testNewInstanceHashCode() {
+ UnknownFieldSetLite emptyFieldSet = UnknownFieldSetLite.getDefaultInstance();
+ UnknownFieldSetLite paddedFieldSet = UnknownFieldSetLite.newInstance();
+
+ assertEquals(emptyFieldSet, paddedFieldSet);
+ assertEquals(emptyFieldSet.hashCode(), paddedFieldSet.hashCode());
+ }
+
public void testMergeVarintField() throws IOException {
UnknownFieldSetLite unknownFields = UnknownFieldSetLite.newInstance();
unknownFields.mergeVarintField(10, 2);
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 625d4b42..03c33ecf 100644
--- a/java/core/src/test/java/com/google/protobuf/WireFormatTest.java
+++ b/java/core/src/test/java/com/google/protobuf/WireFormatTest.java
@@ -36,6 +36,7 @@ import protobuf_unittest.UnittestMset.TestMessageSetExtension2;
import protobuf_unittest.UnittestProto;
import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestAllTypes;
+import protobuf_unittest.UnittestProto.TestExtensionInsideTable;
import protobuf_unittest.UnittestProto.TestFieldOrderings;
import protobuf_unittest.UnittestProto.TestOneof2;
import protobuf_unittest.UnittestProto.TestOneofBackwardsCompatible;
@@ -235,6 +236,26 @@ public class WireFormatTest extends TestCase {
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();
+ TestExtensionInsideTable dest =
+ TestExtensionInsideTable.parseFrom(source.toByteString(),
+ getTestExtensionInsideTableRegistry());
+ assertEquals(source, dest);
+ }
public void testParseMultipleExtensionRangesDynamic() throws Exception {
// Same as above except with DynamicMessage.
diff --git a/java/core/src/test/proto/com/google/protobuf/map_lite_test.proto b/java/core/src/test/proto/com/google/protobuf/map_lite_test.proto
new file mode 100644
index 00000000..c04f5d57
--- /dev/null
+++ b/java/core/src/test/proto/com/google/protobuf/map_lite_test.proto
@@ -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.
+
+syntax = "proto3";
+
+package map_lite_test;
+
+option optimize_for = LITE_RUNTIME;
+option java_package = "map_lite_test";
+option java_outer_classname = "MapTestProto";
+
+message TestMap {
+ message MessageValue {
+ int32 value = 1;
+ }
+ enum EnumValue {
+ FOO = 0;
+ BAR = 1;
+ BAZ = 2;
+ QUX = 3;
+ }
+
+ map<int32, int32> int32_to_int32_field = 1;
+ map<int32, string> int32_to_string_field = 2;
+ map<int32, bytes> int32_to_bytes_field = 3;
+ map<int32, EnumValue> int32_to_enum_field = 4;
+ map<int32, MessageValue> int32_to_message_field = 5;
+ map<string, int32> string_to_int32_field = 6;
+ map<uint32, int32> uint32_to_int32_field = 7;
+ map<int64, int32> int64_to_int32_field = 8;
+}
+
+// Used to test that a nested builder containing map fields will properly
+// propagate the onChange event and mark its parent dirty when a change
+// is made to a map field.
+message TestOnChangeEventPropagation {
+ TestMap optional_message = 1;
+}
+
+// a decoy of TestMap for testing parsing errors
+message BizarroTestMap {
+ map<int32, bytes> int32_to_int32_field = 1; // same key type, different value
+ map<string, int32> int32_to_string_field = 2; // different key and value types
+ map<string, int32> int32_to_bytes_field = 3; // different key types, same value
+ map<string, bytes> int32_to_enum_field = 4; // different key and value types
+ map<string, bytes> int32_to_message_field = 5; // different key and value types
+ map<string, bytes> string_to_int32_field = 6; // same key type, different value
+}
+
+// Used to test that java reserved words can be used as protobuf field names
+// Not all reserved words are tested (to avoid bloat) but instead an arbitrary
+// subset of them chosen to cover various keyword categories like
+// type, modifier, declaration, etc.
+message ReservedAsMapField {
+ map<string, uint32> if = 1;
+ map<string, uint32> const = 2;
+ map<string, uint32> private = 3;
+ map<string, uint32> class = 4;
+ map<string, uint32> int = 5;
+ map<string, uint32> void = 6;
+ map<string, uint32> string = 7; // These are also proto keywords
+ map<string, uint32> package = 8;
+ map<string, uint32> enum = 9; // Most recent Java reserved word
+ map<string, uint32> null = 10;
+ // null is not a 'reserved word' per se but as a literal needs similar care
+}
+
+message ReservedAsMapFieldWithEnumValue {
+ enum SampleEnum {
+ A = 0;
+ B = 1;
+ }
+ map<string, SampleEnum> if = 1;
+ map<string, SampleEnum> const = 2;
+ map<string, SampleEnum> private = 3;
+ map<string, SampleEnum> class = 4;
+ map<string, SampleEnum> int = 5;
+ map<string, SampleEnum> void = 6;
+ map<string, SampleEnum> string = 7; // These are also proto keywords
+ map<string, SampleEnum> package = 8;
+ map<string, SampleEnum> enum = 9; // Most recent Java reserved word
+ map<string, SampleEnum> null = 10;
+ // null is not a 'reserved word' per se but as a literal needs similar care
+}
diff --git a/java/lite.md b/java/lite.md
new file mode 100644
index 00000000..84a45ec5
--- /dev/null
+++ b/java/lite.md
@@ -0,0 +1,50 @@
+# Protocol Buffers - Google's data interchange format
+
+Copyright 2008 Google Inc.
+
+https://developers.google.com/protocol-buffers/
+
+## Use Protobuf Java Lite Runtime
+
+Protobuf Java Lite runtime is separated from the main Java runtime because
+it's designed/implemented with different constraints. In particular, Java
+Lite runtime has a much smaller code size which makes it more suitable to
+be used on Android.
+
+To use Java Lite runtime, you need to install protoc and the protoc plugin for
+Java Lite runtime. You can obtain protoc following the instructions in the
+toplevel [README.md](../README.md) file. For the protoc plugin, you can
+download it from maven:
+
+ https://repo1.maven.org/maven2/com/google/protobuf/protoc-gen-javalite/
+
+Choose the version that works on your platform (e.g., on windows you can
+download `protoc-gen-javalite-3.0.0-windows-x86_32.exe`), rename it to
+protoc-gen-javalite (or protoc-gen-javalite.exe on windows) and place it
+in a directory where it can be find in PATH.
+
+Once you have the protoc and protoc plugin, you can generate Java Lite code
+for your .proto files:
+
+ $ protoc --javalite_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:
+
+```xml
+<dependency>
+ <groupId>com.google.protobuf</groupId>
+ <artifactId>protobuf-lite</artifactId>
+ <version>3.0.1</version>
+</dependency>
+```
+
+Make sure the version number of the runtime matches (or is newer than) the
+version number of the protoc plugin. The version number of the protoc doesn't
+matter and any version >= 3.0.0 should work.
+
+### Use Protobuf Java Lite Runtime with Bazel
+
+Bazel has native build rules to work with protobuf. For Java Lite runtime,
+you can use the `java_lite_proto_library` rule. Check out [our build files
+examples](../examples/BUILD) to learn how to use it.
diff --git a/java/lite/generate-sources-build.xml b/java/lite/generate-sources-build.xml
deleted file mode 100644
index 89c21c13..00000000
--- a/java/lite/generate-sources-build.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<project name="generate-sources">
- <echo message="Running protoc ..."/>
- <mkdir dir="${generated.sources.lite.dir}"/>
- <exec executable="${protoc}">
- <arg value="--java_out=lite:${generated.sources.lite.dir}"/>
- <arg value="--proto_path=${protobuf.source.dir}"/>
- <arg value="${protobuf.source.dir}/google/protobuf/any.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/api.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/descriptor.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/duration.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/empty.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/field_mask.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/source_context.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/struct.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/timestamp.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/type.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/wrappers.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/compiler/plugin.proto"/>
- </exec>
-</project>
diff --git a/java/lite/generate-test-sources-build.xml b/java/lite/generate-test-sources-build.xml
deleted file mode 100644
index cdd1ee89..00000000
--- a/java/lite/generate-test-sources-build.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<project name="generate-test-sources">
- <mkdir dir="${generated.testsources.lite.dir}"/>
- <exec executable="${protoc}">
- <arg value="--java_out=lite:${generated.testsources.lite.dir}"/>
- <arg value="--proto_path=${protobuf.source.dir}"/>
- <arg value="--proto_path=${test.proto.dir}"/>
- <arg value="${protobuf.source.dir}/google/protobuf/unittest.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/unittest_import.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/unittest_import_public.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/unittest_mset.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/unittest_mset_wire_format.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/unittest_optimize_for.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/unittest_custom_options.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/unittest_lite.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/unittest_import_lite.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/unittest_import_public_lite.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/unittest_lite_imports_nonlite.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/unittest_enormous_descriptor.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/unittest_no_generic_services.proto"/>
- <arg value="${protobuf.source.dir}/google/protobuf/unittest_well_known_types.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/lazy_fields_lite.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/lite_equals_and_hash.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/multiple_files_test.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/nested_builders_test.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/nested_extension.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/nested_extension_lite.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/non_nested_extension.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/non_nested_extension_lite.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/outer_class_name_test.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/outer_class_name_test2.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/outer_class_name_test3.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/test_bad_identifiers.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/test_check_utf8.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/test_check_utf8_size.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/test_custom_options.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/any_test.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/field_presence_test.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/map_for_proto2_lite_test.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/map_for_proto2_test.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/map_test.proto"/>
- <arg value="${test.proto.dir}/com/google/protobuf/map_initialization_order_test.proto"/>
- </exec>
-</project>
diff --git a/java/lite/pom.xml b/java/lite/pom.xml
deleted file mode 100644
index c902f819..00000000
--- a/java/lite/pom.xml
+++ /dev/null
@@ -1,185 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>com.google.protobuf</groupId>
- <artifactId>protobuf-parent</artifactId>
- <version>3.0.0</version>
- </parent>
-
- <artifactId>protobuf-lite</artifactId>
- <packaging>bundle</packaging>
-
- <name>Protocol Buffers [Lite]</name>
- <description>A trimmed-down version of the Protocol Buffers library.</description>
-
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- </dependency>
- <dependency>
- <groupId>org.easymock</groupId>
- <artifactId>easymock</artifactId>
- </dependency>
- <dependency>
- <groupId>org.easymock</groupId>
- <artifactId>easymockclassextension</artifactId>
- </dependency>
- </dependencies>
-
- <properties>
- <core.root>../core</core.root>
- <test.proto.dir>${core.root}/src/test/proto</test.proto.dir>
- </properties>
-
- <build>
- <sourceDirectory>${core.root}/src/main/java</sourceDirectory>
- <testSourceDirectory>${core.root}/src/test/java</testSourceDirectory>
-
- <plugins>
- <!-- Use Antrun plugin to generate sources with protoc -->
- <plugin>
- <artifactId>maven-antrun-plugin</artifactId>
- <executions>
- <!-- Generate core protos -->
- <execution>
- <id>generate-sources</id>
- <phase>generate-sources</phase>
- <configuration>
- <target>
- <ant antfile="generate-sources-build.xml"/>
- </target>
- </configuration>
- <goals>
- <goal>run</goal>
- </goals>
- </execution>
-
- <!-- Generate the test protos -->
- <execution>
- <id>generate-test-sources</id>
- <phase>generate-test-sources</phase>
- <configuration>
- <target>
- <ant antfile="generate-test-sources-build.xml"/>
- </target>
- </configuration>
- <goals>
- <goal>run</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
- <!-- Only compile a subset of the files -->
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>add-generated-sources</id>
- <phase>generate-sources</phase>
- <goals>
- <goal>add-source</goal>
- </goals>
- <configuration>
- <sources>
- <source>${generated.sources.lite.dir}</source>
- </sources>
- </configuration>
- </execution>
- <execution>
- <id>add-generated-test-sources</id>
- <phase>generate-test-sources</phase>
- <goals>
- <goal>add-test-source</goal>
- </goals>
- <configuration>
- <sources>
- <source>${generated.testsources.lite.dir}</source>
- </sources>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <includes>
- <include>**/AbstractMessageLite.java</include>
- <include>**/AbstractParser.java</include>
- <include>**/AbstractProtobufList.java</include>
- <include>**/BooleanArrayList.java</include>
- <include>**/ByteString.java</include>
- <include>**/CodedInputStream.java</include>
- <include>**/CodedOutputStream.java</include>
- <include>**/DoubleArrayList.java</include>
- <include>**/ExtensionLite.java</include>
- <include>**/ExtensionRegistryLite.java</include>
- <include>**/FieldSet.java</include>
- <include>**/FloatArrayList.java</include>
- <include>**/GeneratedMessageLite.java</include>
- <include>**/IntArrayList.java</include>
- <include>**/Internal.java</include>
- <include>**/InvalidProtocolBufferException.java</include>
- <include>**/LazyFieldLite.java</include>
- <include>**/LazyStringArrayList.java</include>
- <include>**/LazyStringList.java</include>
- <include>**/LongArrayList.java</include>
- <include>**/MapEntryLite.java</include>
- <include>**/MapFieldLite.java</include>
- <include>**/MessageLite.java</include>
- <include>**/MessageLiteOrBuilder.java</include>
- <include>**/MessageLiteToString.java</include>
- <include>**/MutabilityOracle.java</include>
- <include>**/NioByteString.java</include>
- <include>**/Parser.java</include>
- <include>**/PrimitiveNonBoxingCollection.java</include>
- <include>**/ProtobufArrayList.java</include>
- <include>**/ProtocolStringList.java</include>
- <include>**/RopeByteString.java</include>
- <include>**/SmallSortedMap.java</include>
- <include>**/TextFormatEscaper.java</include>
- <include>**/UninitializedMessageException.java</include>
- <include>**/UnknownFieldSetLite.java</include>
- <include>**/UnmodifiableLazyStringList.java</include>
- <include>**/UnsafeByteOperations.java</include>
- <include>**/Utf8.java</include>
- <include>**/WireFormat.java</include>
- </includes>
- <testIncludes>
- <testInclude>**/*Lite.java</testInclude>
- <testInclude>**/BooleanArrayListTest.java</testInclude>
- <testInclude>**/DoubleArrayListTest.java</testInclude>
- <testInclude>**/FloatArrayListTest.java</testInclude>
- <testInclude>**/IntArrayListTest.java</testInclude>
- <testInclude>**/LazyMessageLiteTest.java</testInclude>
- <testInclude>**/LiteTest.java</testInclude>
- <testInclude>**/LongArrayListTest.java</testInclude>
- <testInclude>**/NioByteStringTest.java</testInclude>
- <testInclude>**/ProtobufArrayListTest.java</testInclude>
- <testInclude>**/UnknownFieldSetLiteTest.java</testInclude>
- </testIncludes>
- </configuration>
- </plugin>
-
- <!-- OSGI bundle configuration -->
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Bundle-DocURL>https://developers.google.com/protocol-buffers/</Bundle-DocURL>
- <Bundle-SymbolicName>com.google.protobuf</Bundle-SymbolicName>
- <Export-Package>com.google.${project.artifactId};version=${project.version}</Export-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
-</project>
diff --git a/java/pom.xml b/java/pom.xml
index b7c3e485..35d653b4 100644
--- a/java/pom.xml
+++ b/java/pom.xml
@@ -11,7 +11,7 @@
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-parent</artifactId>
- <version>3.5.1</version>
+ <version>3.6.0</version>
<packaging>pom</packaging>
<name>Protocol Buffers [Parent]</name>
@@ -33,8 +33,6 @@
<test.proto.dir>src/test/proto</test.proto.dir>
<generated.sources.dir>${project.build.directory}/generated-sources</generated.sources.dir>
<generated.testsources.dir>${project.build.directory}/generated-test-sources</generated.testsources.dir>
- <generated.sources.lite.dir>${project.build.directory}/generated-sources-lite</generated.sources.lite.dir>
- <generated.testsources.lite.dir>${project.build.directory}/generated-test-sources-lite</generated.testsources.lite.dir>
</properties>
<licenses>
@@ -208,7 +206,6 @@
<modules>
<module>core</module>
- <!-- <module>lite</module> -->
<module>util</module>
</modules>
diff --git a/java/util/pom.xml b/java/util/pom.xml
index 3de624fa..8ea4a40d 100644
--- a/java/util/pom.xml
+++ b/java/util/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-parent</artifactId>
- <version>3.5.1</version>
+ <version>3.6.0</version>
</parent>
<artifactId>protobuf-java-util</artifactId>
diff --git a/javanano/README.md b/javanano/README.md
deleted file mode 100644
index 6b13ecea..00000000
--- a/javanano/README.md
+++ /dev/null
@@ -1,401 +0,0 @@
-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 the Java Protocol Buffers Nano runtime library.
-
-**Nano is no longer supported by protobuf team. We recommend Android users to
-use protobuf lite runtime instead.**
-
-Installation - With Maven
--------------------------
-
-The Protocol Buffers build is managed using Maven. If you would
-rather build without Maven, see below.
-
-1) Install Apache Maven if you don't have it:
-
- http://maven.apache.org/
-
-2) Build the C++ code, or obtain a binary distribution of protoc. If
- you install a binary distribution, make sure that it is the same
- version as this package. If in doubt, run:
-
- $ protoc --version
-
- You will need to place the protoc executable in ../src. (If you
- built it yourself, it should already be there.)
-
-3) Run the tests:
-
- $ mvn test
-
- If some tests fail, this library may not work correctly on your
- system. Continue at your own risk.
-
-4) Install the library into your Maven repository:
-
- $ mvn install
-
-5) If you do not use Maven to manage your own build, you can build a
- .jar file to use:
-
- $ mvn package
-
- The .jar will be placed in the "target" directory.
-
-Installation - Without Maven
-----------------------------
-
-If you would rather not install Maven to build the library, you may
-follow these instructions instead. Note that these instructions skip
-running unit tests.
-
-1) Build the C++ code, or obtain a binary distribution of protoc. If
- you install a binary distribution, make sure that it is the same
- version as this package. If in doubt, run:
-
- $ protoc --version
-
- If you built the C++ code without installing, the compiler binary
- should be located in ../src.
-
-2) Invoke protoc to build DescriptorProtos.java:
-
- $ protoc --java_out=src/main/java -I../src \
- ../src/google/protobuf/descriptor.proto
-
-3) Compile the code in src/main/java using whatever means you prefer.
-
-4) Install the classes wherever you prefer.
-
-Nano version
-------------
-
-JavaNano is a special code generator and runtime library designed specially for
-resource-restricted systems, like Android. It is very resource-friendly in both
-the amount of code and the runtime overhead. Here is an overview of JavaNano
-features compared with the official Java protobuf:
-
-- No descriptors or message builders.
-- All messages are mutable; fields are public Java fields.
-- For optional fields only, encapsulation behind setter/getter/hazzer/
- clearer functions is opt-in, which provide proper 'has' state support.
-- For proto2, if not opted in, has state (field presence) is not available.
- Serialization outputs all fields not equal to their defaults
- (see important implications below).
- The behavior is consistent with proto3 semantics.
-- Required fields (proto2 only) are always serialized.
-- Enum constants are integers; protection against invalid values only
- when parsing from the wire.
-- Enum constants can be generated into container interfaces bearing
- the enum's name (so the referencing code is in Java style).
-- CodedInputByteBufferNano can only take byte[] (not InputStream).
-- Similarly CodedOutputByteBufferNano can only write to byte[].
-- Repeated fields are in arrays, not ArrayList or Vector. Null array
- elements are allowed and silently ignored.
-- Full support for serializing/deserializing repeated packed fields.
-- Support extensions (in proto2).
-- Unset messages/groups are null, not an immutable empty default
- instance.
-- toByteArray(...) and mergeFrom(...) are now static functions of
- MessageNano.
-- The 'bytes' type translates to the Java type byte[].
-
-The generated messages are not thread-safe for writes, but may be
-used simultaneously from multiple threads in a read-only manner.
-In other words, an appropriate synchronization mechanism (such as
-a ReadWriteLock) must be used to ensure that a message, its
-ancestors, and descendants are not accessed by any other threads
-while the message is being modified. Field reads, getter methods
-(but not getExtension(...)), toByteArray(...), writeTo(...),
-getCachedSize(), and getSerializedSize() are all considered read-only
-operations.
-
-IMPORTANT: If you have fields with defaults and opt out of accessors
-
-How fields with defaults are serialized has changed. Because we don't
-keep "has" state, any field equal to its default is assumed to be not
-set and therefore is not serialized. Consider the situation where we
-change the default value of a field. Senders compiled against an older
-version of the proto continue to match against the old default, and
-don't send values to the receiver even though the receiver assumes the
-new default value. Therefore, think carefully about the implications
-of changing the default value. Alternatively, turn on accessors and
-enjoy the benefit of the explicit has() checks.
-
-IMPORTANT: If you have "bytes" fields with non-empty defaults
-
-Because the byte buffer is now of mutable type byte[], the default
-static final cannot be exposed through a public field. Each time a
-message's constructor or clear() function is called, the default value
-(kept in a private byte[]) is cloned. This causes a small memory
-penalty. This is not a problem if the field has no default or is an
-empty default.
-
-Nano Generator options
-----------------------
-
-```
-java_package -> <file-name>|<package-name>
-java_outer_classname -> <file-name>|<package-name>
-java_multiple_files -> true or false
-java_nano_generate_has -> true or false [DEPRECATED]
-optional_field_style -> default or accessors
-enum_style -> c or java
-ignore_services -> true or false
-parcelable_messages -> true or false
-generate_intdefs -> true or false
-```
-
-**java_package=\<file-name\>|\<package-name\>** (no default)
-
- This allows overriding the 'java_package' option value
- for the given file from the command line. Use multiple
- java_package options to override the option for multiple
- files. The final Java package for each file is the value
- of this command line option if present, or the value of
- the same option defined in the file if present, or the
- proto package if present, or the default Java package.
-
-**java_outer_classname=\<file-name\>|\<outer-classname\>** (no default)
-
- This allows overriding the 'java_outer_classname' option
- for the given file from the command line. Use multiple
- java_outer_classname options to override the option for
- multiple files. The final Java outer class name for each
- file is the value of this command line option if present,
- or the value of the same option defined in the file if
- present, or the file name converted to CamelCase. This
- outer class will nest all classes and integer constants
- generated from file-scope messages and enums.
-
-**java_multiple_files={true,false}** (no default)
-
- This allows overriding the 'java_multiple_files' option
- in all source files and their imported files from the
- command line. The final value of this option for each
- file is the value defined in this command line option, or
- the value of the same option defined in the file if
- present, or false. This specifies whether to generate
- package-level classes for the file-scope messages in the
- same Java package as the outer class (instead of nested
- classes in the outer class). File-scope enum constants
- are still generated as integer constants in the outer
- class. This affects the fully qualified references in the
- Java code. NOTE: because the command line option
- overrides the value for all files and their imported
- files, using this option inconsistently may result in
- incorrect references to the imported messages and enum
- constants.
-
-**java_nano_generate_has={true,false}** (default: false)
-
- DEPRECATED. Use optional_field_style=accessors.
-
- If true, generates a public boolean variable has\<fieldname\>
- accompanying each optional or required field (not present for
- repeated fields, groups or messages). It is set to false initially
- and upon clear(). If parseFrom(...) reads the field from the wire,
- it is set to true. This is a way for clients to inspect the "has"
- value upon parse. If it is set to true, writeTo(...) will ALWAYS
- output that field (even if field value is equal to its
- default).
-
- IMPORTANT: This option costs an extra 4 bytes per primitive field in
- the message. Think carefully about whether you really need this. In
- many cases reading the default works and determining whether the
- field was received over the wire is irrelevant.
-
-**optional_field_style={default,accessors,reftypes}** (default: default)
-
- Defines the style of the generated code for fields.
-
- * default
-
- In the default style, optional fields translate into public mutable
- Java fields, and the serialization process is as discussed in the
- "IMPORTANT" section above.
-
- * accessors
-
- When set to 'accessors', each optional field is encapsulated behind
- 4 accessors, namely get\<fieldname\>(), set\<fieldname\>(), has\<fieldname\>()
- and clear\<fieldname\>() methods, with the standard semantics. The hazzer's
- return value determines whether a field is serialized, so this style is
- useful when you need to serialize a field with the default value, or check
- if a field has been explicitly set to its default value from the wire.
-
- In the 'accessors' style, required and nested message fields are still
- translated to one public mutable Java field each, repeated fields are still
- translated to arrays. No accessors are generated for them.
-
- IMPORTANT: When using the 'accessors' style, ProGuard should always
- be enabled with optimization (don't use -dontoptimize) and allowing
- access modification (use -allowaccessmodification). This removes the
- unused accessors and maybe inline the rest at the call sites,
- reducing the final code size.
- TODO(maxtroy): find ProGuard config that would work the best.
-
- * reftypes
-
- When set to 'reftypes', each proto field is generated as a public Java
- field. For primitive types, these fields use the Java reference types
- such as java.lang.Integer instead of primitive types such as int.
-
- In the 'reftypes' style, fields are initialized to null (or empty
- arrays for repeated fields), and their default values are not available.
- They are serialized over the wire based on equality to null.
-
- The 'reftypes' mode has some additional cost due to autoboxing and usage
- of reference types. In practice, many boxed types are cached, and so don't
- result in object creation. However, references do take slightly more memory
- than primitives.
-
- The 'reftypes' mode is useful when you want to be able to serialize fields
- with default values, or check if a field has been explicitly set to the
- default over the wire without paying the extra method cost of the
- 'accessors' mode.
-
- Note that if you attempt to write null to a required field in the reftypes
- mode, serialization of the proto will cause a NullPointerException. This is
- an intentional indicator that you must set required fields.
-
- NOTE
- optional_field_style=accessors or reftypes cannot be used together with
- java_nano_generate_has=true. If you need the 'has' flag for any
- required field (you have no reason to), you can only use
- java_nano_generate_has=true.
-
-**enum_style={c,java}** (default: c)
-
- Defines where to put the int constants generated from enum members.
-
- * c
-
- Use C-style, so the enum constants are available at the scope where
- the enum is defined. A file-scope enum's members are referenced like
- 'FileOuterClass.ENUM_VALUE'; a message-scope enum's members are
- referenced as 'Message.ENUM_VALUE'. The enum name is unavailable.
- This complies with the Micro code generator's behavior.
-
- * java
-
- Use Java-style, so the enum constants are available under the enum
- name and referenced like 'EnumName.ENUM_VALUE' (they are still int
- constants). The enum name becomes the name of a public interface, at
- the scope where the enum is defined. If the enum is file-scope and
- the java_multiple_files option is on, the interface will be defined
- in its own file. To reduce code size, this interface should not be
- implemented and ProGuard shrinking should be used, so after the Java
- compiler inlines all referenced enum constants into the call sites,
- the interface remains unused and can be removed by ProGuard.
-
-**ignore_services={true,false}** (default: false)
-
- Skips services definitions.
-
- Nano doesn't support services. By default, if a service is defined
- it will generate a compilation error. If this flag is set to true,
- services will be silently ignored, instead.
-
-**parcelable_messages={true,false}** (default: false)
-
- Android-specific option to generate Parcelable messages.
-
-**generate_intdefs={true,false}** (default: false)
- Android-specific option to generate @IntDef annotations for enums.
-
- If turned on, an '@IntDef' annotation (a public @interface) will be
- generated for each enum, and every integer parameter and return
- value in the generated code meant for this enum will be annotated
- with it. This interface is generated with the same name and at the
- same place as the enum members' container interfaces described
- above under 'enum_style=java', regardless of the enum_style option
- used. When this is combined with enum_style=java, the interface
- will be both the '@IntDef' annotation and the container of the enum
- members; otherwise the interface has an empty body.
-
- Your app must declare a compile-time dependency on the
- android-support-annotations library.
-
- For more information on how these @IntDef annotations help with
- compile-time type safety, see:
- https://sites.google.com/a/android.com/tools/tech-docs/support-annotations
- and
- https://developer.android.com/reference/android/support/annotation/IntDef.html
-
-
-To use nano protobufs within the Android repo:
-----------------------------------------------
-
-- Set 'LOCAL_PROTOC_OPTIMIZE_TYPE := nano' in your local .mk file.
- When building a Java library or an app (package) target, the build
- system will add the Java nano runtime library to the
- LOCAL_STATIC_JAVA_LIBRARIES variable, so you don't need to.
-- Set 'LOCAL_PROTO_JAVA_OUTPUT_PARAMS := ...' in your local .mk file
- for any command-line options you need. Use commas to join multiple
- options. In the nano flavor only, whitespace surrounding the option
- names and values are ignored, so you can use backslash-newline or
- '+=' to structure your make files nicely.
-- The options will be applied to *all* proto files in LOCAL_SRC_FILES
- when you build a Java library or package. In case different options
- are needed for different proto files, build separate Java libraries
- and reference them in your main target. Note: you should make sure
- that, for each separate target, all proto files imported from any
- proto file in LOCAL_SRC_FILES are included in LOCAL_SRC_FILES. This
- is because the generator has to assume that the imported files are
- built using the same options, and will generate code that reference
- the fields and enums from the imported files using the same code
- style.
-- Hint: 'include $(CLEAR_VARS)' resets all LOCAL_ variables, including
- the two above.
-
-To use nano protobufs outside of Android repo:
-----------------------------------------------
-
-- Link with the generated jar file
- \<protobuf-root\>java/target/protobuf-java-2.3.0-nano.jar.
-- Invoke with --javanano_out, e.g.:
-```
-./protoc '--javanano_out=\
- java_package=src/proto/simple-data.proto|my_package,\
- java_outer_classname=src/proto/simple-data.proto|OuterName\
- :.' src/proto/simple-data.proto
-```
-
-Contributing to nano:
----------------------
-
-Please add/edit tests in NanoTest.java.
-
-Please run the following steps to test:
-
-- cd external/protobuf
-- ./configure
-- Run "make -j12 check" and verify all tests pass.
-- cd java
-- Run "mvn test" and verify all tests pass.
-- cd ../../..
-- . build/envsetup.sh
-- lunch 1
-- "make -j12 aprotoc libprotobuf-java-2.3.0-nano aprotoc-test-nano-params NanoAndroidTest" and
- check for build errors.
-- Plug in an Android device or start an emulator.
-- adb install -r out/target/product/generic/data/app/NanoAndroidTest.apk
-- Run:
- "adb shell am instrument -w com.google.protobuf.nano.test/android.test.InstrumentationTestRunner"
- and verify all tests pass.
-- repo sync -c -j256
-- "make -j12" and check for build errors
-
-Usage
------
-
-The complete documentation for Protocol Buffers is available via the
-web at:
-
- https://developers.google.com/protocol-buffers/
diff --git a/javanano/pom.xml b/javanano/pom.xml
deleted file mode 100644
index 0395e8f2..00000000
--- a/javanano/pom.xml
+++ /dev/null
@@ -1,244 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>com.google</groupId>
- <artifactId>google</artifactId>
- <version>1</version>
- </parent>
- <groupId>com.google.protobuf.nano</groupId>
- <artifactId>protobuf-javanano</artifactId>
- <version>3.2.0</version>
- <packaging>bundle</packaging>
- <name>Protocol Buffer JavaNano API</name>
- <description>
- Protocol Buffers are a way of encoding structured data in an efficient yet
- extensible format.
- </description>
- <inceptionYear>2008</inceptionYear>
- <url>https://developers.google.com/protocol-buffers/</url>
- <licenses>
- <license>
- <name>3-Clause BSD License</name>
- <url>https://opensource.org/licenses/BSD-3-Clause</url>
- <distribution>repo</distribution>
- </license>
- </licenses>
- <scm>
- <url>https://github.com/google/protobuf</url>
- <connection>
- scm:git:https://github.com/google/protobuf.git
- </connection>
- </scm>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- </properties>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.4</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.easymock</groupId>
- <artifactId>easymock</artifactId>
- <version>2.2</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.easymock</groupId>
- <artifactId>easymockclassextension</artifactId>
- <version>2.2.1</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <source>1.5</source>
- <target>1.5</target>
- </configuration>
- </plugin>
- <plugin>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <includes>
- <include>**/*Test.java</include>
- </includes>
- </configuration>
- </plugin>
- <plugin>
- <artifactId>maven-antrun-plugin</artifactId>
- <executions>
- <execution>
- <id>generate-test-sources</id>
- <phase>generate-test-sources</phase>
- <configuration>
- <tasks>
- <mkdir dir="target/generated-test-sources" />
- <exec executable="../src/protoc">
- <arg value="--javanano_out=generate_equals=true:target/generated-test-sources" />
- <arg value="--proto_path=src/test/java/com" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_nano.proto" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_simple_nano.proto" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_stringutf8_nano.proto" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_recursive_nano.proto" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_import_nano.proto" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_single_nano.proto" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_multiple_nano.proto" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_multiple_nameclash_nano.proto" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_enum_class_nano.proto" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_repeated_merge_nano.proto" />
- <arg value="src/test/java/com/google/protobuf/nano/map_test.proto" />
- </exec>
- <exec executable="../src/protoc">
- <arg value="--javanano_out=store_unknown_fields=true,generate_equals=true,generate_clone=true:target/generated-test-sources" />
- <arg value="--proto_path=src/test/java/com" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_extension_nano.proto" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_extension_singular_nano.proto" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_extension_repeated_nano.proto" />
- </exec>
- <exec executable="../src/protoc">
- <arg value="--javanano_out=store_unknown_fields=true,generate_clone=true:target/generated-test-sources" />
- <arg value="--proto_path=src/test/java/com" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_extension_packed_nano.proto" />
- </exec>
- <exec executable="../src/protoc">
- <arg value="--javanano_out=java_nano_generate_has=true,generate_equals=true,generate_clone=true:target/generated-test-sources" />
- <arg value="--proto_path=src/test/java/com" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_has_nano.proto" />
- </exec>
- <exec executable="../src/protoc">
- <arg value="--javanano_out=optional_field_style=accessors,generate_equals=true:target/generated-test-sources" />
- <arg value="--proto_path=src/test/java/com" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_accessors_nano.proto" />
- </exec>
- <exec executable="../src/protoc">
- <arg value="--javanano_out=enum_style=java:target/generated-test-sources" />
- <arg value="--proto_path=src/test/java/com" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_enum_class_nano.proto" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_enum_class_multiple_nano.proto" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_repeated_packables_nano.proto" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_enum_validity_nano.proto" />
- </exec>
- <exec executable="../src/protoc">
- <arg value="--javanano_out=
- optional_field_style=accessors,
- java_outer_classname=google/protobuf/nano/unittest_enum_validity_nano.proto|EnumValidityAccessors
- :target/generated-test-sources" />
- <arg value="--proto_path=src/test/java/com" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_enum_validity_nano.proto" />
- </exec>
- <exec executable="../src/protoc">
- <arg value="--javanano_out=optional_field_style=reftypes,generate_equals=true:target/generated-test-sources" />
- <arg value="--proto_path=src/test/java/com" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_reference_types_nano.proto" />
- </exec>
- <exec executable="../src/protoc">
- <arg value="--javanano_out=
- optional_field_style=reftypes_compat_mode,
- generate_equals=true,
- java_outer_classname=google/protobuf/nano/unittest_reference_types_nano.proto|NanoReferenceTypesCompat
- :target/generated-test-sources" />
- <arg value="--proto_path=src/test/java/com" />
- <arg value="src/test/java/com/google/protobuf/nano/unittest_reference_types_nano.proto" />
- </exec>
- </tasks>
- <testSourceRoot>target/generated-test-sources</testSourceRoot>
- </configuration>
- <goals>
- <goal>run</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Bundle-DocURL>https://developers.google.com/protocol-buffers/</Bundle-DocURL>
- <Bundle-SymbolicName>com.google.protobuf.nano</Bundle-SymbolicName>
- <Export-Package>com.google.protobuf.nano;version=3.0.0-alpha-7</Export-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
- <profiles>
- <profile>
- <id>release</id>
- <distributionManagement>
- <snapshotRepository>
- <id>sonatype-nexus-staging</id>
- <url>https://oss.sonatype.org/content/repositories/snapshots</url>
- </snapshotRepository>
- <repository>
- <id>sonatype-nexus-staging</id>
- <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
- </repository>
- </distributionManagement>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-source-plugin</artifactId>
- <version>2.2.1</version>
- <executions>
- <execution>
- <id>attach-sources</id>
- <goals>
- <goal>jar-no-fork</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <version>2.9.1</version>
- <executions>
- <execution>
- <id>attach-javadocs</id>
- <goals>
- <goal>jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-gpg-plugin</artifactId>
- <version>1.5</version>
- <executions>
- <execution>
- <id>sign-artifacts</id>
- <phase>verify</phase>
- <goals>
- <goal>sign</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.sonatype.plugins</groupId>
- <artifactId>nexus-staging-maven-plugin</artifactId>
- <version>1.6.3</version>
- <extensions>true</extensions>
- <configuration>
- <serverId>sonatype-nexus-staging</serverId>
- <nexusUrl>https://oss.sonatype.org/</nexusUrl>
- <autoReleaseAfterClose>false</autoReleaseAfterClose>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
-</project>
diff --git a/javanano/src/main/java/com/google/protobuf/nano/CodedInputByteBufferNano.java b/javanano/src/main/java/com/google/protobuf/nano/CodedInputByteBufferNano.java
deleted file mode 100644
index f3993155..00000000
--- a/javanano/src/main/java/com/google/protobuf/nano/CodedInputByteBufferNano.java
+++ /dev/null
@@ -1,683 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2013 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package com.google.protobuf.nano;
-
-import java.io.IOException;
-
-/**
- * Reads and decodes protocol message fields.
- *
- * This class contains two kinds of methods: methods that read specific
- * protocol message constructs and field types (e.g. {@link #readTag()} and
- * {@link #readInt32()}) and methods that read low-level values (e.g.
- * {@link #readRawVarint32()} and {@link #readRawBytes}). If you are reading
- * encoded protocol messages, you should use the former methods, but if you are
- * reading some other format of your own design, use the latter.
- *
- * @author kenton@google.com Kenton Varda
- */
-public final class CodedInputByteBufferNano {
- /**
- * Create a new CodedInputStream wrapping the given byte array.
- */
- public static CodedInputByteBufferNano newInstance(final byte[] buf) {
- return newInstance(buf, 0, buf.length);
- }
-
- /**
- * Create a new CodedInputStream wrapping the given byte array slice.
- */
- public static CodedInputByteBufferNano newInstance(final byte[] buf, final int off,
- final int len) {
- return new CodedInputByteBufferNano(buf, off, len);
- }
-
- // -----------------------------------------------------------------
-
- /**
- * Attempt to read a field tag, returning zero if we have reached EOF.
- * Protocol message parsers use this to read tags, since a protocol message
- * may legally end wherever a tag occurs, and zero is not a valid tag number.
- */
- public int readTag() throws IOException {
- if (isAtEnd()) {
- lastTag = 0;
- return 0;
- }
-
- lastTag = readRawVarint32();
- if (lastTag == 0) {
- // If we actually read zero, that's not a valid tag.
- throw InvalidProtocolBufferNanoException.invalidTag();
- }
- return lastTag;
- }
-
- /**
- * Verifies that the last call to readTag() returned the given tag value.
- * This is used to verify that a nested group ended with the correct
- * end tag.
- *
- * @throws InvalidProtocolBufferNanoException {@code value} does not match the
- * last tag.
- */
- public void checkLastTagWas(final int value)
- throws InvalidProtocolBufferNanoException {
- if (lastTag != value) {
- throw InvalidProtocolBufferNanoException.invalidEndTag();
- }
- }
-
- /**
- * Reads and discards a single field, given its tag value.
- *
- * @return {@code false} if the tag is an endgroup tag, in which case
- * nothing is skipped. Otherwise, returns {@code true}.
- */
- public boolean skipField(final int tag) throws IOException {
- switch (WireFormatNano.getTagWireType(tag)) {
- case WireFormatNano.WIRETYPE_VARINT:
- readInt32();
- return true;
- case WireFormatNano.WIRETYPE_FIXED64:
- readRawLittleEndian64();
- return true;
- case WireFormatNano.WIRETYPE_LENGTH_DELIMITED:
- skipRawBytes(readRawVarint32());
- return true;
- case WireFormatNano.WIRETYPE_START_GROUP:
- skipMessage();
- checkLastTagWas(
- WireFormatNano.makeTag(WireFormatNano.getTagFieldNumber(tag),
- WireFormatNano.WIRETYPE_END_GROUP));
- return true;
- case WireFormatNano.WIRETYPE_END_GROUP:
- return false;
- case WireFormatNano.WIRETYPE_FIXED32:
- readRawLittleEndian32();
- return true;
- default:
- throw InvalidProtocolBufferNanoException.invalidWireType();
- }
- }
-
- /**
- * Reads and discards an entire message. This will read either until EOF
- * or until an endgroup tag, whichever comes first.
- */
- public void skipMessage() throws IOException {
- while (true) {
- final int tag = readTag();
- if (tag == 0 || !skipField(tag)) {
- return;
- }
- }
- }
-
- // -----------------------------------------------------------------
-
- /** Read a {@code double} field value from the stream. */
- public double readDouble() throws IOException {
- return Double.longBitsToDouble(readRawLittleEndian64());
- }
-
- /** Read a {@code float} field value from the stream. */
- public float readFloat() throws IOException {
- return Float.intBitsToFloat(readRawLittleEndian32());
- }
-
- /** Read a {@code uint64} field value from the stream. */
- public long readUInt64() throws IOException {
- return readRawVarint64();
- }
-
- /** Read an {@code int64} field value from the stream. */
- public long readInt64() throws IOException {
- return readRawVarint64();
- }
-
- /** Read an {@code int32} field value from the stream. */
- public int readInt32() throws IOException {
- return readRawVarint32();
- }
-
- /** Read a {@code fixed64} field value from the stream. */
- public long readFixed64() throws IOException {
- return readRawLittleEndian64();
- }
-
- /** Read a {@code fixed32} field value from the stream. */
- public int readFixed32() throws IOException {
- return readRawLittleEndian32();
- }
-
- /** Read a {@code bool} field value from the stream. */
- public boolean readBool() throws IOException {
- return readRawVarint32() != 0;
- }
-
- /** Read a {@code string} field value from the stream. */
- public String readString() throws IOException {
- final int size = readRawVarint32();
- if (size <= (bufferSize - bufferPos) && size > 0) {
- // Fast path: We already have the bytes in a contiguous buffer, so
- // just copy directly from it.
- final String result = new String(buffer, bufferPos, size, InternalNano.UTF_8);
- bufferPos += size;
- return result;
- } else {
- // Slow path: Build a byte array first then copy it.
- return new String(readRawBytes(size), InternalNano.UTF_8);
- }
- }
-
- /** Read a {@code group} field value from the stream. */
- public void readGroup(final MessageNano msg, final int fieldNumber)
- throws IOException {
- if (recursionDepth >= recursionLimit) {
- throw InvalidProtocolBufferNanoException.recursionLimitExceeded();
- }
- ++recursionDepth;
- msg.mergeFrom(this);
- checkLastTagWas(
- WireFormatNano.makeTag(fieldNumber, WireFormatNano.WIRETYPE_END_GROUP));
- --recursionDepth;
- }
-
- public void readMessage(final MessageNano msg)
- throws IOException {
- final int length = readRawVarint32();
- if (recursionDepth >= recursionLimit) {
- throw InvalidProtocolBufferNanoException.recursionLimitExceeded();
- }
- final int oldLimit = pushLimit(length);
- ++recursionDepth;
- msg.mergeFrom(this);
- checkLastTagWas(0);
- --recursionDepth;
- popLimit(oldLimit);
- }
-
- /** Read a {@code bytes} field value from the stream. */
- public byte[] readBytes() throws IOException {
- final int size = readRawVarint32();
- if (size <= (bufferSize - bufferPos) && size > 0) {
- // Fast path: We already have the bytes in a contiguous buffer, so
- // just copy directly from it.
- final byte[] result = new byte[size];
- System.arraycopy(buffer, bufferPos, result, 0, size);
- bufferPos += size;
- return result;
- } else if (size == 0) {
- return WireFormatNano.EMPTY_BYTES;
- } else {
- // Slow path: Build a byte array first then copy it.
- return readRawBytes(size);
- }
- }
-
- /** Read a {@code uint32} field value from the stream. */
- public int readUInt32() throws IOException {
- return readRawVarint32();
- }
-
- /**
- * Read an enum field value from the stream. Caller is responsible
- * for converting the numeric value to an actual enum.
- */
- public int readEnum() throws IOException {
- return readRawVarint32();
- }
-
- /** Read an {@code sfixed32} field value from the stream. */
- public int readSFixed32() throws IOException {
- return readRawLittleEndian32();
- }
-
- /** Read an {@code sfixed64} field value from the stream. */
- public long readSFixed64() throws IOException {
- return readRawLittleEndian64();
- }
-
- /** Read an {@code sint32} field value from the stream. */
- public int readSInt32() throws IOException {
- return decodeZigZag32(readRawVarint32());
- }
-
- /** Read an {@code sint64} field value from the stream. */
- public long readSInt64() throws IOException {
- return decodeZigZag64(readRawVarint64());
- }
-
- // =================================================================
-
- /**
- * Read a raw Varint from the stream. If larger than 32 bits, discard the
- * upper bits.
- */
- public int readRawVarint32() throws IOException {
- byte tmp = readRawByte();
- if (tmp >= 0) {
- return tmp;
- }
- int result = tmp & 0x7f;
- if ((tmp = readRawByte()) >= 0) {
- result |= tmp << 7;
- } else {
- result |= (tmp & 0x7f) << 7;
- if ((tmp = readRawByte()) >= 0) {
- result |= tmp << 14;
- } else {
- result |= (tmp & 0x7f) << 14;
- if ((tmp = readRawByte()) >= 0) {
- result |= tmp << 21;
- } else {
- result |= (tmp & 0x7f) << 21;
- result |= (tmp = readRawByte()) << 28;
- if (tmp < 0) {
- // Discard upper 32 bits.
- for (int i = 0; i < 5; i++) {
- if (readRawByte() >= 0) {
- return result;
- }
- }
- throw InvalidProtocolBufferNanoException.malformedVarint();
- }
- }
- }
- }
- return result;
- }
-
- /** Read a raw Varint from the stream. */
- public long readRawVarint64() throws IOException {
- int shift = 0;
- long result = 0;
- while (shift < 64) {
- final byte b = readRawByte();
- result |= (long)(b & 0x7F) << shift;
- if ((b & 0x80) == 0) {
- return result;
- }
- shift += 7;
- }
- throw InvalidProtocolBufferNanoException.malformedVarint();
- }
-
- /** Read a 32-bit little-endian integer from the stream. */
- public int readRawLittleEndian32() throws IOException {
- final byte b1 = readRawByte();
- final byte b2 = readRawByte();
- final byte b3 = readRawByte();
- final byte b4 = readRawByte();
- return ((b1 & 0xff) ) |
- ((b2 & 0xff) << 8) |
- ((b3 & 0xff) << 16) |
- ((b4 & 0xff) << 24);
- }
-
- /** Read a 64-bit little-endian integer from the stream. */
- public long readRawLittleEndian64() throws IOException {
- final byte b1 = readRawByte();
- final byte b2 = readRawByte();
- final byte b3 = readRawByte();
- final byte b4 = readRawByte();
- final byte b5 = readRawByte();
- final byte b6 = readRawByte();
- final byte b7 = readRawByte();
- final byte b8 = readRawByte();
- return (((long)b1 & 0xff) ) |
- (((long)b2 & 0xff) << 8) |
- (((long)b3 & 0xff) << 16) |
- (((long)b4 & 0xff) << 24) |
- (((long)b5 & 0xff) << 32) |
- (((long)b6 & 0xff) << 40) |
- (((long)b7 & 0xff) << 48) |
- (((long)b8 & 0xff) << 56);
- }
-
- /**
- * Decode 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 An unsigned 32-bit integer, stored in a signed int because
- * Java has no explicit unsigned support.
- * @return A signed 32-bit integer.
- */
- public static int decodeZigZag32(final int n) {
- return (n >>> 1) ^ -(n & 1);
- }
-
- /**
- * Decode 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 An unsigned 64-bit integer, stored in a signed int because
- * Java has no explicit unsigned support.
- * @return A signed 64-bit integer.
- */
- public static long decodeZigZag64(final long n) {
- return (n >>> 1) ^ -(n & 1);
- }
-
- // -----------------------------------------------------------------
-
- private final byte[] buffer;
- private int bufferStart;
- private int bufferSize;
- private int bufferSizeAfterLimit;
- private int bufferPos;
- private int lastTag;
-
- /** The absolute position of the end of the current message. */
- private int currentLimit = Integer.MAX_VALUE;
-
- /** See setRecursionLimit() */
- private int recursionDepth;
- private int recursionLimit = DEFAULT_RECURSION_LIMIT;
-
- /** See setSizeLimit() */
- private int sizeLimit = DEFAULT_SIZE_LIMIT;
-
- private static final int DEFAULT_RECURSION_LIMIT = 64;
- private static final int DEFAULT_SIZE_LIMIT = 64 << 20; // 64MB
-
- private CodedInputByteBufferNano(final byte[] buffer, final int off, final int len) {
- this.buffer = buffer;
- bufferStart = off;
- bufferSize = off + len;
- bufferPos = off;
- }
-
- /**
- * Set the maximum message recursion depth. In order to prevent malicious
- * messages from causing stack overflows, {@code CodedInputStream} limits
- * how deeply messages may be nested. The default limit is 64.
- *
- * @return the old limit.
- */
- public int setRecursionLimit(final int limit) {
- if (limit < 0) {
- throw new IllegalArgumentException(
- "Recursion limit cannot be negative: " + limit);
- }
- final int oldLimit = recursionLimit;
- recursionLimit = limit;
- return oldLimit;
- }
-
- /**
- * Set the maximum message size. In order to prevent malicious
- * messages from exhausting memory or causing integer overflows,
- * {@code CodedInputStream} limits how large a message may be.
- * The default limit is 64MB. You should set this limit as small
- * as you can without harming your app's functionality. Note that
- * size limits only apply when reading from an {@code InputStream}, not
- * when constructed around a raw byte array.
- * <p>
- * If you want to read several messages from a single CodedInputStream, you
- * could call {@link #resetSizeCounter()} after each one to avoid hitting the
- * size limit.
- *
- * @return the old limit.
- */
- public int setSizeLimit(final int limit) {
- if (limit < 0) {
- throw new IllegalArgumentException(
- "Size limit cannot be negative: " + limit);
- }
- final int oldLimit = sizeLimit;
- sizeLimit = limit;
- return oldLimit;
- }
-
- /**
- * Resets the current size counter to zero (see {@link #setSizeLimit(int)}).
- */
- public void resetSizeCounter() {
- }
-
- /**
- * Sets {@code currentLimit} to (current position) + {@code byteLimit}. This
- * is called when descending into a length-delimited embedded message.
- *
- * @return the old limit.
- */
- public int pushLimit(int byteLimit) throws InvalidProtocolBufferNanoException {
- if (byteLimit < 0) {
- throw InvalidProtocolBufferNanoException.negativeSize();
- }
- byteLimit += bufferPos;
- final int oldLimit = currentLimit;
- if (byteLimit > oldLimit) {
- throw InvalidProtocolBufferNanoException.truncatedMessage();
- }
- currentLimit = byteLimit;
-
- recomputeBufferSizeAfterLimit();
-
- return oldLimit;
- }
-
- private void recomputeBufferSizeAfterLimit() {
- bufferSize += bufferSizeAfterLimit;
- final int bufferEnd = bufferSize;
- if (bufferEnd > currentLimit) {
- // Limit is in current buffer.
- bufferSizeAfterLimit = bufferEnd - currentLimit;
- bufferSize -= bufferSizeAfterLimit;
- } else {
- bufferSizeAfterLimit = 0;
- }
- }
-
- /**
- * Discards the current limit, returning to the previous limit.
- *
- * @param oldLimit The old limit, as returned by {@code pushLimit}.
- */
- public void popLimit(final int oldLimit) {
- currentLimit = oldLimit;
- recomputeBufferSizeAfterLimit();
- }
-
- /**
- * Returns the number of bytes to be read before the current limit.
- * If no limit is set, returns -1.
- */
- public int getBytesUntilLimit() {
- if (currentLimit == Integer.MAX_VALUE) {
- return -1;
- }
-
- final int currentAbsolutePosition = bufferPos;
- return currentLimit - currentAbsolutePosition;
- }
-
- /**
- * Returns true if the stream has reached the end of the input. This is the
- * case if either the end of the underlying input source has been reached or
- * if the stream has reached a limit created using {@link #pushLimit(int)}.
- */
- public boolean isAtEnd() {
- return bufferPos == bufferSize;
- }
-
- /**
- * Get current position in buffer relative to beginning offset.
- */
- public int getPosition() {
- return bufferPos - bufferStart;
- }
-
- /**
- * Retrieves a subset of data in the buffer. The returned array is not backed by the original
- * buffer array.
- *
- * @param offset the position (relative to the buffer start position) to start at.
- * @param length the number of bytes to retrieve.
- */
- public byte[] getData(int offset, int length) {
- if (length == 0) {
- return WireFormatNano.EMPTY_BYTES;
- }
- byte[] copy = new byte[length];
- int start = bufferStart + offset;
- System.arraycopy(buffer, start, copy, 0, length);
- return copy;
- }
-
- /**
- * Rewind to previous position. Cannot go forward.
- */
- public void rewindToPosition(int position) {
- if (position > bufferPos - bufferStart) {
- throw new IllegalArgumentException(
- "Position " + position + " is beyond current " + (bufferPos - bufferStart));
- }
- if (position < 0) {
- throw new IllegalArgumentException("Bad position " + position);
- }
- bufferPos = bufferStart + position;
- }
-
- /**
- * Read one byte from the input.
- *
- * @throws InvalidProtocolBufferNanoException The end of the stream or the current
- * limit was reached.
- */
- public byte readRawByte() throws IOException {
- if (bufferPos == bufferSize) {
- throw InvalidProtocolBufferNanoException.truncatedMessage();
- }
- return buffer[bufferPos++];
- }
-
- /**
- * Read a fixed size of bytes from the input.
- *
- * @throws InvalidProtocolBufferNanoException The end of the stream or the current
- * limit was reached.
- */
- public byte[] readRawBytes(final int size) throws IOException {
- if (size < 0) {
- throw InvalidProtocolBufferNanoException.negativeSize();
- }
-
- if (bufferPos + size > currentLimit) {
- // Read to the end of the stream anyway.
- skipRawBytes(currentLimit - bufferPos);
- // Then fail.
- throw InvalidProtocolBufferNanoException.truncatedMessage();
- }
-
- if (size <= bufferSize - bufferPos) {
- // We have all the bytes we need already.
- final byte[] bytes = new byte[size];
- System.arraycopy(buffer, bufferPos, bytes, 0, size);
- bufferPos += size;
- return bytes;
- } else {
- throw InvalidProtocolBufferNanoException.truncatedMessage();
- }
- }
-
- /**
- * Reads and discards {@code size} bytes.
- *
- * @throws InvalidProtocolBufferNanoException The end of the stream or the current
- * limit was reached.
- */
- public void skipRawBytes(final int size) throws IOException {
- if (size < 0) {
- throw InvalidProtocolBufferNanoException.negativeSize();
- }
-
- if (bufferPos + size > currentLimit) {
- // Read to the end of the stream anyway.
- skipRawBytes(currentLimit - bufferPos);
- // Then fail.
- throw InvalidProtocolBufferNanoException.truncatedMessage();
- }
-
- if (size <= bufferSize - bufferPos) {
- // We have all the bytes we need already.
- bufferPos += size;
- } else {
- throw InvalidProtocolBufferNanoException.truncatedMessage();
- }
- }
-
- // Read a primitive type.
- Object readPrimitiveField(int type) throws IOException {
- switch (type) {
- case InternalNano.TYPE_DOUBLE:
- return readDouble();
- case InternalNano.TYPE_FLOAT:
- return readFloat();
- case InternalNano.TYPE_INT64:
- return readInt64();
- case InternalNano.TYPE_UINT64:
- return readUInt64();
- case InternalNano.TYPE_INT32:
- return readInt32();
- case InternalNano.TYPE_FIXED64:
- return readFixed64();
- case InternalNano.TYPE_FIXED32:
- return readFixed32();
- case InternalNano.TYPE_BOOL:
- return readBool();
- case InternalNano.TYPE_STRING:
- return readString();
- case InternalNano.TYPE_BYTES:
- return readBytes();
- case InternalNano.TYPE_UINT32:
- return readUInt32();
- case InternalNano.TYPE_ENUM:
- return readEnum();
- case InternalNano.TYPE_SFIXED32:
- return readSFixed32();
- case InternalNano.TYPE_SFIXED64:
- return readSFixed64();
- case InternalNano.TYPE_SINT32:
- return readSInt32();
- case InternalNano.TYPE_SINT64:
- return readSInt64();
- default:
- throw new IllegalArgumentException("Unknown type " + type);
- }
- }
-}
diff --git a/javanano/src/main/java/com/google/protobuf/nano/CodedOutputByteBufferNano.java b/javanano/src/main/java/com/google/protobuf/nano/CodedOutputByteBufferNano.java
deleted file mode 100644
index 322ada8e..00000000
--- a/javanano/src/main/java/com/google/protobuf/nano/CodedOutputByteBufferNano.java
+++ /dev/null
@@ -1,1214 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2013 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package com.google.protobuf.nano;
-
-import java.io.IOException;
-import java.nio.BufferOverflowException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.ReadOnlyBufferException;
-
-/**
- * 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 is totally unsynchronized.
- *
- * @author kneton@google.com Kenton Varda
- */
-public final class CodedOutputByteBufferNano {
- /* max bytes per java UTF-16 char in UTF-8 */
- private static final int MAX_UTF8_EXPANSION = 3;
- private final ByteBuffer buffer;
-
- private CodedOutputByteBufferNano(final byte[] buffer, final int offset,
- final int length) {
- this(ByteBuffer.wrap(buffer, offset, length));
- }
-
- private CodedOutputByteBufferNano(final ByteBuffer buffer) {
- this.buffer = buffer;
- this.buffer.order(ByteOrder.LITTLE_ENDIAN);
- }
-
- /**
- * 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}.
- */
- public static CodedOutputByteBufferNano 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}.
- */
- public static CodedOutputByteBufferNano newInstance(final byte[] flatArray,
- final int offset,
- final int length) {
- return new CodedOutputByteBufferNano(flatArray, offset, length);
- }
-
- // -----------------------------------------------------------------
-
- /** Write a {@code double} field, including tag, to the stream. */
- public void writeDouble(final int fieldNumber, final double value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_FIXED64);
- writeDoubleNoTag(value);
- }
-
- /** Write a {@code float} field, including tag, to the stream. */
- public void writeFloat(final int fieldNumber, final float value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_FIXED32);
- writeFloatNoTag(value);
- }
-
- /** Write a {@code uint64} field, including tag, to the stream. */
- public void writeUInt64(final int fieldNumber, final long value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT);
- writeUInt64NoTag(value);
- }
-
- /** Write an {@code int64} field, including tag, to the stream. */
- public void writeInt64(final int fieldNumber, final long value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT);
- writeInt64NoTag(value);
- }
-
- /** Write an {@code int32} field, including tag, to the stream. */
- public void writeInt32(final int fieldNumber, final int value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT);
- writeInt32NoTag(value);
- }
-
- /** Write a {@code fixed64} field, including tag, to the stream. */
- public void writeFixed64(final int fieldNumber, final long value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_FIXED64);
- writeFixed64NoTag(value);
- }
-
- /** Write a {@code fixed32} field, including tag, to the stream. */
- public void writeFixed32(final int fieldNumber, final int value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_FIXED32);
- writeFixed32NoTag(value);
- }
-
- /** Write a {@code bool} field, including tag, to the stream. */
- public void writeBool(final int fieldNumber, final boolean value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT);
- writeBoolNoTag(value);
- }
-
- /** Write a {@code string} field, including tag, to the stream. */
- public void writeString(final int fieldNumber, final String value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_LENGTH_DELIMITED);
- writeStringNoTag(value);
- }
-
- /** Write a {@code group} field, including tag, to the stream. */
- public void writeGroup(final int fieldNumber, final MessageNano value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_START_GROUP);
- writeGroupNoTag(value);
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_END_GROUP);
- }
-
- /** Write an embedded message field, including tag, to the stream. */
- public void writeMessage(final int fieldNumber, final MessageNano value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_LENGTH_DELIMITED);
- writeMessageNoTag(value);
- }
-
- /** Write a {@code bytes} field, including tag, to the stream. */
- public void writeBytes(final int fieldNumber, final byte[] value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_LENGTH_DELIMITED);
- writeBytesNoTag(value);
- }
-
- /** Write a {@code uint32} field, including tag, to the stream. */
- public void writeUInt32(final int fieldNumber, final int value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT);
- writeUInt32NoTag(value);
- }
-
- /**
- * Write an enum field, including tag, to the stream. Caller is responsible
- * for converting the enum value to its numeric value.
- */
- public void writeEnum(final int fieldNumber, final int value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT);
- writeEnumNoTag(value);
- }
-
- /** Write an {@code sfixed32} field, including tag, to the stream. */
- public void writeSFixed32(final int fieldNumber, final int value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_FIXED32);
- writeSFixed32NoTag(value);
- }
-
- /** Write an {@code sfixed64} field, including tag, to the stream. */
- public void writeSFixed64(final int fieldNumber, final long value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_FIXED64);
- writeSFixed64NoTag(value);
- }
-
- /** Write an {@code sint32} field, including tag, to the stream. */
- public void writeSInt32(final int fieldNumber, final int value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT);
- writeSInt32NoTag(value);
- }
-
- /** Write an {@code sint64} field, including tag, to the stream. */
- public void writeSInt64(final int fieldNumber, final long value)
- throws IOException {
- writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT);
- writeSInt64NoTag(value);
- }
-
- /**
- * Write a MessageSet extension field to the stream. For historical reasons,
- * the wire format differs from normal fields.
- */
-// public void writeMessageSetExtension(final int fieldNumber,
-// final MessageMicro value)
-// throws IOException {
-// writeTag(WireFormatMicro.MESSAGE_SET_ITEM, WireFormatMicro.WIRETYPE_START_GROUP);
-// writeUInt32(WireFormatMicro.MESSAGE_SET_TYPE_ID, fieldNumber);
-// writeMessage(WireFormatMicro.MESSAGE_SET_MESSAGE, value);
-// writeTag(WireFormatMicro.MESSAGE_SET_ITEM, WireFormatMicro.WIRETYPE_END_GROUP);
-// }
-
- /**
- * Write an unparsed MessageSet extension field to the stream. For
- * historical reasons, the wire format differs from normal fields.
- */
-// public void writeRawMessageSetExtension(final int fieldNumber,
-// final ByteStringMicro value)
-// throws IOException {
-// writeTag(WireFormatMicro.MESSAGE_SET_ITEM, WireFormatMicro.WIRETYPE_START_GROUP);
-// writeUInt32(WireFormatMicro.MESSAGE_SET_TYPE_ID, fieldNumber);
-// writeBytes(WireFormatMicro.MESSAGE_SET_MESSAGE, value);
-// writeTag(WireFormatMicro.MESSAGE_SET_ITEM, WireFormatMicro.WIRETYPE_END_GROUP);
-// }
-
- // -----------------------------------------------------------------
-
- /** Write a {@code double} field to the stream. */
- public void writeDoubleNoTag(final double value) throws IOException {
- writeRawLittleEndian64(Double.doubleToLongBits(value));
- }
-
- /** Write a {@code float} field to the stream. */
- public void writeFloatNoTag(final float value) throws IOException {
- writeRawLittleEndian32(Float.floatToIntBits(value));
- }
-
- /** Write a {@code uint64} field to the stream. */
- public void writeUInt64NoTag(final long value) throws IOException {
- writeRawVarint64(value);
- }
-
- /** Write an {@code int64} field to the stream. */
- public void writeInt64NoTag(final long value) throws IOException {
- writeRawVarint64(value);
- }
-
- /** Write an {@code int32} field to the stream. */
- public void writeInt32NoTag(final int value) throws IOException {
- if (value >= 0) {
- writeRawVarint32(value);
- } else {
- // Must sign-extend.
- writeRawVarint64(value);
- }
- }
-
- /** Write a {@code fixed64} field to the stream. */
- public void writeFixed64NoTag(final long value) throws IOException {
- writeRawLittleEndian64(value);
- }
-
- /** Write a {@code fixed32} field to the stream. */
- public void writeFixed32NoTag(final int value) throws IOException {
- writeRawLittleEndian32(value);
- }
-
- /** Write a {@code bool} field to the stream. */
- public void writeBoolNoTag(final boolean value) throws IOException {
- writeRawByte(value ? 1 : 0);
- }
-
- /** Write a {@code string} field to the stream. */
- public void writeStringNoTag(final String value) throws IOException {
- // UTF-8 byte length of the string is at least its UTF-16 code unit length (value.length()),
- // and at most 3 times of it. Optimize for the case where we know this length results in a
- // constant varint length - saves measuring length of the string.
- try {
- final int minLengthVarIntSize = computeRawVarint32Size(value.length());
- final int maxLengthVarIntSize = computeRawVarint32Size(value.length() * MAX_UTF8_EXPANSION);
- if (minLengthVarIntSize == maxLengthVarIntSize) {
- int oldPosition = buffer.position();
- // Buffer.position, when passed a position that is past its limit, throws
- // IllegalArgumentException, and this class is documented to throw
- // OutOfSpaceException instead.
- if (buffer.remaining() < minLengthVarIntSize) {
- throw new OutOfSpaceException(oldPosition + minLengthVarIntSize, buffer.limit());
- }
- buffer.position(oldPosition + minLengthVarIntSize);
- encode(value, buffer);
- int newPosition = buffer.position();
- buffer.position(oldPosition);
- writeRawVarint32(newPosition - oldPosition - minLengthVarIntSize);
- buffer.position(newPosition);
- } else {
- writeRawVarint32(encodedLength(value));
- encode(value, buffer);
- }
- } catch (BufferOverflowException e) {
- final OutOfSpaceException outOfSpaceException = new OutOfSpaceException(buffer.position(),
- buffer.limit());
- outOfSpaceException.initCause(e);
- throw outOfSpaceException;
- }
- }
-
- // These UTF-8 handling methods are copied from Guava's Utf8 class.
- /**
- * 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)
- */
- private static int encodedLength(CharSequence sequence) {
- // Warning to maintainers: this implementation is highly optimized.
- int utf16Length = sequence.length();
- int utf8Length = utf16Length;
- int i = 0;
-
- // This loop optimizes for pure ASCII.
- while (i < utf16Length && sequence.charAt(i) < 0x80) {
- i++;
- }
-
- // This loop optimizes for chars less than 0x800.
- for (; i < utf16Length; i++) {
- char c = sequence.charAt(i);
- if (c < 0x800) {
- utf8Length += ((0x7f - c) >>> 31); // branch free!
- } else {
- utf8Length += encodedLengthGeneral(sequence, i);
- break;
- }
- }
-
- 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)));
- }
- return utf8Length;
- }
-
- private static int encodedLengthGeneral(CharSequence sequence, int start) {
- int utf16Length = sequence.length();
- int utf8Length = 0;
- for (int i = start; i < utf16Length; i++) {
- char c = sequence.charAt(i);
- if (c < 0x800) {
- utf8Length += (0x7f - c) >>> 31; // branch free!
- } else {
- utf8Length += 2;
- // jdk7+: if (Character.isSurrogate(c)) {
- if (Character.MIN_SURROGATE <= c && c <= Character.MAX_SURROGATE) {
- // Check that we have a well-formed surrogate pair.
- int cp = Character.codePointAt(sequence, i);
- if (cp < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
- throw new IllegalArgumentException("Unpaired surrogate at index " + i);
- }
- i++;
- }
- }
- }
- return utf8Length;
- }
-
- /**
- * Encodes {@code sequence} into UTF-8, in {@code byteBuffer}. For a string, this method is
- * equivalent to {@code buffer.put(string.getBytes(UTF_8))}, but is more efficient in both time
- * and space. Bytes are written starting at the current position. 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 3 * sequence.length()}, which is the
- * largest possible number of bytes that any input can be encoded to.
- *
- * @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired
- * surrogates)
- * @throws BufferOverflowException if {@code sequence} encoded in UTF-8 does not fit in
- * {@code byteBuffer}'s remaining space.
- * @throws ReadOnlyBufferException if {@code byteBuffer} is a read-only buffer.
- */
- private static void encode(CharSequence sequence, ByteBuffer byteBuffer) {
- if (byteBuffer.isReadOnly()) {
- throw new ReadOnlyBufferException();
- } else if (byteBuffer.hasArray()) {
- try {
- int encoded = encode(sequence,
- byteBuffer.array(),
- byteBuffer.arrayOffset() + byteBuffer.position(),
- byteBuffer.remaining());
- byteBuffer.position(encoded - byteBuffer.arrayOffset());
- } catch (ArrayIndexOutOfBoundsException e) {
- BufferOverflowException boe = new BufferOverflowException();
- boe.initCause(e);
- throw boe;
- }
- } else {
- encodeDirect(sequence, byteBuffer);
- }
- }
-
- private static void encodeDirect(CharSequence sequence, ByteBuffer byteBuffer) {
- int utf16Length = sequence.length();
- for (int i = 0; i < utf16Length; i++) {
- final char c = sequence.charAt(i);
- if (c < 0x80) { // ASCII
- byteBuffer.put((byte) c);
- } else if (c < 0x800) { // 11 bits, two UTF-8 bytes
- byteBuffer.put((byte) ((0xF << 6) | (c >>> 6)));
- byteBuffer.put((byte) (0x80 | (0x3F & c)));
- } else if (c < Character.MIN_SURROGATE || Character.MAX_SURROGATE < c) {
- // Maximium single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes
- byteBuffer.put((byte) ((0xF << 5) | (c >>> 12)));
- byteBuffer.put((byte) (0x80 | (0x3F & (c >>> 6))));
- byteBuffer.put((byte) (0x80 | (0x3F & c)));
- } else {
- final char low;
- if (i + 1 == sequence.length()
- || !Character.isSurrogatePair(c, (low = sequence.charAt(++i)))) {
- throw new IllegalArgumentException("Unpaired surrogate at index " + (i - 1));
- }
- int codePoint = Character.toCodePoint(c, low);
- byteBuffer.put((byte) ((0xF << 4) | (codePoint >>> 18)));
- byteBuffer.put((byte) (0x80 | (0x3F & (codePoint >>> 12))));
- byteBuffer.put((byte) (0x80 | (0x3F & (codePoint >>> 6))));
- byteBuffer.put((byte) (0x80 | (0x3F & codePoint)));
- }
- }
- }
-
- private static int encode(CharSequence sequence, byte[] bytes, int offset, int length) {
- int utf16Length = sequence.length();
- int j = offset;
- int i = 0;
- int limit = offset + length;
- // Designed to take advantage of
- // https://wikis.oracle.com/display/HotSpotInternals/RangeCheckElimination
- for (char c; i < utf16Length && i + j < limit && (c = sequence.charAt(i)) < 0x80; i++) {
- bytes[j + i] = (byte) c;
- }
- if (i == utf16Length) {
- return j + utf16Length;
- }
- j += i;
- for (char c; i < utf16Length; i++) {
- c = sequence.charAt(i);
- if (c < 0x80 && j < limit) {
- bytes[j++] = (byte) c;
- } else if (c < 0x800 && j <= limit - 2) { // 11 bits, two UTF-8 bytes
- bytes[j++] = (byte) ((0xF << 6) | (c >>> 6));
- bytes[j++] = (byte) (0x80 | (0x3F & c));
- } else if ((c < Character.MIN_SURROGATE || Character.MAX_SURROGATE < c) && j <= limit - 3) {
- // Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes
- bytes[j++] = (byte) ((0xF << 5) | (c >>> 12));
- bytes[j++] = (byte) (0x80 | (0x3F & (c >>> 6)));
- bytes[j++] = (byte) (0x80 | (0x3F & c));
- } else if (j <= limit - 4) {
- // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8 bytes
- final char low;
- if (i + 1 == sequence.length()
- || !Character.isSurrogatePair(c, (low = sequence.charAt(++i)))) {
- throw new IllegalArgumentException("Unpaired surrogate at index " + (i - 1));
- }
- int codePoint = Character.toCodePoint(c, low);
- bytes[j++] = (byte) ((0xF << 4) | (codePoint >>> 18));
- bytes[j++] = (byte) (0x80 | (0x3F & (codePoint >>> 12)));
- bytes[j++] = (byte) (0x80 | (0x3F & (codePoint >>> 6)));
- bytes[j++] = (byte) (0x80 | (0x3F & codePoint));
- } else {
- throw new ArrayIndexOutOfBoundsException("Failed writing " + c + " at index " + j);
- }
- }
- return j;
- }
-
- // End guava UTF-8 methods
-
-
- /** Write a {@code group} field to the stream. */
- public void writeGroupNoTag(final MessageNano value) throws IOException {
- value.writeTo(this);
- }
-
- /** Write an embedded message field to the stream. */
- public void writeMessageNoTag(final MessageNano value) throws IOException {
- writeRawVarint32(value.getCachedSize());
- value.writeTo(this);
- }
-
- /** Write a {@code bytes} field to the stream. */
- public void writeBytesNoTag(final byte[] value) throws IOException {
- writeRawVarint32(value.length);
- writeRawBytes(value);
- }
-
- /** Write a {@code uint32} field to the stream. */
- public void writeUInt32NoTag(final int value) throws IOException {
- writeRawVarint32(value);
- }
-
- /**
- * Write an enum field to the stream. Caller is responsible
- * for converting the enum value to its numeric value.
- */
- public void writeEnumNoTag(final int value) throws IOException {
- writeRawVarint32(value);
- }
-
- /** Write an {@code sfixed32} field to the stream. */
- public void writeSFixed32NoTag(final int value) throws IOException {
- writeRawLittleEndian32(value);
- }
-
- /** Write an {@code sfixed64} field to the stream. */
- public void writeSFixed64NoTag(final long value) throws IOException {
- writeRawLittleEndian64(value);
- }
-
- /** Write an {@code sint32} field to the stream. */
- public void writeSInt32NoTag(final int value) throws IOException {
- writeRawVarint32(encodeZigZag32(value));
- }
-
- /** Write an {@code sint64} field to the stream. */
- public void writeSInt64NoTag(final long value) throws IOException {
- writeRawVarint64(encodeZigZag64(value));
- }
-
- // =================================================================
-
- /**
- * 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 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 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 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 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 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 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 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 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 group} field, including tag.
- */
- public static int computeGroupSize(final int fieldNumber,
- final MessageNano value) {
- return computeTagSize(fieldNumber) * 2 + computeGroupSizeNoTag(value);
- }
-
- /**
- * 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 MessageNano value) {
- return computeTagSize(fieldNumber) + computeMessageSizeNoTag(value);
- }
-
- /**
- * 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 byte[] value) {
- return computeTagSize(fieldNumber) + computeBytesSizeNoTag(value);
- }
-
- /**
- * 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
- * enum field, including tag. Caller is responsible for converting the
- * enum value to its numeric 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 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 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 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 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
- * MessageSet extension to the stream. For historical reasons,
- * the wire format differs from normal fields.
- */
-// public static int computeMessageSetExtensionSize(
-// final int fieldNumber, final MessageMicro value) {
-// return computeTagSize(WireFormatMicro.MESSAGE_SET_ITEM) * 2 +
-// computeUInt32Size(WireFormatMicro.MESSAGE_SET_TYPE_ID, fieldNumber) +
-// computeMessageSize(WireFormatMicro.MESSAGE_SET_MESSAGE, value);
-// }
-
- /**
- * Compute the number of bytes that would be needed to encode an
- * unparsed MessageSet extension field to the stream. For
- * historical reasons, the wire format differs from normal fields.
- */
-// public static int computeRawMessageSetExtensionSize(
-// final int fieldNumber, final ByteStringMicro value) {
-// return computeTagSize(WireFormatMicro.MESSAGE_SET_ITEM) * 2 +
-// computeUInt32Size(WireFormatMicro.MESSAGE_SET_TYPE_ID, fieldNumber) +
-// computeBytesSize(WireFormatMicro.MESSAGE_SET_MESSAGE, value);
-// }
-
- // -----------------------------------------------------------------
-
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code double} field, including tag.
- */
- public static int computeDoubleSizeNoTag(final double value) {
- return LITTLE_ENDIAN_64_SIZE;
- }
-
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code float} field, including tag.
- */
- public static int computeFloatSizeNoTag(final float value) {
- return LITTLE_ENDIAN_32_SIZE;
- }
-
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code uint64} field, including tag.
- */
- public static int computeUInt64SizeNoTag(final long value) {
- return computeRawVarint64Size(value);
- }
-
- /**
- * 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 computeRawVarint64Size(value);
- }
-
- /**
- * 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) {
- return computeRawVarint32Size(value);
- } else {
- // Must sign-extend.
- return 10;
- }
- }
-
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code fixed64} field.
- */
- public static int computeFixed64SizeNoTag(final long value) {
- return LITTLE_ENDIAN_64_SIZE;
- }
-
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code fixed32} field.
- */
- public static int computeFixed32SizeNoTag(final int value) {
- return LITTLE_ENDIAN_32_SIZE;
- }
-
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code bool} field.
- */
- public static int computeBoolSizeNoTag(final boolean value) {
- return 1;
- }
-
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code string} field.
- */
- public static int computeStringSizeNoTag(final String value) {
- final int length = encodedLength(value);
- return computeRawVarint32Size(length) + length;
- }
-
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code group} field.
- */
- public static int computeGroupSizeNoTag(final MessageNano value) {
- return value.getSerializedSize();
- }
-
- /**
- * Compute the number of bytes that would be needed to encode an embedded
- * message field.
- */
- public static int computeMessageSizeNoTag(final MessageNano value) {
- final int size = value.getSerializedSize();
- return computeRawVarint32Size(size) + size;
- }
-
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code bytes} field.
- */
- public static int computeBytesSizeNoTag(final byte[] value) {
- return computeRawVarint32Size(value.length) + value.length;
- }
-
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code uint32} field.
- */
- public static int computeUInt32SizeNoTag(final int value) {
- return computeRawVarint32Size(value);
- }
-
- /**
- * Compute the number of bytes that would be needed to encode an enum field.
- * Caller is responsible for converting the enum value to its numeric value.
- */
- public static int computeEnumSizeNoTag(final int value) {
- return computeRawVarint32Size(value);
- }
-
- /**
- * Compute the number of bytes that would be needed to encode an
- * {@code sfixed32} field.
- */
- public static int computeSFixed32SizeNoTag(final int value) {
- return LITTLE_ENDIAN_32_SIZE;
- }
-
- /**
- * Compute the number of bytes that would be needed to encode an
- * {@code sfixed64} field.
- */
- public static int computeSFixed64SizeNoTag(final long value) {
- return LITTLE_ENDIAN_64_SIZE;
- }
-
- /**
- * Compute the number of bytes that would be needed to encode an
- * {@code sint32} field.
- */
- public static int computeSInt32SizeNoTag(final int value) {
- return computeRawVarint32Size(encodeZigZag32(value));
- }
-
- /**
- * Compute the number of bytes that would be needed to encode an
- * {@code sint64} field.
- */
- public static int computeSInt64SizeNoTag(final long value) {
- return computeRawVarint64Size(encodeZigZag64(value));
- }
-
- // =================================================================
-
- /**
- * If writing to a flat array, return the space left in the array.
- * Otherwise, throws {@code UnsupportedOperationException}.
- */
- public int spaceLeft() {
- return buffer.remaining();
- }
-
- /**
- * 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 void checkNoSpaceLeft() {
- if (spaceLeft() != 0) {
- throw new IllegalStateException(
- "Did not write as much data as expected.");
- }
- }
-
- /**
- * Returns the position within the internal buffer.
- */
- public int position() {
- return buffer.position();
- }
-
- /**
- * Resets the position within the internal buffer to zero.
- *
- * @see #position
- * @see #spaceLeft
- */
- public void reset() {
- buffer.clear();
- }
-
- /**
- * 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;
-
- OutOfSpaceException(int position, int limit) {
- super("CodedOutputStream was writing to a flat byte array and ran " +
- "out of space (pos " + position + " limit " + limit + ").");
- }
- }
-
- /** Write a single byte. */
- public void writeRawByte(final byte value) throws IOException {
- if (!buffer.hasRemaining()) {
- // We're writing to a single buffer.
- throw new OutOfSpaceException(buffer.position(), buffer.limit());
- }
-
- buffer.put(value);
- }
-
- /** Write a single byte, represented by an integer value. */
- public void writeRawByte(final int value) throws IOException {
- writeRawByte((byte) value);
- }
-
- /** Write an array of bytes. */
- public void writeRawBytes(final byte[] value) throws IOException {
- writeRawBytes(value, 0, value.length);
- }
-
- /** Write part of an array of bytes. */
- public void writeRawBytes(final byte[] value, int offset, int length)
- throws IOException {
- if (buffer.remaining() >= length) {
- buffer.put(value, offset, length);
- } else {
- // We're writing to a single buffer.
- throw new OutOfSpaceException(buffer.position(), buffer.limit());
- }
- }
-
- /** Encode and write a tag. */
- public void writeTag(final int fieldNumber, final int wireType)
- throws IOException {
- writeRawVarint32(WireFormatNano.makeTag(fieldNumber, wireType));
- }
-
- /** Compute the number of bytes that would be needed to encode a tag. */
- public static int computeTagSize(final int fieldNumber) {
- return computeRawVarint32Size(WireFormatNano.makeTag(fieldNumber, 0));
- }
-
- /**
- * Encode and write a varint. {@code value} is treated as
- * unsigned, so it won't be sign-extended if negative.
- */
- public void writeRawVarint32(int value) throws IOException {
- while (true) {
- if ((value & ~0x7F) == 0) {
- writeRawByte(value);
- return;
- } else {
- writeRawByte((value & 0x7F) | 0x80);
- value >>>= 7;
- }
- }
- }
-
- /**
- * 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.
- */
- public static int computeRawVarint32Size(final int value) {
- if ((value & (0xffffffff << 7)) == 0) return 1;
- if ((value & (0xffffffff << 14)) == 0) return 2;
- if ((value & (0xffffffff << 21)) == 0) return 3;
- if ((value & (0xffffffff << 28)) == 0) return 4;
- return 5;
- }
-
- /** Encode and write a varint. */
- public void writeRawVarint64(long value) throws IOException {
- while (true) {
- if ((value & ~0x7FL) == 0) {
- writeRawByte((int)value);
- return;
- } else {
- writeRawByte(((int)value & 0x7F) | 0x80);
- value >>>= 7;
- }
- }
- }
-
- /** Compute the number of bytes that would be needed to encode a varint. */
- public static int computeRawVarint64Size(final long value) {
- if ((value & (0xffffffffffffffffL << 7)) == 0) return 1;
- if ((value & (0xffffffffffffffffL << 14)) == 0) return 2;
- if ((value & (0xffffffffffffffffL << 21)) == 0) return 3;
- if ((value & (0xffffffffffffffffL << 28)) == 0) return 4;
- if ((value & (0xffffffffffffffffL << 35)) == 0) return 5;
- if ((value & (0xffffffffffffffffL << 42)) == 0) return 6;
- if ((value & (0xffffffffffffffffL << 49)) == 0) return 7;
- if ((value & (0xffffffffffffffffL << 56)) == 0) return 8;
- if ((value & (0xffffffffffffffffL << 63)) == 0) return 9;
- return 10;
- }
-
- /** Write a little-endian 32-bit integer. */
- public void writeRawLittleEndian32(final int value) throws IOException {
- if (buffer.remaining() < 4) {
- throw new OutOfSpaceException(buffer.position(), buffer.limit());
- }
- buffer.putInt(value);
- }
-
- public static final int LITTLE_ENDIAN_32_SIZE = 4;
-
- /** Write a little-endian 64-bit integer. */
- public void writeRawLittleEndian64(final long value) throws IOException {
- if (buffer.remaining() < 8) {
- throw new OutOfSpaceException(buffer.position(), buffer.limit());
- }
- buffer.putLong(value);
- }
-
- public static final int LITTLE_ENDIAN_64_SIZE = 8;
-
- /**
- * 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.
- */
- public static int encodeZigZag32(final int n) {
- // Note: the right-shift must be arithmetic
- return (n << 1) ^ (n >> 31);
- }
-
- /**
- * 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.
- */
- public static long encodeZigZag64(final long n) {
- // Note: the right-shift must be arithmetic
- return (n << 1) ^ (n >> 63);
- }
-
- static int computeFieldSize(int number, int type, Object object) {
- switch (type) {
- case InternalNano.TYPE_BOOL:
- return computeBoolSize(number, (Boolean) object);
- case InternalNano.TYPE_BYTES:
- return computeBytesSize(number, (byte[]) object);
- case InternalNano.TYPE_STRING:
- return computeStringSize(number, (String) object);
- case InternalNano.TYPE_FLOAT:
- return computeFloatSize(number, (Float) object);
- case InternalNano.TYPE_DOUBLE:
- return computeDoubleSize(number, (Double) object);
- case InternalNano.TYPE_ENUM:
- return computeEnumSize(number, (Integer) object);
- case InternalNano.TYPE_FIXED32:
- return computeFixed32Size(number, (Integer) object);
- case InternalNano.TYPE_INT32:
- return computeInt32Size(number, (Integer) object);
- case InternalNano.TYPE_UINT32:
- return computeUInt32Size(number, (Integer) object);
- case InternalNano.TYPE_SINT32:
- return computeSInt32Size(number, (Integer) object);
- case InternalNano.TYPE_SFIXED32:
- return computeSFixed32Size(number, (Integer) object);
- case InternalNano.TYPE_INT64:
- return computeInt64Size(number, (Long) object);
- case InternalNano.TYPE_UINT64:
- return computeUInt64Size(number, (Long) object);
- case InternalNano.TYPE_SINT64:
- return computeSInt64Size(number, (Long) object);
- case InternalNano.TYPE_FIXED64:
- return computeFixed64Size(number, (Long) object);
- case InternalNano.TYPE_SFIXED64:
- return computeSFixed64Size(number, (Long) object);
- case InternalNano.TYPE_MESSAGE:
- return computeMessageSize(number, (MessageNano) object);
- case InternalNano.TYPE_GROUP:
- return computeGroupSize(number, (MessageNano) object);
- default:
- throw new IllegalArgumentException("Unknown type: " + type);
- }
- }
-
- void writeField(int number, int type, Object value)
- throws IOException {
- switch (type) {
- case InternalNano.TYPE_DOUBLE:
- Double doubleValue = (Double) value;
- writeDouble(number, doubleValue);
- break;
- case InternalNano.TYPE_FLOAT:
- Float floatValue = (Float) value;
- writeFloat(number, floatValue);
- break;
- case InternalNano.TYPE_INT64:
- Long int64Value = (Long) value;
- writeInt64(number, int64Value);
- break;
- case InternalNano.TYPE_UINT64:
- Long uint64Value = (Long) value;
- writeUInt64(number, uint64Value);
- break;
- case InternalNano.TYPE_INT32:
- Integer int32Value = (Integer) value;
- writeInt32(number, int32Value);
- break;
- case InternalNano.TYPE_FIXED64:
- Long fixed64Value = (Long) value;
- writeFixed64(number, fixed64Value);
- break;
- case InternalNano.TYPE_FIXED32:
- Integer fixed32Value = (Integer) value;
- writeFixed32(number, fixed32Value);
- break;
- case InternalNano.TYPE_BOOL:
- Boolean boolValue = (Boolean) value;
- writeBool(number, boolValue);
- break;
- case InternalNano.TYPE_STRING:
- String stringValue = (String) value;
- writeString(number, stringValue);
- break;
- case InternalNano.TYPE_BYTES:
- byte[] bytesValue = (byte[]) value;
- writeBytes(number, bytesValue);
- break;
- case InternalNano.TYPE_UINT32:
- Integer uint32Value = (Integer) value;
- writeUInt32(number, uint32Value);
- break;
- case InternalNano.TYPE_ENUM:
- Integer enumValue = (Integer) value;
- writeEnum(number, enumValue);
- break;
- case InternalNano.TYPE_SFIXED32:
- Integer sfixed32Value = (Integer) value;
- writeSFixed32(number, sfixed32Value);
- break;
- case InternalNano.TYPE_SFIXED64:
- Long sfixed64Value = (Long) value;
- writeSFixed64(number, sfixed64Value);
- break;
- case InternalNano.TYPE_SINT32:
- Integer sint32Value = (Integer) value;
- writeSInt32(number, sint32Value);
- break;
- case InternalNano.TYPE_SINT64:
- Long sint64Value = (Long) value;
- writeSInt64(number, sint64Value);
- break;
- case InternalNano.TYPE_MESSAGE:
- MessageNano messageValue = (MessageNano) value;
- writeMessage(number, messageValue);
- break;
- case InternalNano.TYPE_GROUP:
- MessageNano groupValue = (MessageNano) value;
- writeGroup(number, groupValue);
- break;
- default:
- throw new IOException("Unknown type: " + type);
- }
- }
-
-}
diff --git a/javanano/src/main/java/com/google/protobuf/nano/ExtendableMessageNano.java b/javanano/src/main/java/com/google/protobuf/nano/ExtendableMessageNano.java
deleted file mode 100644
index 87973d76..00000000
--- a/javanano/src/main/java/com/google/protobuf/nano/ExtendableMessageNano.java
+++ /dev/null
@@ -1,169 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2013 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package com.google.protobuf.nano;
-
-import java.io.IOException;
-
-/**
- * Base class of those Protocol Buffer messages that need to store unknown fields,
- * such as extensions.
- */
-public abstract class ExtendableMessageNano<M extends ExtendableMessageNano<M>>
- extends MessageNano {
- /**
- * A container for fields unknown to the message, including extensions. Extension fields can
- * can be accessed through the {@link #getExtension} and {@link #setExtension} methods.
- */
- protected FieldArray unknownFieldData;
-
- @Override
- protected int computeSerializedSize() {
- int size = 0;
- if (unknownFieldData != null) {
- for (int i = 0; i < unknownFieldData.size(); i++) {
- FieldData field = unknownFieldData.dataAt(i);
- size += field.computeSerializedSize();
- }
- }
- return size;
- }
-
- @Override
- public void writeTo(CodedOutputByteBufferNano output) throws IOException {
- if (unknownFieldData == null) {
- return;
- }
- for (int i = 0; i < unknownFieldData.size(); i++) {
- FieldData field = unknownFieldData.dataAt(i);
- field.writeTo(output);
- }
- }
-
- /**
- * Checks if there is a value stored for the specified extension in this
- * message.
- */
- public final boolean hasExtension(Extension<M, ?> extension) {
- if (unknownFieldData == null) {
- return false;
- }
- FieldData field = unknownFieldData.get(WireFormatNano.getTagFieldNumber(extension.tag));
- return field != null;
- }
-
- /**
- * Gets the value stored in the specified extension of this message.
- */
- public final <T> T getExtension(Extension<M, T> extension) {
- if (unknownFieldData == null) {
- return null;
- }
- FieldData field = unknownFieldData.get(WireFormatNano.getTagFieldNumber(extension.tag));
- return field == null ? null : field.getValue(extension);
- }
-
- /**
- * Sets the value of the specified extension of this message.
- */
- public final <T> M setExtension(Extension<M, T> extension, T value) {
- int fieldNumber = WireFormatNano.getTagFieldNumber(extension.tag);
- if (value == null) {
- if (unknownFieldData != null) {
- unknownFieldData.remove(fieldNumber);
- if (unknownFieldData.isEmpty()) {
- unknownFieldData = null;
- }
- }
- } else {
- FieldData field = null;
- if (unknownFieldData == null) {
- unknownFieldData = new FieldArray();
- } else {
- field = unknownFieldData.get(fieldNumber);
- }
- if (field == null) {
- unknownFieldData.put(fieldNumber, new FieldData(extension, value));
- } else {
- field.setValue(extension, value);
- }
- }
-
- @SuppressWarnings("unchecked") // Generated code should guarantee type safety
- M typedThis = (M) this;
- return typedThis;
- }
-
- /**
- * Stores the binary data of an unknown field.
- *
- * <p>Generated messages will call this for unknown fields if the store_unknown_fields
- * option is on.
- *
- * <p>Note that the tag might be a end-group tag (rather than the start of an unknown field) in
- * which case we do not want to add an unknown field entry.
- *
- * @param input the input buffer.
- * @param tag the tag of the field.
-
- * @return {@literal true} unless the tag is an end-group tag.
- */
- protected final boolean storeUnknownField(CodedInputByteBufferNano input, int tag)
- throws IOException {
- int startPos = input.getPosition();
- if (!input.skipField(tag)) {
- return false; // This wasn't an unknown field, it's an end-group tag.
- }
- int fieldNumber = WireFormatNano.getTagFieldNumber(tag);
- int endPos = input.getPosition();
- byte[] bytes = input.getData(startPos, endPos - startPos);
- UnknownFieldData unknownField = new UnknownFieldData(tag, bytes);
-
- FieldData field = null;
- if (unknownFieldData == null) {
- unknownFieldData = new FieldArray();
- } else {
- field = unknownFieldData.get(fieldNumber);
- }
- if (field == null) {
- field = new FieldData();
- unknownFieldData.put(fieldNumber, field);
- }
- field.addUnknownField(unknownField);
- return true;
- }
-
- @Override
- public M clone() throws CloneNotSupportedException {
- M cloned = (M) super.clone();
- InternalNano.cloneUnknownFieldData(this, cloned);
- return cloned;
- }
-}
diff --git a/javanano/src/main/java/com/google/protobuf/nano/Extension.java b/javanano/src/main/java/com/google/protobuf/nano/Extension.java
deleted file mode 100644
index c458f9b1..00000000
--- a/javanano/src/main/java/com/google/protobuf/nano/Extension.java
+++ /dev/null
@@ -1,706 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2013 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package com.google.protobuf.nano;
-
-import java.io.IOException;
-import java.lang.reflect.Array;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Represents an extension.
- *
- * @author bduff@google.com (Brian Duff)
- * @author maxtroy@google.com (Max Cai)
- * @param <M> the type of the extendable message this extension is for.
- * @param <T> the Java type of the extension; see {@link #clazz}.
- */
-public class Extension<M extends ExtendableMessageNano<M>, T> {
-
- /*
- * Because we typically only define message-typed extensions, the Extension class hierarchy is
- * designed as follows, to allow a big amount of code in this file to be removed by ProGuard:
- *
- * Extension // ready to use for message/group typed extensions
- * Δ
- * |
- * PrimitiveExtension // for primitive/enum typed extensions
- */
-
- public static final int TYPE_DOUBLE = InternalNano.TYPE_DOUBLE;
- public static final int TYPE_FLOAT = InternalNano.TYPE_FLOAT;
- public static final int TYPE_INT64 = InternalNano.TYPE_INT64;
- public static final int TYPE_UINT64 = InternalNano.TYPE_UINT64;
- public static final int TYPE_INT32 = InternalNano.TYPE_INT32;
- public static final int TYPE_FIXED64 = InternalNano.TYPE_FIXED64;
- public static final int TYPE_FIXED32 = InternalNano.TYPE_FIXED32;
- public static final int TYPE_BOOL = InternalNano.TYPE_BOOL;
- public static final int TYPE_STRING = InternalNano.TYPE_STRING;
- public static final int TYPE_GROUP = InternalNano.TYPE_GROUP;
- public static final int TYPE_MESSAGE = InternalNano.TYPE_MESSAGE;
- public static final int TYPE_BYTES = InternalNano.TYPE_BYTES;
- public static final int TYPE_UINT32 = InternalNano.TYPE_UINT32;
- public static final int TYPE_ENUM = InternalNano.TYPE_ENUM;
- public static final int TYPE_SFIXED32 = InternalNano.TYPE_SFIXED32;
- public static final int TYPE_SFIXED64 = InternalNano.TYPE_SFIXED64;
- public static final int TYPE_SINT32 = InternalNano.TYPE_SINT32;
- public static final int TYPE_SINT64 = InternalNano.TYPE_SINT64;
-
- /**
- * Creates an {@code Extension} of the given message type and tag number.
- * Should be used by the generated code only.
- *
- * @param type {@link #TYPE_MESSAGE} or {@link #TYPE_GROUP}
- * @deprecated use {@link #createMessageTyped(int, Class, long)} instead.
- */
- @Deprecated
- public static <M extends ExtendableMessageNano<M>, T extends MessageNano>
- Extension<M, T> createMessageTyped(int type, Class<T> clazz, int tag) {
- return new Extension<M, T>(type, clazz, tag, false);
- }
-
- // Note: these create...() methods take a long for the tag parameter,
- // because tags are represented as unsigned ints, and these values exist
- // in generated code as long values. However, they can fit in 32-bits, so
- // it's safe to cast them to int without loss of precision.
-
- /**
- * Creates an {@code Extension} of the given message type and tag number.
- * Should be used by the generated code only.
- *
- * @param type {@link #TYPE_MESSAGE} or {@link #TYPE_GROUP}
- */
- public static <M extends ExtendableMessageNano<M>, T extends MessageNano>
- Extension<M, T> createMessageTyped(int type, Class<T> clazz, long tag) {
- return new Extension<M, T>(type, clazz, (int) tag, false);
- }
-
- /**
- * Creates a repeated {@code Extension} of the given message type and tag number.
- * Should be used by the generated code only.
- *
- * @param type {@link #TYPE_MESSAGE} or {@link #TYPE_GROUP}
- */
- public static <M extends ExtendableMessageNano<M>, T extends MessageNano>
- Extension<M, T[]> createRepeatedMessageTyped(int type, Class<T[]> clazz, long tag) {
- return new Extension<M, T[]>(type, clazz, (int) tag, true);
- }
-
- /**
- * Creates an {@code Extension} of the given primitive type and tag number.
- * Should be used by the generated code only.
- *
- * @param type one of {@code TYPE_*}, except {@link #TYPE_MESSAGE} and {@link #TYPE_GROUP}
- * @param clazz the boxed Java type of this extension
- */
- public static <M extends ExtendableMessageNano<M>, T>
- Extension<M, T> createPrimitiveTyped(int type, Class<T> clazz, long tag) {
- return new PrimitiveExtension<M, T>(type, clazz, (int) tag, false, 0, 0);
- }
-
- /**
- * Creates a repeated {@code Extension} of the given primitive type and tag number.
- * Should be used by the generated code only.
- *
- * @param type one of {@code TYPE_*}, except {@link #TYPE_MESSAGE} and {@link #TYPE_GROUP}
- * @param clazz the Java array type of this extension, with an unboxed component type
- */
- public static <M extends ExtendableMessageNano<M>, T>
- Extension<M, T> createRepeatedPrimitiveTyped(
- int type, Class<T> clazz, long tag, long nonPackedTag, long packedTag) {
- return new PrimitiveExtension<M, T>(type, clazz, (int) tag, true,
- (int) nonPackedTag, (int) packedTag);
- }
-
- /**
- * Protocol Buffer type of this extension; one of the {@code TYPE_} constants.
- */
- protected final int type;
-
- /**
- * Java type of this extension. For a singular extension, this is the boxed Java type for the
- * Protocol Buffer {@link #type}; for a repeated extension, this is an array type whose
- * component type is the unboxed Java type for {@link #type}. For example, for a singular
- * {@code int32}/{@link #TYPE_INT32} extension, this equals {@code Integer.class}; for a
- * repeated {@code int32} extension, this equals {@code int[].class}.
- */
- protected final Class<T> clazz;
-
- /**
- * Tag number of this extension. The data should be viewed as an unsigned 32-bit value.
- */
- public final int tag;
-
- /**
- * Whether this extension is repeated.
- */
- protected final boolean repeated;
-
- private Extension(int type, Class<T> clazz, int tag, boolean repeated) {
- this.type = type;
- this.clazz = clazz;
- this.tag = tag;
- this.repeated = repeated;
- }
-
- /**
- * Returns the value of this extension stored in the given list of unknown fields, or
- * {@code null} if no unknown fields matches this extension.
- *
- * @param unknownFields a list of {@link UnknownFieldData}. All of the elements must have a tag
- * that matches this Extension's tag.
- *
- */
- final T getValueFrom(List<UnknownFieldData> unknownFields) {
- if (unknownFields == null) {
- return null;
- }
- return repeated ? getRepeatedValueFrom(unknownFields) : getSingularValueFrom(unknownFields);
- }
-
- private T getRepeatedValueFrom(List<UnknownFieldData> unknownFields) {
- // For repeated extensions, read all matching unknown fields in their original order.
- List<Object> resultList = new ArrayList<Object>();
- for (int i = 0; i < unknownFields.size(); i++) {
- UnknownFieldData data = unknownFields.get(i);
- if (data.bytes.length != 0) {
- readDataInto(data, resultList);
- }
- }
-
- int resultSize = resultList.size();
- if (resultSize == 0) {
- return null;
- } else {
- T result = clazz.cast(Array.newInstance(clazz.getComponentType(), resultSize));
- for (int i = 0; i < resultSize; i++) {
- Array.set(result, i, resultList.get(i));
- }
- return result;
- }
- }
-
- private T getSingularValueFrom(List<UnknownFieldData> unknownFields) {
- // For singular extensions, get the last piece of data stored under this extension.
- if (unknownFields.isEmpty()) {
- return null;
- }
- UnknownFieldData lastData = unknownFields.get(unknownFields.size() - 1);
- return clazz.cast(readData(CodedInputByteBufferNano.newInstance(lastData.bytes)));
- }
-
- protected Object readData(CodedInputByteBufferNano input) {
- // This implementation is for message/group extensions.
- Class<?> messageType = repeated ? clazz.getComponentType() : clazz;
- try {
- switch (type) {
- case TYPE_GROUP:
- MessageNano group = (MessageNano) messageType.newInstance();
- input.readGroup(group, WireFormatNano.getTagFieldNumber(tag));
- return group;
- case TYPE_MESSAGE:
- MessageNano message = (MessageNano) messageType.newInstance();
- input.readMessage(message);
- return message;
- default:
- throw new IllegalArgumentException("Unknown type " + type);
- }
- } catch (InstantiationException e) {
- throw new IllegalArgumentException(
- "Error creating instance of class " + messageType, e);
- } catch (IllegalAccessException e) {
- throw new IllegalArgumentException(
- "Error creating instance of class " + messageType, e);
- } catch (IOException e) {
- throw new IllegalArgumentException("Error reading extension field", e);
- }
- }
-
- protected void readDataInto(UnknownFieldData data, List<Object> resultList) {
- // This implementation is for message/group extensions.
- resultList.add(readData(CodedInputByteBufferNano.newInstance(data.bytes)));
- }
-
- void writeTo(Object value, CodedOutputByteBufferNano output) throws IOException {
- if (repeated) {
- writeRepeatedData(value, output);
- } else {
- writeSingularData(value, output);
- }
- }
-
- protected void writeSingularData(Object value, CodedOutputByteBufferNano out) {
- // This implementation is for message/group extensions.
- try {
- out.writeRawVarint32(tag);
- switch (type) {
- case TYPE_GROUP:
- MessageNano groupValue = (MessageNano) value;
- int fieldNumber = WireFormatNano.getTagFieldNumber(tag);
- out.writeGroupNoTag(groupValue);
- // The endgroup tag must be included in the data payload.
- out.writeTag(fieldNumber, WireFormatNano.WIRETYPE_END_GROUP);
- break;
- case TYPE_MESSAGE:
- MessageNano messageValue = (MessageNano) value;
- out.writeMessageNoTag(messageValue);
- break;
- default:
- throw new IllegalArgumentException("Unknown type " + type);
- }
- } catch (IOException e) {
- // Should not happen
- throw new IllegalStateException(e);
- }
- }
-
- protected void writeRepeatedData(Object array, CodedOutputByteBufferNano output) {
- // This implementation is for non-packed extensions.
- int arrayLength = Array.getLength(array);
- for (int i = 0; i < arrayLength; i++) {
- Object element = Array.get(array, i);
- if (element != null) {
- writeSingularData(element, output);
- }
- }
- }
-
- int computeSerializedSize(Object value) {
- if (repeated) {
- return computeRepeatedSerializedSize(value);
- } else {
- return computeSingularSerializedSize(value);
- }
- }
-
- protected int computeRepeatedSerializedSize(Object array) {
- // This implementation is for non-packed extensions.
- int size = 0;
- int arrayLength = Array.getLength(array);
- for (int i = 0; i < arrayLength; i++) {
- Object element = Array.get(array, i);
- if (element != null) {
- size += computeSingularSerializedSize(Array.get(array, i));
- }
- }
- return size;
- }
-
- protected int computeSingularSerializedSize(Object value) {
- // This implementation is for message/group extensions.
- int fieldNumber = WireFormatNano.getTagFieldNumber(tag);
- switch (type) {
- case TYPE_GROUP:
- MessageNano groupValue = (MessageNano) value;
- return CodedOutputByteBufferNano.computeGroupSize(fieldNumber, groupValue);
- case TYPE_MESSAGE:
- MessageNano messageValue = (MessageNano) value;
- return CodedOutputByteBufferNano.computeMessageSize(fieldNumber, messageValue);
- default:
- throw new IllegalArgumentException("Unknown type " + type);
- }
- }
-
- /**
- * Represents an extension of a primitive (including enum) type. If there is no primitive
- * extensions, this subclass will be removable by ProGuard.
- */
- private static class PrimitiveExtension<M extends ExtendableMessageNano<M>, T>
- extends Extension<M, T> {
-
- /**
- * Tag of a piece of non-packed data from the wire compatible with this extension.
- */
- private final int nonPackedTag;
-
- /**
- * Tag of a piece of packed data from the wire compatible with this extension.
- * 0 if the type of this extension is not packable.
- */
- private final int packedTag;
-
- public PrimitiveExtension(int type, Class<T> clazz, int tag, boolean repeated,
- int nonPackedTag, int packedTag) {
- super(type, clazz, tag, repeated);
- this.nonPackedTag = nonPackedTag;
- this.packedTag = packedTag;
- }
-
- @Override
- protected Object readData(CodedInputByteBufferNano input) {
- try {
- return input.readPrimitiveField(type);
- } catch (IOException e) {
- throw new IllegalArgumentException("Error reading extension field", e);
- }
- }
-
- @Override
- protected void readDataInto(UnknownFieldData data, List<Object> resultList) {
- // This implementation is for primitive typed extensions,
- // which can read both packed and non-packed data.
- if (data.tag == nonPackedTag) {
- resultList.add(readData(CodedInputByteBufferNano.newInstance(data.bytes)));
- } else {
- CodedInputByteBufferNano buffer =
- CodedInputByteBufferNano.newInstance(data.bytes);
- try {
- buffer.pushLimit(buffer.readRawVarint32()); // length limit
- } catch (IOException e) {
- throw new IllegalArgumentException("Error reading extension field", e);
- }
- while (!buffer.isAtEnd()) {
- resultList.add(readData(buffer));
- }
- }
- }
-
- @Override
- protected final void writeSingularData(Object value, CodedOutputByteBufferNano output) {
- try {
- output.writeRawVarint32(tag);
- switch (type) {
- case TYPE_DOUBLE:
- Double doubleValue = (Double) value;
- output.writeDoubleNoTag(doubleValue);
- break;
- case TYPE_FLOAT:
- Float floatValue = (Float) value;
- output.writeFloatNoTag(floatValue);
- break;
- case TYPE_INT64:
- Long int64Value = (Long) value;
- output.writeInt64NoTag(int64Value);
- break;
- case TYPE_UINT64:
- Long uint64Value = (Long) value;
- output.writeUInt64NoTag(uint64Value);
- break;
- case TYPE_INT32:
- Integer int32Value = (Integer) value;
- output.writeInt32NoTag(int32Value);
- break;
- case TYPE_FIXED64:
- Long fixed64Value = (Long) value;
- output.writeFixed64NoTag(fixed64Value);
- break;
- case TYPE_FIXED32:
- Integer fixed32Value = (Integer) value;
- output.writeFixed32NoTag(fixed32Value);
- break;
- case TYPE_BOOL:
- Boolean boolValue = (Boolean) value;
- output.writeBoolNoTag(boolValue);
- break;
- case TYPE_STRING:
- String stringValue = (String) value;
- output.writeStringNoTag(stringValue);
- break;
- case TYPE_BYTES:
- byte[] bytesValue = (byte[]) value;
- output.writeBytesNoTag(bytesValue);
- break;
- case TYPE_UINT32:
- Integer uint32Value = (Integer) value;
- output.writeUInt32NoTag(uint32Value);
- break;
- case TYPE_ENUM:
- Integer enumValue = (Integer) value;
- output.writeEnumNoTag(enumValue);
- break;
- case TYPE_SFIXED32:
- Integer sfixed32Value = (Integer) value;
- output.writeSFixed32NoTag(sfixed32Value);
- break;
- case TYPE_SFIXED64:
- Long sfixed64Value = (Long) value;
- output.writeSFixed64NoTag(sfixed64Value);
- break;
- case TYPE_SINT32:
- Integer sint32Value = (Integer) value;
- output.writeSInt32NoTag(sint32Value);
- break;
- case TYPE_SINT64:
- Long sint64Value = (Long) value;
- output.writeSInt64NoTag(sint64Value);
- break;
- default:
- throw new IllegalArgumentException("Unknown type " + type);
- }
- } catch (IOException e) {
- // Should not happen
- throw new IllegalStateException(e);
- }
- }
-
- @Override
- protected void writeRepeatedData(Object array, CodedOutputByteBufferNano output) {
- if (tag == nonPackedTag) {
- // Use base implementation for non-packed data
- super.writeRepeatedData(array, output);
- } else if (tag == packedTag) {
- // Packed. Note that the array element type is guaranteed to be primitive, so there
- // won't be any null elements, so no null check in this block.
- int arrayLength = Array.getLength(array);
- int dataSize = computePackedDataSize(array);
-
- try {
- output.writeRawVarint32(tag);
- output.writeRawVarint32(dataSize);
- switch (type) {
- case TYPE_BOOL:
- for (int i = 0; i < arrayLength; i++) {
- output.writeBoolNoTag(Array.getBoolean(array, i));
- }
- break;
- case TYPE_FIXED32:
- for (int i = 0; i < arrayLength; i++) {
- output.writeFixed32NoTag(Array.getInt(array, i));
- }
- break;
- case TYPE_SFIXED32:
- for (int i = 0; i < arrayLength; i++) {
- output.writeSFixed32NoTag(Array.getInt(array, i));
- }
- break;
- case TYPE_FLOAT:
- for (int i = 0; i < arrayLength; i++) {
- output.writeFloatNoTag(Array.getFloat(array, i));
- }
- break;
- case TYPE_FIXED64:
- for (int i = 0; i < arrayLength; i++) {
- output.writeFixed64NoTag(Array.getLong(array, i));
- }
- break;
- case TYPE_SFIXED64:
- for (int i = 0; i < arrayLength; i++) {
- output.writeSFixed64NoTag(Array.getLong(array, i));
- }
- break;
- case TYPE_DOUBLE:
- for (int i = 0; i < arrayLength; i++) {
- output.writeDoubleNoTag(Array.getDouble(array, i));
- }
- break;
- case TYPE_INT32:
- for (int i = 0; i < arrayLength; i++) {
- output.writeInt32NoTag(Array.getInt(array, i));
- }
- break;
- case TYPE_SINT32:
- for (int i = 0; i < arrayLength; i++) {
- output.writeSInt32NoTag(Array.getInt(array, i));
- }
- break;
- case TYPE_UINT32:
- for (int i = 0; i < arrayLength; i++) {
- output.writeUInt32NoTag(Array.getInt(array, i));
- }
- break;
- case TYPE_INT64:
- for (int i = 0; i < arrayLength; i++) {
- output.writeInt64NoTag(Array.getLong(array, i));
- }
- break;
- case TYPE_SINT64:
- for (int i = 0; i < arrayLength; i++) {
- output.writeSInt64NoTag(Array.getLong(array, i));
- }
- break;
- case TYPE_UINT64:
- for (int i = 0; i < arrayLength; i++) {
- output.writeUInt64NoTag(Array.getLong(array, i));
- }
- break;
- case TYPE_ENUM:
- for (int i = 0; i < arrayLength; i++) {
- output.writeEnumNoTag(Array.getInt(array, i));
- }
- break;
- default:
- throw new IllegalArgumentException("Unpackable type " + type);
- }
- } catch (IOException e) {
- // Should not happen.
- throw new IllegalStateException(e);
- }
- } else {
- throw new IllegalArgumentException("Unexpected repeated extension tag " + tag
- + ", unequal to both non-packed variant " + nonPackedTag
- + " and packed variant " + packedTag);
- }
- }
-
- private int computePackedDataSize(Object array) {
- int dataSize = 0;
- int arrayLength = Array.getLength(array);
- switch (type) {
- case TYPE_BOOL:
- // Bools are stored as int32 but just as 0 or 1, so 1 byte each.
- dataSize = arrayLength;
- break;
- case TYPE_FIXED32:
- case TYPE_SFIXED32:
- case TYPE_FLOAT:
- dataSize = arrayLength * CodedOutputByteBufferNano.LITTLE_ENDIAN_32_SIZE;
- break;
- case TYPE_FIXED64:
- case TYPE_SFIXED64:
- case TYPE_DOUBLE:
- dataSize = arrayLength * CodedOutputByteBufferNano.LITTLE_ENDIAN_64_SIZE;
- break;
- case TYPE_INT32:
- for (int i = 0; i < arrayLength; i++) {
- dataSize += CodedOutputByteBufferNano.computeInt32SizeNoTag(
- Array.getInt(array, i));
- }
- break;
- case TYPE_SINT32:
- for (int i = 0; i < arrayLength; i++) {
- dataSize += CodedOutputByteBufferNano.computeSInt32SizeNoTag(
- Array.getInt(array, i));
- }
- break;
- case TYPE_UINT32:
- for (int i = 0; i < arrayLength; i++) {
- dataSize += CodedOutputByteBufferNano.computeUInt32SizeNoTag(
- Array.getInt(array, i));
- }
- break;
- case TYPE_INT64:
- for (int i = 0; i < arrayLength; i++) {
- dataSize += CodedOutputByteBufferNano.computeInt64SizeNoTag(
- Array.getLong(array, i));
- }
- break;
- case TYPE_SINT64:
- for (int i = 0; i < arrayLength; i++) {
- dataSize += CodedOutputByteBufferNano.computeSInt64SizeNoTag(
- Array.getLong(array, i));
- }
- break;
- case TYPE_UINT64:
- for (int i = 0; i < arrayLength; i++) {
- dataSize += CodedOutputByteBufferNano.computeUInt64SizeNoTag(
- Array.getLong(array, i));
- }
- break;
- case TYPE_ENUM:
- for (int i = 0; i < arrayLength; i++) {
- dataSize += CodedOutputByteBufferNano.computeEnumSizeNoTag(
- Array.getInt(array, i));
- }
- break;
- default:
- throw new IllegalArgumentException("Unexpected non-packable type " + type);
- }
- return dataSize;
- }
-
- @Override
- protected int computeRepeatedSerializedSize(Object array) {
- if (tag == nonPackedTag) {
- // Use base implementation for non-packed data
- return super.computeRepeatedSerializedSize(array);
- } else if (tag == packedTag) {
- // Packed.
- int dataSize = computePackedDataSize(array);
- int payloadSize =
- dataSize + CodedOutputByteBufferNano.computeRawVarint32Size(dataSize);
- return payloadSize + CodedOutputByteBufferNano.computeRawVarint32Size(tag);
- } else {
- throw new IllegalArgumentException("Unexpected repeated extension tag " + tag
- + ", unequal to both non-packed variant " + nonPackedTag
- + " and packed variant " + packedTag);
- }
- }
-
- @Override
- protected final int computeSingularSerializedSize(Object value) {
- int fieldNumber = WireFormatNano.getTagFieldNumber(tag);
- switch (type) {
- case TYPE_DOUBLE:
- Double doubleValue = (Double) value;
- return CodedOutputByteBufferNano.computeDoubleSize(fieldNumber, doubleValue);
- case TYPE_FLOAT:
- Float floatValue = (Float) value;
- return CodedOutputByteBufferNano.computeFloatSize(fieldNumber, floatValue);
- case TYPE_INT64:
- Long int64Value = (Long) value;
- return CodedOutputByteBufferNano.computeInt64Size(fieldNumber, int64Value);
- case TYPE_UINT64:
- Long uint64Value = (Long) value;
- return CodedOutputByteBufferNano.computeUInt64Size(fieldNumber, uint64Value);
- case TYPE_INT32:
- Integer int32Value = (Integer) value;
- return CodedOutputByteBufferNano.computeInt32Size(fieldNumber, int32Value);
- case TYPE_FIXED64:
- Long fixed64Value = (Long) value;
- return CodedOutputByteBufferNano.computeFixed64Size(fieldNumber, fixed64Value);
- case TYPE_FIXED32:
- Integer fixed32Value = (Integer) value;
- return CodedOutputByteBufferNano.computeFixed32Size(fieldNumber, fixed32Value);
- case TYPE_BOOL:
- Boolean boolValue = (Boolean) value;
- return CodedOutputByteBufferNano.computeBoolSize(fieldNumber, boolValue);
- case TYPE_STRING:
- String stringValue = (String) value;
- return CodedOutputByteBufferNano.computeStringSize(fieldNumber, stringValue);
- case TYPE_BYTES:
- byte[] bytesValue = (byte[]) value;
- return CodedOutputByteBufferNano.computeBytesSize(fieldNumber, bytesValue);
- case TYPE_UINT32:
- Integer uint32Value = (Integer) value;
- return CodedOutputByteBufferNano.computeUInt32Size(fieldNumber, uint32Value);
- case TYPE_ENUM:
- Integer enumValue = (Integer) value;
- return CodedOutputByteBufferNano.computeEnumSize(fieldNumber, enumValue);
- case TYPE_SFIXED32:
- Integer sfixed32Value = (Integer) value;
- return CodedOutputByteBufferNano.computeSFixed32Size(fieldNumber,
- sfixed32Value);
- case TYPE_SFIXED64:
- Long sfixed64Value = (Long) value;
- return CodedOutputByteBufferNano.computeSFixed64Size(fieldNumber,
- sfixed64Value);
- case TYPE_SINT32:
- Integer sint32Value = (Integer) value;
- return CodedOutputByteBufferNano.computeSInt32Size(fieldNumber, sint32Value);
- case TYPE_SINT64:
- Long sint64Value = (Long) value;
- return CodedOutputByteBufferNano.computeSInt64Size(fieldNumber, sint64Value);
- default:
- throw new IllegalArgumentException("Unknown type " + type);
- }
- }
- }
-}
diff --git a/javanano/src/main/java/com/google/protobuf/nano/FieldArray.java b/javanano/src/main/java/com/google/protobuf/nano/FieldArray.java
deleted file mode 100644
index b49a97fa..00000000
--- a/javanano/src/main/java/com/google/protobuf/nano/FieldArray.java
+++ /dev/null
@@ -1,291 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2014 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package com.google.protobuf.nano;
-
-
-/**
- * A custom version of {@code android.util.SparseArray} with the minimal API
- * for storing {@link FieldData} objects.
- *
- * <p>This class is an internal implementation detail of nano and should not
- * be called directly by clients.
- *
- * Based on {@code android.support.v4.util.SpareArrayCompat}.
- */
-public final class FieldArray implements Cloneable {
- private static final FieldData DELETED = new FieldData();
- private boolean mGarbage = false;
-
- private int[] mFieldNumbers;
- private FieldData[] mData;
- private int mSize;
-
- /**
- * Creates a new FieldArray containing no fields.
- */
- FieldArray() {
- this(10);
- }
-
- /**
- * Creates a new FieldArray containing no mappings that will not
- * require any additional memory allocation to store the specified
- * number of mappings.
- */
- FieldArray(int initialCapacity) {
- initialCapacity = idealIntArraySize(initialCapacity);
- mFieldNumbers = new int[initialCapacity];
- mData = new FieldData[initialCapacity];
- mSize = 0;
- }
-
- /**
- * Gets the FieldData mapped from the specified fieldNumber, or <code>null</code>
- * if no such mapping has been made.
- */
- FieldData get(int fieldNumber) {
- int i = binarySearch(fieldNumber);
-
- if (i < 0 || mData[i] == DELETED) {
- return null;
- } else {
- return mData[i];
- }
- }
-
- /**
- * Removes the data from the specified fieldNumber, if there was any.
- */
- void remove(int fieldNumber) {
- int i = binarySearch(fieldNumber);
-
- if (i >= 0 && mData[i] != DELETED) {
- mData[i] = DELETED;
- mGarbage = true;
- }
- }
-
- private void gc() {
- int n = mSize;
- int o = 0;
- int[] keys = mFieldNumbers;
- FieldData[] values = mData;
-
- for (int i = 0; i < n; i++) {
- FieldData val = values[i];
-
- if (val != DELETED) {
- if (i != o) {
- keys[o] = keys[i];
- values[o] = val;
- values[i] = null;
- }
-
- o++;
- }
- }
-
- mGarbage = false;
- mSize = o;
- }
-
- /**
- * Adds a mapping from the specified fieldNumber to the specified data,
- * replacing the previous mapping if there was one.
- */
- void put(int fieldNumber, FieldData data) {
- int i = binarySearch(fieldNumber);
-
- if (i >= 0) {
- mData[i] = data;
- } else {
- i = ~i;
-
- if (i < mSize && mData[i] == DELETED) {
- mFieldNumbers[i] = fieldNumber;
- mData[i] = data;
- return;
- }
-
- if (mGarbage && mSize >= mFieldNumbers.length) {
- gc();
-
- // Search again because indices may have changed.
- i = ~ binarySearch(fieldNumber);
- }
-
- if (mSize >= mFieldNumbers.length) {
- int n = idealIntArraySize(mSize + 1);
-
- int[] nkeys = new int[n];
- FieldData[] nvalues = new FieldData[n];
-
- System.arraycopy(mFieldNumbers, 0, nkeys, 0, mFieldNumbers.length);
- System.arraycopy(mData, 0, nvalues, 0, mData.length);
-
- mFieldNumbers = nkeys;
- mData = nvalues;
- }
-
- if (mSize - i != 0) {
- System.arraycopy(mFieldNumbers, i, mFieldNumbers, i + 1, mSize - i);
- System.arraycopy(mData, i, mData, i + 1, mSize - i);
- }
-
- mFieldNumbers[i] = fieldNumber;
- mData[i] = data;
- mSize++;
- }
- }
-
- /**
- * Returns the number of key-value mappings that this FieldArray
- * currently stores.
- */
- int size() {
- if (mGarbage) {
- gc();
- }
-
- return mSize;
- }
-
- public boolean isEmpty() {
- return size() == 0;
- }
-
- /**
- * Given an index in the range <code>0...size()-1</code>, returns
- * the value from the <code>index</code>th key-value mapping that this
- * FieldArray stores.
- */
- FieldData dataAt(int index) {
- if (mGarbage) {
- gc();
- }
-
- return mData[index];
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == this) {
- return true;
- }
- if (!(o instanceof FieldArray)) {
- return false;
- }
-
- FieldArray other = (FieldArray) o;
- if (size() != other.size()) { // size() will call gc() if necessary.
- return false;
- }
- return arrayEquals(mFieldNumbers, other.mFieldNumbers, mSize) &&
- arrayEquals(mData, other.mData, mSize);
- }
-
- @Override
- public int hashCode() {
- if (mGarbage) {
- gc();
- }
- int result = 17;
- for (int i = 0; i < mSize; i++) {
- result = 31 * result + mFieldNumbers[i];
- result = 31 * result + mData[i].hashCode();
- }
- return result;
- }
-
- private int idealIntArraySize(int need) {
- return idealByteArraySize(need * 4) / 4;
- }
-
- private int idealByteArraySize(int need) {
- for (int i = 4; i < 32; i++)
- if (need <= (1 << i) - 12)
- return (1 << i) - 12;
-
- return need;
- }
-
- private int binarySearch(int value) {
- int lo = 0;
- int hi = mSize - 1;
-
- while (lo <= hi) {
- int mid = (lo + hi) >>> 1;
- int midVal = mFieldNumbers[mid];
-
- if (midVal < value) {
- lo = mid + 1;
- } else if (midVal > value) {
- hi = mid - 1;
- } else {
- return mid; // value found
- }
- }
- return ~lo; // value not present
- }
-
- private boolean arrayEquals(int[] a, int[] b, int size) {
- for (int i = 0; i < size; i++) {
- if (a[i] != b[i]) {
- return false;
- }
- }
- return true;
- }
-
- private boolean arrayEquals(FieldData[] a, FieldData[] b, int size) {
- for (int i = 0; i < size; i++) {
- if (!a[i].equals(b[i])) {
- return false;
- }
- }
- return true;
- }
-
- @Override
- public final FieldArray clone() {
- // Trigger GC so we compact and don't copy DELETED elements.
- int size = size();
- FieldArray clone = new FieldArray(size);
- System.arraycopy(mFieldNumbers, 0, clone.mFieldNumbers, 0, size);
- for (int i = 0; i < size; i++) {
- if (mData[i] != null) {
- clone.mData[i] = mData[i].clone();
- }
- }
- clone.mSize = size;
- return clone;
- }
-}
diff --git a/javanano/src/main/java/com/google/protobuf/nano/FieldData.java b/javanano/src/main/java/com/google/protobuf/nano/FieldData.java
deleted file mode 100644
index ebebabc8..00000000
--- a/javanano/src/main/java/com/google/protobuf/nano/FieldData.java
+++ /dev/null
@@ -1,240 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2014 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package com.google.protobuf.nano;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * Stores unknown fields. These might be extensions or fields that the generated API doesn't
- * know about yet.
- */
-class FieldData implements Cloneable {
- private Extension<?, ?> cachedExtension;
- private Object value;
- /** The serialised values for this object. Will be cleared if getValue is called */
- private List<UnknownFieldData> unknownFieldData;
-
- <T> FieldData(Extension<?, T> extension, T newValue) {
- cachedExtension = extension;
- value = newValue;
- }
-
- FieldData() {
- unknownFieldData = new ArrayList<UnknownFieldData>();
- }
-
- void addUnknownField(UnknownFieldData unknownField) {
- unknownFieldData.add(unknownField);
- }
-
- UnknownFieldData getUnknownField(int index) {
- if (unknownFieldData == null) {
- return null;
- }
- if (index < unknownFieldData.size()) {
- return unknownFieldData.get(index);
- }
- return null;
- }
-
- int getUnknownFieldSize() {
- if (unknownFieldData == null) {
- return 0;
- }
- return unknownFieldData.size();
- }
-
- <T> T getValue(Extension<?, T> extension) {
- if (value != null){
- if (cachedExtension != extension) { // Extension objects are singletons.
- throw new IllegalStateException(
- "Tried to getExtension with a differernt Extension.");
- }
- } else {
- cachedExtension = extension;
- value = extension.getValueFrom(unknownFieldData);
- unknownFieldData = null;
- }
- return (T) value;
- }
-
- <T> void setValue(Extension<?, T> extension, T newValue) {
- cachedExtension = extension;
- value = newValue;
- unknownFieldData = null;
- }
-
- int computeSerializedSize() {
- int size = 0;
- if (value != null) {
- size = cachedExtension.computeSerializedSize(value);
- } else {
- for (UnknownFieldData unknownField : unknownFieldData) {
- size += unknownField.computeSerializedSize();
- }
- }
- return size;
- }
-
- void writeTo(CodedOutputByteBufferNano output) throws IOException {
- if (value != null) {
- cachedExtension.writeTo(value, output);
- } else {
- for (UnknownFieldData unknownField : unknownFieldData) {
- unknownField.writeTo(output);
- }
- }
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == this) {
- return true;
- }
- if (!(o instanceof FieldData)) {
- return false;
- }
-
- FieldData other = (FieldData) o;
- if (value != null && other.value != null) {
- // If both objects have deserialized values, compare those.
- // Since unknown fields are only compared if messages have generated equals methods
- // we know this will be a meaningful comparison (not identity) for all values.
- if (cachedExtension != other.cachedExtension) { // Extension objects are singletons.
- return false;
- }
- if (!cachedExtension.clazz.isArray()) {
- // Can't test (!cachedExtension.repeated) due to 'bytes' -> 'byte[]'
- return value.equals(other.value);
- }
- if (value instanceof byte[]) {
- return Arrays.equals((byte[]) value, (byte[]) other.value);
- } else if (value instanceof int[]) {
- return Arrays.equals((int[]) value, (int[]) other.value);
- } else if (value instanceof long[]) {
- return Arrays.equals((long[]) value, (long[]) other.value);
- } else if (value instanceof float[]) {
- return Arrays.equals((float[]) value, (float[]) other.value);
- } else if (value instanceof double[]) {
- return Arrays.equals((double[]) value, (double[]) other.value);
- } else if (value instanceof boolean[]) {
- return Arrays.equals((boolean[]) value, (boolean[]) other.value);
- } else {
- return Arrays.deepEquals((Object[]) value, (Object[]) other.value);
- }
- }
- if (unknownFieldData != null && other.unknownFieldData != null) {
- // If both objects have byte arrays compare those directly.
- return unknownFieldData.equals(other.unknownFieldData);
- }
- try {
- // As a last resort, serialize and compare the resulting byte arrays.
- return Arrays.equals(toByteArray(), other.toByteArray());
- } catch (IOException e) {
- // Should not happen.
- throw new IllegalStateException(e);
- }
- }
-
- @Override
- public int hashCode() {
- int result = 17;
- try {
- // The only way to generate a consistent hash is to use the serialized form.
- result = 31 * result + Arrays.hashCode(toByteArray());
- } catch (IOException e) {
- // Should not happen.
- throw new IllegalStateException(e);
- }
- return result;
- }
-
- private byte[] toByteArray() throws IOException {
- byte[] result = new byte[computeSerializedSize()];
- CodedOutputByteBufferNano output = CodedOutputByteBufferNano.newInstance(result);
- writeTo(output);
- return result;
- }
-
- @Override
- public final FieldData clone() {
- FieldData clone = new FieldData();
- try {
- clone.cachedExtension = cachedExtension;
- if (unknownFieldData == null) {
- clone.unknownFieldData = null;
- } else {
- clone.unknownFieldData.addAll(unknownFieldData);
- }
-
- // Whether we need to deep clone value depends on its type. Primitive reference types
- // (e.g. Integer, Long etc.) are ok, since they're immutable. We need to clone arrays
- // and messages.
- if (value == null) {
- // No cloning required.
- } else if (value instanceof MessageNano) {
- clone.value = ((MessageNano) value).clone();
- } else if (value instanceof byte[]) {
- clone.value = ((byte[]) value).clone();
- } else if (value instanceof byte[][]) {
- byte[][] valueArray = (byte[][]) value;
- byte[][] cloneArray = new byte[valueArray.length][];
- clone.value = cloneArray;
- for (int i = 0; i < valueArray.length; i++) {
- cloneArray[i] = valueArray[i].clone();
- }
- } else if (value instanceof boolean[]) {
- clone.value = ((boolean[]) value).clone();
- } else if (value instanceof int[]) {
- clone.value = ((int[]) value).clone();
- } else if (value instanceof long[]) {
- clone.value = ((long[]) value).clone();
- } else if (value instanceof float[]) {
- clone.value = ((float[]) value).clone();
- } else if (value instanceof double[]) {
- clone.value = ((double[]) value).clone();
- } else if (value instanceof MessageNano[]) {
- MessageNano[] valueArray = (MessageNano[]) value;
- MessageNano[] cloneArray = new MessageNano[valueArray.length];
- clone.value = cloneArray;
- for (int i = 0; i < valueArray.length; i++) {
- cloneArray[i] = valueArray[i].clone();
- }
- }
- return clone;
- } catch (CloneNotSupportedException e) {
- throw new AssertionError(e);
- }
- }
-}
diff --git a/javanano/src/main/java/com/google/protobuf/nano/InternalNano.java b/javanano/src/main/java/com/google/protobuf/nano/InternalNano.java
deleted file mode 100644
index 278368a0..00000000
--- a/javanano/src/main/java/com/google/protobuf/nano/InternalNano.java
+++ /dev/null
@@ -1,547 +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.
-
-package com.google.protobuf.nano;
-
-import com.google.protobuf.nano.MapFactories.MapFactory;
-
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.util.Arrays;
-import java.util.Map;
-import java.util.Map.Entry;
-
-/**
- * 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)
- */
-public final class InternalNano {
-
- public static final int TYPE_DOUBLE = 1;
- public static final int TYPE_FLOAT = 2;
- public static final int TYPE_INT64 = 3;
- public static final int TYPE_UINT64 = 4;
- public static final int TYPE_INT32 = 5;
- public static final int TYPE_FIXED64 = 6;
- public static final int TYPE_FIXED32 = 7;
- public static final int TYPE_BOOL = 8;
- public static final int TYPE_STRING = 9;
- public static final int TYPE_GROUP = 10;
- public static final int TYPE_MESSAGE = 11;
- public static final int TYPE_BYTES = 12;
- public static final int TYPE_UINT32 = 13;
- public static final int TYPE_ENUM = 14;
- public static final int TYPE_SFIXED32 = 15;
- public static final int TYPE_SFIXED64 = 16;
- public static final int TYPE_SINT32 = 17;
- public static final int TYPE_SINT64 = 18;
-
- static final Charset UTF_8 = Charset.forName("UTF-8");
- static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
-
- private InternalNano() {}
-
- /**
- * An object to provide synchronization when lazily initializing static fields
- * of {@link MessageNano} subclasses.
- * <p>
- * To enable earlier versions of ProGuard to inline short methods from a
- * generated MessageNano subclass to the call sites, that class must not have
- * a class initializer, which will be created if there is any static variable
- * initializers. To lazily initialize the static variables in a thread-safe
- * manner, the initialization code will synchronize on this object.
- */
- public static final Object LAZY_INIT_LOCK = new Object();
-
- /**
- * 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), InternalNano.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.
- */
- public static byte[] bytesDefaultValue(String bytes) {
- return bytes.getBytes(ISO_8859_1);
- }
-
- /**
- * Helper function to convert a string into UTF-8 while turning the
- * UnsupportedEncodingException to a RuntimeException.
- */
- public static byte[] copyFromUtf8(final String text) {
- return text.getBytes(InternalNano.UTF_8);
- }
-
- /**
- * Checks repeated int field equality; null-value and 0-length fields are
- * considered equal.
- */
- public static boolean equals(int[] field1, int[] field2) {
- if (field1 == null || field1.length == 0) {
- return field2 == null || field2.length == 0;
- } else {
- return Arrays.equals(field1, field2);
- }
- }
-
- /**
- * Checks repeated long field equality; null-value and 0-length fields are
- * considered equal.
- */
- public static boolean equals(long[] field1, long[] field2) {
- if (field1 == null || field1.length == 0) {
- return field2 == null || field2.length == 0;
- } else {
- return Arrays.equals(field1, field2);
- }
- }
-
- /**
- * Checks repeated float field equality; null-value and 0-length fields are
- * considered equal.
- */
- public static boolean equals(float[] field1, float[] field2) {
- if (field1 == null || field1.length == 0) {
- return field2 == null || field2.length == 0;
- } else {
- return Arrays.equals(field1, field2);
- }
- }
-
- /**
- * Checks repeated double field equality; null-value and 0-length fields are
- * considered equal.
- */
- public static boolean equals(double[] field1, double[] field2) {
- if (field1 == null || field1.length == 0) {
- return field2 == null || field2.length == 0;
- } else {
- return Arrays.equals(field1, field2);
- }
- }
-
- /**
- * Checks repeated boolean field equality; null-value and 0-length fields are
- * considered equal.
- */
- public static boolean equals(boolean[] field1, boolean[] field2) {
- if (field1 == null || field1.length == 0) {
- return field2 == null || field2.length == 0;
- } else {
- return Arrays.equals(field1, field2);
- }
- }
-
- /**
- * Checks repeated bytes field equality. Only non-null elements are tested.
- * Returns true if the two fields have the same sequence of non-null
- * elements. Null-value fields and fields of any length with only null
- * elements are considered equal.
- */
- public static boolean equals(byte[][] field1, byte[][] field2) {
- int index1 = 0;
- int length1 = field1 == null ? 0 : field1.length;
- int index2 = 0;
- int length2 = field2 == null ? 0 : field2.length;
- while (true) {
- while (index1 < length1 && field1[index1] == null) {
- index1++;
- }
- while (index2 < length2 && field2[index2] == null) {
- index2++;
- }
- boolean atEndOf1 = index1 >= length1;
- boolean atEndOf2 = index2 >= length2;
- if (atEndOf1 && atEndOf2) {
- // no more non-null elements to test in both arrays
- return true;
- } else if (atEndOf1 != atEndOf2) {
- // one of the arrays have extra non-null elements
- return false;
- } else if (!Arrays.equals(field1[index1], field2[index2])) {
- // element mismatch
- return false;
- }
- index1++;
- index2++;
- }
- }
-
- /**
- * Checks repeated string/message field equality. Only non-null elements are
- * tested. Returns true if the two fields have the same sequence of non-null
- * elements. Null-value fields and fields of any length with only null
- * elements are considered equal.
- */
- public static boolean equals(Object[] field1, Object[] field2) {
- int index1 = 0;
- int length1 = field1 == null ? 0 : field1.length;
- int index2 = 0;
- int length2 = field2 == null ? 0 : field2.length;
- while (true) {
- while (index1 < length1 && field1[index1] == null) {
- index1++;
- }
- while (index2 < length2 && field2[index2] == null) {
- index2++;
- }
- boolean atEndOf1 = index1 >= length1;
- boolean atEndOf2 = index2 >= length2;
- if (atEndOf1 && atEndOf2) {
- // no more non-null elements to test in both arrays
- return true;
- } else if (atEndOf1 != atEndOf2) {
- // one of the arrays have extra non-null elements
- return false;
- } else if (!field1[index1].equals(field2[index2])) {
- // element mismatch
- return false;
- }
- index1++;
- index2++;
- }
- }
-
- /**
- * Computes the hash code of a repeated int field. Null-value and 0-length
- * fields have the same hash code.
- */
- public static int hashCode(int[] field) {
- return field == null || field.length == 0 ? 0 : Arrays.hashCode(field);
- }
-
- /**
- * Computes the hash code of a repeated long field. Null-value and 0-length
- * fields have the same hash code.
- */
- public static int hashCode(long[] field) {
- return field == null || field.length == 0 ? 0 : Arrays.hashCode(field);
- }
-
- /**
- * Computes the hash code of a repeated float field. Null-value and 0-length
- * fields have the same hash code.
- */
- public static int hashCode(float[] field) {
- return field == null || field.length == 0 ? 0 : Arrays.hashCode(field);
- }
-
- /**
- * Computes the hash code of a repeated double field. Null-value and 0-length
- * fields have the same hash code.
- */
- public static int hashCode(double[] field) {
- return field == null || field.length == 0 ? 0 : Arrays.hashCode(field);
- }
-
- /**
- * Computes the hash code of a repeated boolean field. Null-value and 0-length
- * fields have the same hash code.
- */
- public static int hashCode(boolean[] field) {
- return field == null || field.length == 0 ? 0 : Arrays.hashCode(field);
- }
-
- /**
- * Computes the hash code of a repeated bytes field. Only the sequence of all
- * non-null elements are used in the computation. Null-value fields and fields
- * of any length with only null elements have the same hash code.
- */
- public static int hashCode(byte[][] field) {
- int result = 0;
- for (int i = 0, size = field == null ? 0 : field.length; i < size; i++) {
- byte[] element = field[i];
- if (element != null) {
- result = 31 * result + Arrays.hashCode(element);
- }
- }
- return result;
- }
-
- /**
- * Computes the hash code of a repeated string/message field. Only the
- * sequence of all non-null elements are used in the computation. Null-value
- * fields and fields of any length with only null elements have the same hash
- * code.
- */
- public static int hashCode(Object[] field) {
- int result = 0;
- for (int i = 0, size = field == null ? 0 : field.length; i < size; i++) {
- Object element = field[i];
- if (element != null) {
- result = 31 * result + element.hashCode();
- }
- }
- return result;
- }
- private static Object primitiveDefaultValue(int type) {
- switch (type) {
- case TYPE_BOOL:
- return Boolean.FALSE;
- case TYPE_BYTES:
- return WireFormatNano.EMPTY_BYTES;
- case TYPE_STRING:
- return "";
- case TYPE_FLOAT:
- return Float.valueOf(0);
- case TYPE_DOUBLE:
- return Double.valueOf(0);
- case TYPE_ENUM:
- case TYPE_FIXED32:
- case TYPE_INT32:
- case TYPE_UINT32:
- case TYPE_SINT32:
- case TYPE_SFIXED32:
- return Integer.valueOf(0);
- case TYPE_INT64:
- case TYPE_UINT64:
- case TYPE_SINT64:
- case TYPE_FIXED64:
- case TYPE_SFIXED64:
- return Long.valueOf(0L);
- case TYPE_MESSAGE:
- case TYPE_GROUP:
- default:
- throw new IllegalArgumentException(
- "Type: " + type + " is not a primitive type.");
- }
- }
-
- /**
- * Merges the map entry into the map field. Note this is only supposed to
- * be called by generated messages.
- *
- * @param map the map field; may be null, in which case a map will be
- * instantiated using the {@link MapFactories.MapFactory}
- * @param input the input byte buffer
- * @param keyType key type, as defined in InternalNano.TYPE_*
- * @param valueType value type, as defined in InternalNano.TYPE_*
- * @param value an new instance of the value, if the value is a TYPE_MESSAGE;
- * otherwise this parameter can be null and will be ignored.
- * @param keyTag wire tag for the key
- * @param valueTag wire tag for the value
- * @return the map field
- * @throws IOException
- */
- @SuppressWarnings("unchecked")
- public static final <K, V> Map<K, V> mergeMapEntry(
- CodedInputByteBufferNano input,
- Map<K, V> map,
- MapFactory mapFactory,
- int keyType,
- int valueType,
- V value,
- int keyTag,
- int valueTag) throws IOException {
- map = mapFactory.forMap(map);
- final int length = input.readRawVarint32();
- final int oldLimit = input.pushLimit(length);
- K key = null;
- while (true) {
- int tag = input.readTag();
- if (tag == 0) {
- break;
- }
- if (tag == keyTag) {
- key = (K) input.readPrimitiveField(keyType);
- } else if (tag == valueTag) {
- if (valueType == TYPE_MESSAGE) {
- input.readMessage((MessageNano) value);
- } else {
- value = (V) input.readPrimitiveField(valueType);
- }
- } else {
- if (!input.skipField(tag)) {
- break;
- }
- }
- }
- input.checkLastTagWas(0);
- input.popLimit(oldLimit);
-
- if (key == null) {
- // key can only be primitive types.
- key = (K) primitiveDefaultValue(keyType);
- }
-
- if (value == null) {
- // message type value will be initialized by code-gen.
- value = (V) primitiveDefaultValue(valueType);
- }
-
- map.put(key, value);
- return map;
- }
-
- public static <K, V> void serializeMapField(
- CodedOutputByteBufferNano output,
- Map<K, V> map, int number, int keyType, int valueType)
- throws IOException {
- for (Entry<K, V> entry: map.entrySet()) {
- K key = entry.getKey();
- V value = entry.getValue();
- if (key == null || value == null) {
- throw new IllegalStateException(
- "keys and values in maps cannot be null");
- }
- int entrySize =
- CodedOutputByteBufferNano.computeFieldSize(1, keyType, key) +
- CodedOutputByteBufferNano.computeFieldSize(2, valueType, value);
- output.writeTag(number, WireFormatNano.WIRETYPE_LENGTH_DELIMITED);
- output.writeRawVarint32(entrySize);
- output.writeField(1, keyType, key);
- output.writeField(2, valueType, value);
- }
- }
-
- public static <K, V> int computeMapFieldSize(
- Map<K, V> map, int number, int keyType, int valueType) {
- int size = 0;
- int tagSize = CodedOutputByteBufferNano.computeTagSize(number);
- for (Entry<K, V> entry: map.entrySet()) {
- K key = entry.getKey();
- V value = entry.getValue();
- if (key == null || value == null) {
- throw new IllegalStateException(
- "keys and values in maps cannot be null");
- }
- int entrySize =
- CodedOutputByteBufferNano.computeFieldSize(1, keyType, key) +
- CodedOutputByteBufferNano.computeFieldSize(2, valueType, value);
- size += tagSize + entrySize
- + CodedOutputByteBufferNano.computeRawVarint32Size(entrySize);
- }
- return size;
- }
-
- /**
- * Checks whether two {@link Map} are equal. We don't use the default equals
- * method of {@link Map} because it compares by identity not by content for
- * byte arrays.
- */
- public static <K, V> boolean equals(Map<K, V> a, Map<K, V> b) {
- if (a == b) {
- return true;
- }
- if (a == null) {
- return b.size() == 0;
- }
- if (b == null) {
- return a.size() == 0;
- }
- if (a.size() != b.size()) {
- return false;
- }
- for (Entry<K, V> entry : a.entrySet()) {
- if (!b.containsKey(entry.getKey())) {
- return false;
- }
- if (!equalsMapValue(entry.getValue(), b.get(entry.getKey()))) {
- return false;
- }
- }
- return true;
- }
-
- private static boolean equalsMapValue(Object a, Object b) {
- if (a == null || b == null) {
- throw new IllegalStateException(
- "keys and values in maps cannot be null");
- }
- if (a instanceof byte[] && b instanceof byte[]) {
- return Arrays.equals((byte[]) a, (byte[]) b);
- }
- return a.equals(b);
- }
-
- public static <K, V> int hashCode(Map<K, V> map) {
- if (map == null) {
- return 0;
- }
- int result = 0;
- for (Entry<K, V> entry : map.entrySet()) {
- result += hashCodeForMap(entry.getKey())
- ^ hashCodeForMap(entry.getValue());
- }
- return result;
- }
-
- private static int hashCodeForMap(Object o) {
- if (o instanceof byte[]) {
- return Arrays.hashCode((byte[]) o);
- }
- return o.hashCode();
- }
-
- // This avoids having to make FieldArray public.
- public static void cloneUnknownFieldData(ExtendableMessageNano original,
- ExtendableMessageNano cloned) {
- if (original.unknownFieldData != null) {
- cloned.unknownFieldData = (FieldArray) original.unknownFieldData.clone();
- }
- }
-}
diff --git a/javanano/src/main/java/com/google/protobuf/nano/InvalidProtocolBufferNanoException.java b/javanano/src/main/java/com/google/protobuf/nano/InvalidProtocolBufferNanoException.java
deleted file mode 100644
index 9a83d6d3..00000000
--- a/javanano/src/main/java/com/google/protobuf/nano/InvalidProtocolBufferNanoException.java
+++ /dev/null
@@ -1,93 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2013 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package com.google.protobuf.nano;
-
-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.
- *
- * @author kenton@google.com Kenton Varda
- */
-public class InvalidProtocolBufferNanoException extends IOException {
- private static final long serialVersionUID = -1616151763072450476L;
-
- public InvalidProtocolBufferNanoException(final String description) {
- super(description);
- }
-
- static InvalidProtocolBufferNanoException truncatedMessage() {
- return new InvalidProtocolBufferNanoException(
- "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 InvalidProtocolBufferNanoException negativeSize() {
- return new InvalidProtocolBufferNanoException(
- "CodedInputStream encountered an embedded string or message " +
- "which claimed to have negative size.");
- }
-
- static InvalidProtocolBufferNanoException malformedVarint() {
- return new InvalidProtocolBufferNanoException(
- "CodedInputStream encountered a malformed varint.");
- }
-
- static InvalidProtocolBufferNanoException invalidTag() {
- return new InvalidProtocolBufferNanoException(
- "Protocol message contained an invalid tag (zero).");
- }
-
- static InvalidProtocolBufferNanoException invalidEndTag() {
- return new InvalidProtocolBufferNanoException(
- "Protocol message end-group tag did not match expected tag.");
- }
-
- static InvalidProtocolBufferNanoException invalidWireType() {
- return new InvalidProtocolBufferNanoException(
- "Protocol message tag had invalid wire type.");
- }
-
- static InvalidProtocolBufferNanoException recursionLimitExceeded() {
- return new InvalidProtocolBufferNanoException(
- "Protocol message had too many levels of nesting. May be malicious. " +
- "Use CodedInputStream.setRecursionLimit() to increase the depth limit.");
- }
-
- static InvalidProtocolBufferNanoException sizeLimitExceeded() {
- return new InvalidProtocolBufferNanoException(
- "Protocol message was too large. May be malicious. " +
- "Use CodedInputStream.setSizeLimit() to increase the size limit.");
- }
-}
diff --git a/javanano/src/main/java/com/google/protobuf/nano/MapFactories.java b/javanano/src/main/java/com/google/protobuf/nano/MapFactories.java
deleted file mode 100644
index 98fa4877..00000000
--- a/javanano/src/main/java/com/google/protobuf/nano/MapFactories.java
+++ /dev/null
@@ -1,67 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2013 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package com.google.protobuf.nano;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Utility class for maps support.
- */
-public final class MapFactories {
- public static interface MapFactory {
- <K, V> Map<K, V> forMap(Map<K, V> oldMap);
- }
-
- // NOTE(liujisi): The factory setter is temporarily marked as package private.
- // The way to provide customized implementations of maps for different
- // platforms are still under discussion. Mark it as private to avoid exposing
- // the API in proto3 alpha release.
- /* public */ static void setMapFactory(MapFactory newMapFactory) {
- mapFactory = newMapFactory;
- }
-
- public static MapFactory getMapFactory() {
- return mapFactory;
- }
-
- private static class DefaultMapFactory implements MapFactory {
- public <K, V> Map<K, V> forMap(Map<K, V> oldMap) {
- if (oldMap == null) {
- return new HashMap<K, V>();
- }
- return oldMap;
- }
- }
- private static volatile MapFactory mapFactory = new DefaultMapFactory();
-
- private MapFactories() {}
-}
diff --git a/javanano/src/main/java/com/google/protobuf/nano/MessageNano.java b/javanano/src/main/java/com/google/protobuf/nano/MessageNano.java
deleted file mode 100644
index 23475027..00000000
--- a/javanano/src/main/java/com/google/protobuf/nano/MessageNano.java
+++ /dev/null
@@ -1,198 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2013 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package com.google.protobuf.nano;
-
-import java.io.IOException;
-import java.util.Arrays;
-
-/**
- * Abstract interface implemented by Protocol Message objects.
- *
- * @author wink@google.com Wink Saville
- */
-public abstract class MessageNano {
- protected volatile int cachedSize = -1;
-
- /**
- * Get the number of bytes required to encode this message.
- * Returns the cached size or calls getSerializedSize which
- * sets the cached size. This is used internally when serializing
- * so the size is only computed once. If a member is modified
- * then this could be stale call getSerializedSize if in doubt.
- */
- public int getCachedSize() {
- if (cachedSize < 0) {
- // getSerializedSize sets cachedSize
- getSerializedSize();
- }
- return cachedSize;
- }
-
- /**
- * Computes the number of bytes required to encode this message.
- * The size is cached and the cached result can be retrieved
- * using getCachedSize().
- */
- public int getSerializedSize() {
- int size = computeSerializedSize();
- cachedSize = size;
- return size;
- }
-
- /**
- * Computes the number of bytes required to encode this message. This does not update the
- * cached size.
- */
- protected int computeSerializedSize() {
- // This is overridden if the generated message has serialized fields.
- return 0;
- }
-
- /**
- * Serializes the message and writes it to {@code output}.
- *
- * @param output the output to receive the serialized form.
- * @throws IOException if an error occurred writing to {@code output}.
- */
- public void writeTo(CodedOutputByteBufferNano output) throws IOException {
- // Does nothing by default. Overridden by subclasses which have data to write.
- }
-
- /**
- * Parse {@code input} as a message of this type and merge it with the
- * message being built.
- */
- public abstract MessageNano mergeFrom(CodedInputByteBufferNano input) throws IOException;
-
- /**
- * Serialize to a byte array.
- * @return byte array with the serialized data.
- */
- public static final byte[] toByteArray(MessageNano msg) {
- final byte[] result = new byte[msg.getSerializedSize()];
- toByteArray(msg, result, 0, result.length);
- return result;
- }
-
- /**
- * Serialize to a byte array starting at offset through length. The
- * method getSerializedSize must have been called prior to calling
- * this method so the proper length is know. If an attempt to
- * write more than length bytes OutOfSpaceException will be thrown
- * and if length bytes are not written then IllegalStateException
- * is thrown.
- */
- public static final void toByteArray(MessageNano msg, byte[] data, int offset, int length) {
- try {
- final CodedOutputByteBufferNano output =
- CodedOutputByteBufferNano.newInstance(data, offset, length);
- msg.writeTo(output);
- output.checkNoSpaceLeft();
- } catch (IOException e) {
- throw new RuntimeException("Serializing to a byte array threw an IOException "
- + "(should never happen).", e);
- }
- }
-
- /**
- * Parse {@code data} as a message of this type and merge it with the
- * message being built.
- */
- public static final <T extends MessageNano> T mergeFrom(T msg, final byte[] data)
- throws InvalidProtocolBufferNanoException {
- return mergeFrom(msg, data, 0, data.length);
- }
-
- /**
- * Parse {@code data} as a message of this type and merge it with the
- * message being built.
- */
- public static final <T extends MessageNano> T mergeFrom(T msg, final byte[] data,
- final int off, final int len) throws InvalidProtocolBufferNanoException {
- try {
- final CodedInputByteBufferNano input =
- CodedInputByteBufferNano.newInstance(data, off, len);
- msg.mergeFrom(input);
- input.checkLastTagWas(0);
- return msg;
- } catch (InvalidProtocolBufferNanoException e) {
- throw e;
- } catch (IOException e) {
- throw new RuntimeException("Reading from a byte array threw an IOException (should "
- + "never happen).");
- }
- }
-
- /**
- * Compares two {@code MessageNano}s and returns true if the message's are the same class and
- * have serialized form equality (i.e. all of the field values are the same).
- */
- public static final boolean messageNanoEquals(MessageNano a, MessageNano b) {
- if (a == b) {
- return true;
- }
- if (a == null || b == null) {
- return false;
- }
- if (a.getClass() != b.getClass()) {
- return false;
- }
- final int serializedSize = a.getSerializedSize();
- if (b.getSerializedSize() != serializedSize) {
- return false;
- }
- final byte[] aByteArray = new byte[serializedSize];
- final byte[] bByteArray = new byte[serializedSize];
- toByteArray(a, aByteArray, 0, serializedSize);
- toByteArray(b, bByteArray, 0, serializedSize);
- return Arrays.equals(aByteArray, bByteArray);
- }
-
- /**
- * Returns a string that is (mostly) compatible with ProtoBuffer's TextFormat. Note that groups
- * (which are deprecated) are not serialized with the correct field name.
- *
- * <p>This is implemented using reflection, so it is not especially fast nor is it guaranteed
- * to find all fields if you have method removal turned on for proguard.
- */
- @Override
- public String toString() {
- return MessageNanoPrinter.print(this);
- }
-
- /**
- * Provides support for cloning. This only works if you specify the generate_clone method.
- */
- @Override
- public MessageNano clone() throws CloneNotSupportedException {
- return (MessageNano) super.clone();
- }
-}
diff --git a/javanano/src/main/java/com/google/protobuf/nano/MessageNanoPrinter.java b/javanano/src/main/java/com/google/protobuf/nano/MessageNanoPrinter.java
deleted file mode 100644
index 5f329f02..00000000
--- a/javanano/src/main/java/com/google/protobuf/nano/MessageNanoPrinter.java
+++ /dev/null
@@ -1,275 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2013 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package com.google.protobuf.nano;
-
-import java.lang.reflect.Array;
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.Map;
-
-/**
- * Static helper methods for printing nano protos.
- *
- * @author flynn@google.com Andrew Flynn
- */
-public final class MessageNanoPrinter {
- // Do not allow instantiation
- private MessageNanoPrinter() {}
-
- private static final String INDENT = " ";
- private static final int MAX_STRING_LEN = 200;
-
- /**
- * Returns an text representation of a MessageNano suitable for debugging. The returned string
- * is mostly compatible with Protocol Buffer's TextFormat (as provided by non-nano protocol
- * buffers) -- groups (which are deprecated) are output with an underscore name (e.g. foo_bar
- * instead of FooBar) and will thus not parse.
- *
- * <p>Employs Java reflection on the given object and recursively prints primitive fields,
- * groups, and messages.</p>
- */
- public static <T extends MessageNano> String print(T message) {
- if (message == null) {
- return "";
- }
-
- StringBuffer buf = new StringBuffer();
- try {
- print(null, message, new StringBuffer(), buf);
- } catch (IllegalAccessException e) {
- return "Error printing proto: " + e.getMessage();
- } catch (InvocationTargetException e) {
- return "Error printing proto: " + e.getMessage();
- }
- return buf.toString();
- }
-
- /**
- * Function that will print the given message/field into the StringBuffer.
- * Meant to be called recursively.
- *
- * @param identifier the identifier to use, or {@code null} if this is the root message to
- * print.
- * @param object the value to print. May in fact be a primitive value or byte array and not a
- * message.
- * @param indentBuf the indentation each line should begin with.
- * @param buf the output buffer.
- */
- private static void print(String identifier, Object object,
- StringBuffer indentBuf, StringBuffer buf) throws IllegalAccessException,
- InvocationTargetException {
- if (object == null) {
- // This can happen if...
- // - we're about to print a message, String, or byte[], but it not present;
- // - we're about to print a primitive, but "reftype" optional style is enabled, and
- // the field is unset.
- // In both cases the appropriate behavior is to output nothing.
- } else if (object instanceof MessageNano) { // Nano proto message
- int origIndentBufLength = indentBuf.length();
- if (identifier != null) {
- buf.append(indentBuf).append(deCamelCaseify(identifier)).append(" <\n");
- indentBuf.append(INDENT);
- }
- Class<?> clazz = object.getClass();
-
- // Proto fields follow one of two formats:
- //
- // 1) Public, non-static variables that do not begin or end with '_'
- // Find and print these using declared public fields
- for (Field field : clazz.getFields()) {
- int modifiers = field.getModifiers();
- String fieldName = field.getName();
- if ("cachedSize".equals(fieldName)) {
- // TODO(bduff): perhaps cachedSize should have a more obscure name.
- continue;
- }
-
- if ((modifiers & Modifier.PUBLIC) == Modifier.PUBLIC
- && (modifiers & Modifier.STATIC) != Modifier.STATIC
- && !fieldName.startsWith("_")
- && !fieldName.endsWith("_")) {
- Class<?> fieldType = field.getType();
- Object value = field.get(object);
-
- if (fieldType.isArray()) {
- Class<?> arrayType = fieldType.getComponentType();
-
- // bytes is special since it's not repeated, but is represented by an array
- if (arrayType == byte.class) {
- print(fieldName, value, indentBuf, buf);
- } else {
- int len = value == null ? 0 : Array.getLength(value);
- for (int i = 0; i < len; i++) {
- Object elem = Array.get(value, i);
- print(fieldName, elem, indentBuf, buf);
- }
- }
- } else {
- print(fieldName, value, indentBuf, buf);
- }
- }
- }
-
- // 2) Fields that are accessed via getter methods (when accessors
- // mode is turned on)
- // Find and print these using getter methods.
- for (Method method : clazz.getMethods()) {
- String name = method.getName();
- // Check for the setter accessor method since getters and hazzers both have
- // non-proto-field name collisions (hashCode() and getSerializedSize())
- if (name.startsWith("set")) {
- String subfieldName = name.substring(3);
-
- Method hazzer = null;
- try {
- hazzer = clazz.getMethod("has" + subfieldName);
- } catch (NoSuchMethodException e) {
- continue;
- }
- // If hazzer doesn't exist or returns false, no need to continue
- if (!(Boolean) hazzer.invoke(object)) {
- continue;
- }
-
- Method getter = null;
- try {
- getter = clazz.getMethod("get" + subfieldName);
- } catch (NoSuchMethodException e) {
- continue;
- }
-
- print(subfieldName, getter.invoke(object), indentBuf, buf);
- }
- }
- if (identifier != null) {
- indentBuf.setLength(origIndentBufLength);
- buf.append(indentBuf).append(">\n");
- }
- } else if (object instanceof Map) {
- Map<?,?> map = (Map<?,?>) object;
- identifier = deCamelCaseify(identifier);
-
- for (Map.Entry<?,?> entry : map.entrySet()) {
- buf.append(indentBuf).append(identifier).append(" <\n");
- int origIndentBufLength = indentBuf.length();
- indentBuf.append(INDENT);
- print("key", entry.getKey(), indentBuf, buf);
- print("value", entry.getValue(), indentBuf, buf);
- indentBuf.setLength(origIndentBufLength);
- buf.append(indentBuf).append(">\n");
- }
- } else {
- // Non-null primitive value
- identifier = deCamelCaseify(identifier);
- buf.append(indentBuf).append(identifier).append(": ");
- if (object instanceof String) {
- String stringMessage = sanitizeString((String) object);
- buf.append("\"").append(stringMessage).append("\"");
- } else if (object instanceof byte[]) {
- appendQuotedBytes((byte[]) object, buf);
- } else {
- buf.append(object);
- }
- buf.append("\n");
- }
- }
-
- /**
- * Converts an identifier of the format "FieldName" into "field_name".
- */
- private static String deCamelCaseify(String identifier) {
- StringBuffer out = new StringBuffer();
- for (int i = 0; i < identifier.length(); i++) {
- char currentChar = identifier.charAt(i);
- if (i == 0) {
- out.append(Character.toLowerCase(currentChar));
- } else if (Character.isUpperCase(currentChar)) {
- out.append('_').append(Character.toLowerCase(currentChar));
- } else {
- out.append(currentChar);
- }
- }
- return out.toString();
- }
-
- /**
- * Shortens and escapes the given string.
- */
- private static String sanitizeString(String str) {
- if (!str.startsWith("http") && str.length() > MAX_STRING_LEN) {
- // Trim non-URL strings.
- str = str.substring(0, MAX_STRING_LEN) + "[...]";
- }
- return escapeString(str);
- }
-
- /**
- * Escape everything except for low ASCII code points.
- */
- private static String escapeString(String str) {
- int strLen = str.length();
- StringBuilder b = new StringBuilder(strLen);
- for (int i = 0; i < strLen; i++) {
- char original = str.charAt(i);
- if (original >= ' ' && original <= '~' && original != '"' && original != '\'') {
- b.append(original);
- } else {
- b.append(String.format("\\u%04x", (int) original));
- }
- }
- return b.toString();
- }
-
- /**
- * Appends a quoted byte array to the provided {@code StringBuffer}.
- */
- private static void appendQuotedBytes(byte[] bytes, StringBuffer builder) {
- if (bytes == null) {
- builder.append("\"\"");
- return;
- }
-
- builder.append('"');
- for (int i = 0; i < bytes.length; ++i) {
- int ch = bytes[i] & 0xff;
- if (ch == '\\' || ch == '"') {
- builder.append('\\').append((char) ch);
- } else if (ch >= 32 && ch < 127) {
- builder.append((char) ch);
- } else {
- builder.append(String.format("\\%03o", ch));
- }
- }
- builder.append('"');
- }
-}
diff --git a/javanano/src/main/java/com/google/protobuf/nano/UnknownFieldData.java b/javanano/src/main/java/com/google/protobuf/nano/UnknownFieldData.java
deleted file mode 100644
index b1678d1b..00000000
--- a/javanano/src/main/java/com/google/protobuf/nano/UnknownFieldData.java
+++ /dev/null
@@ -1,88 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2013 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package com.google.protobuf.nano;
-
-import java.io.IOException;
-import java.util.Arrays;
-
-/**
- * Stores unknown fields. These might be extensions or fields that the generated
- * API doesn't know about yet.
- *
- * @author bduff@google.com (Brian Duff)
- */
-final class UnknownFieldData {
-
- final int tag;
- /**
- * Important: this should be treated as immutable, even though it's possible
- * to change the array values.
- */
- final byte[] bytes;
-
- UnknownFieldData(int tag, byte[] bytes) {
- this.tag = tag;
- this.bytes = bytes;
- }
-
- int computeSerializedSize() {
- int size = 0;
- size += CodedOutputByteBufferNano.computeRawVarint32Size(tag);
- size += bytes.length;
- return size;
- }
-
- void writeTo(CodedOutputByteBufferNano output) throws IOException {
- output.writeRawVarint32(tag);
- output.writeRawBytes(bytes);
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == this) {
- return true;
- }
- if (!(o instanceof UnknownFieldData)) {
- return false;
- }
-
- UnknownFieldData other = (UnknownFieldData) o;
- return tag == other.tag && Arrays.equals(bytes, other.bytes);
- }
-
- @Override
- public int hashCode() {
- int result = 17;
- result = 31 * result + tag;
- result = 31 * result + Arrays.hashCode(bytes);
- return result;
- }
-}
diff --git a/javanano/src/main/java/com/google/protobuf/nano/WireFormatNano.java b/javanano/src/main/java/com/google/protobuf/nano/WireFormatNano.java
deleted file mode 100644
index bbb6370a..00000000
--- a/javanano/src/main/java/com/google/protobuf/nano/WireFormatNano.java
+++ /dev/null
@@ -1,124 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2013 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package com.google.protobuf.nano;
-
-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 contains constants and helper functions useful for dealing with
- * the Protocol Buffer wire format.
- *
- * @author kenton@google.com Kenton Varda
- */
-public final class WireFormatNano {
- // Do not allow instantiation.
- private WireFormatNano() {}
-
- static final int WIRETYPE_VARINT = 0;
- static final int WIRETYPE_FIXED64 = 1;
- static final int WIRETYPE_LENGTH_DELIMITED = 2;
- static final int WIRETYPE_START_GROUP = 3;
- static final int WIRETYPE_END_GROUP = 4;
- static final int WIRETYPE_FIXED32 = 5;
-
- static final int TAG_TYPE_BITS = 3;
- static final int TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1;
-
- /** Given a tag value, determines the wire type (the lower 3 bits). */
- static int getTagWireType(final int tag) {
- return tag & TAG_TYPE_MASK;
- }
-
- /** Given a tag value, determines the field number (the upper 29 bits). */
- public static int getTagFieldNumber(final int tag) {
- return tag >>> TAG_TYPE_BITS;
- }
-
- /** Makes a tag value given a field number and wire type. */
- static int makeTag(final int fieldNumber, final int wireType) {
- return (fieldNumber << TAG_TYPE_BITS) | wireType;
- }
-
- public static final int EMPTY_INT_ARRAY[] = {};
- public static final long EMPTY_LONG_ARRAY[] = {};
- public static final float EMPTY_FLOAT_ARRAY[] = {};
- public static final double EMPTY_DOUBLE_ARRAY[] = {};
- public static final boolean EMPTY_BOOLEAN_ARRAY[] = {};
- public static final String EMPTY_STRING_ARRAY[] = {};
- public static final byte[] EMPTY_BYTES_ARRAY[] = {};
- public static final byte[] EMPTY_BYTES = {};
-
- /**
- * Parses an unknown field. This implementation skips the field.
- *
- * <p>Generated messages will call this for unknown fields if the store_unknown_fields
- * option is off.
- *
- * @return {@literal true} unless the tag is an end-group tag.
- */
- public static boolean parseUnknownField(
- final CodedInputByteBufferNano input,
- final int tag) throws IOException {
- return input.skipField(tag);
- }
-
- /**
- * Computes the array length of a repeated field. We assume that in the common case repeated
- * fields are contiguously serialized but we still correctly handle interspersed values of a
- * repeated field (but with extra allocations).
- *
- * Rewinds to current input position before returning.
- *
- * @param input stream input, pointing to the byte after the first tag
- * @param tag repeated field tag just read
- * @return length of array
- * @throws IOException
- */
- public static final int getRepeatedFieldArrayLength(
- final CodedInputByteBufferNano input,
- final int tag) throws IOException {
- int arrayLength = 1;
- int startPos = input.getPosition();
- input.skipField(tag);
- while (input.readTag() == tag) {
- input.skipField(tag);
- arrayLength++;
- }
- input.rewindToPosition(startPos);
- return arrayLength;
- }
-
-}
diff --git a/javanano/src/test/java/com/google/protobuf/nano/NanoTest.java b/javanano/src/test/java/com/google/protobuf/nano/NanoTest.java
deleted file mode 100644
index 4d6e7f09..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/NanoTest.java
+++ /dev/null
@@ -1,4471 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2013 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package com.google.protobuf.nano;
-
-import com.google.protobuf.nano.CodedOutputByteBufferNano;
-import com.google.protobuf.nano.EnumClassNanos.EnumClassNano;
-import com.google.protobuf.nano.EnumClassNanos.EnumClassNano.MessageScopeEnum;
-import com.google.protobuf.nano.EnumClassNanos.FileScopeEnum;
-import com.google.protobuf.nano.MapTestProto.TestMap;
-import com.google.protobuf.nano.MapTestProto.TestMap.MessageValue;
-import com.google.protobuf.nano.NanoAccessorsOuterClass.TestNanoAccessors;
-import com.google.protobuf.nano.NanoHasOuterClass.TestAllTypesNanoHas;
-import com.google.protobuf.nano.NanoOuterClass.TestAllTypesNano;
-import com.google.protobuf.nano.UnittestRecursiveNano.RecursiveMessageNano;
-import com.google.protobuf.nano.NanoReferenceTypesCompat;
-import com.google.protobuf.nano.UnittestSimpleNano.SimpleMessageNano;
-import com.google.protobuf.nano.UnittestSingleNano.SingleMessageNano;
-import com.google.protobuf.nano.testext.nano.Extensions;
-import com.google.protobuf.nano.testext.nano.Extensions.AnotherMessage;
-import com.google.protobuf.nano.testext.nano.Extensions.MessageWithGroup;
-import com.google.protobuf.nano.testimport.nano.UnittestImportNano;
-
-import junit.framework.TestCase;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.TreeMap;
-
-/**
- * Test nano runtime.
- *
- * @author ulas@google.com Ulas Kirazci
- */
-public class NanoTest extends TestCase {
- @Override
- public void setUp() throws Exception {
- }
-
- public void testSimpleMessageNano() throws Exception {
- SimpleMessageNano msg = new SimpleMessageNano();
- assertEquals(123, msg.d);
- assertEquals(null, msg.nestedMsg);
- assertEquals(SimpleMessageNano.BAZ, msg.defaultNestedEnum);
-
- msg.d = 456;
- assertEquals(456, msg.d);
-
- SimpleMessageNano.NestedMessage nestedMsg = new SimpleMessageNano.NestedMessage();
- nestedMsg.bb = 2;
- assertEquals(2, nestedMsg.bb);
- msg.nestedMsg = nestedMsg;
- assertEquals(2, msg.nestedMsg.bb);
-
- msg.defaultNestedEnum = SimpleMessageNano.BAR;
- assertEquals(SimpleMessageNano.BAR, msg.defaultNestedEnum);
-
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 9);
- assertEquals(result.length, msgSerializedSize);
-
- SimpleMessageNano newMsg = SimpleMessageNano.parseFrom(result);
- assertEquals(456, newMsg.d);
- assertEquals(2, msg.nestedMsg.bb);
- assertEquals(SimpleMessageNano.BAR, msg.defaultNestedEnum);
-
- msg.nestedMsg = null;
- assertTrue(msgSerializedSize != msg.getSerializedSize());
-
- msg.clear();
- assertEquals(0, msg.getSerializedSize());
- }
-
- public void testRecursiveMessageNano() throws Exception {
- RecursiveMessageNano msg = new RecursiveMessageNano();
- assertTrue(msg.repeatedRecursiveMessageNano.length == 0);
-
- RecursiveMessageNano msg1 = new RecursiveMessageNano();
- msg1.id = 1;
- assertEquals(1, msg1.id);
- RecursiveMessageNano msg2 = new RecursiveMessageNano();
- msg2.id = 2;
- RecursiveMessageNano msg3 = new RecursiveMessageNano();
- msg3.id = 3;
-
- RecursiveMessageNano.NestedMessage nestedMsg = new RecursiveMessageNano.NestedMessage();
- nestedMsg.a = msg1;
- assertEquals(1, nestedMsg.a.id);
-
- msg.id = 0;
- msg.nestedMessage = nestedMsg;
- msg.optionalRecursiveMessageNano = msg2;
- msg.repeatedRecursiveMessageNano = new RecursiveMessageNano[] { msg3 };
-
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 16);
- assertEquals(result.length, msgSerializedSize);
-
- RecursiveMessageNano newMsg = RecursiveMessageNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedRecursiveMessageNano.length);
-
- assertEquals(0, newMsg.id);
- assertEquals(1, newMsg.nestedMessage.a.id);
- assertEquals(2, newMsg.optionalRecursiveMessageNano.id);
- assertEquals(3, newMsg.repeatedRecursiveMessageNano[0].id);
- }
-
- public void testMessageNoFields() {
- SingleMessageNano msg = new SingleMessageNano();
- assertEquals(0, msg.getSerializedSize());
- assertEquals(0, MessageNano.toByteArray(msg).length);
- }
-
- public void testNanoRequiredInt32() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.id = 123;
- assertEquals(123, msg.id);
- msg.clear().id = 456;
- assertEquals(456, msg.id);
- msg.clear();
-
- msg.id = 123;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 3);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(123, newMsg.id);
- }
-
- public void testNanoOptionalInt32() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalInt32 = 123;
- assertEquals(123, msg.optionalInt32);
- msg.clear()
- .optionalInt32 = 456;
- assertEquals(456, msg.optionalInt32);
- msg.clear();
-
- msg.optionalInt32 = 123;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 5);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(123, newMsg.optionalInt32);
- }
-
- public void testNanoOptionalInt64() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalInt64 = 123;
- assertEquals(123, msg.optionalInt64);
- msg.clear()
- .optionalInt64 = 456;
- assertEquals(456, msg.optionalInt64);
- msg.clear();
- assertEquals(0, msg.optionalInt64);
-
- msg.optionalInt64 = 123;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 5);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(123, newMsg.optionalInt64);
- }
-
- public void testNanoOptionalUint32() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalUint32 = 123;
- assertEquals(123, msg.optionalUint32);
- msg.clear()
- .optionalUint32 = 456;
- assertEquals(456, msg.optionalUint32);
- msg.clear();
- assertEquals(0, msg.optionalUint32);
-
- msg.optionalUint32 = 123;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 5);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(123, newMsg.optionalUint32);
- }
-
- public void testNanoOptionalUint64() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalUint64 = 123;
- assertEquals(123, msg.optionalUint64);
- msg.clear()
- .optionalUint64 = 456;
- assertEquals(456, msg.optionalUint64);
- msg.clear();
- assertEquals(0, msg.optionalUint64);
-
- msg.optionalUint64 = 123;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 5);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(123, newMsg.optionalUint64);
- }
-
- public void testNanoOptionalSint32() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalSint32 = 123;
- assertEquals(123, msg.optionalSint32);
- msg.clear()
- .optionalSint32 = 456;
- assertEquals(456, msg.optionalSint32);
- msg.clear();
- assertEquals(0, msg.optionalSint32);
-
- msg.optionalSint32 = -123;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(-123, newMsg.optionalSint32);
- }
-
- public void testNanoOptionalSint64() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalSint64 = 123;
- assertEquals(123, msg.optionalSint64);
- msg.clear()
- .optionalSint64 = 456;
- assertEquals(456, msg.optionalSint64);
- msg.clear();
- assertEquals(0, msg.optionalSint64);
-
- msg.optionalSint64 = -123;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(-123, newMsg.optionalSint64);
- }
-
- public void testNanoOptionalFixed32() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalFixed32 = 123;
- assertEquals(123, msg.optionalFixed32);
- msg.clear()
- .optionalFixed32 = 456;
- assertEquals(456, msg.optionalFixed32);
- msg.clear();
- assertEquals(0, msg.optionalFixed32);
-
- msg.optionalFixed32 = 123;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 8);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(123, newMsg.optionalFixed32);
- }
-
- public void testNanoOptionalFixed64() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalFixed64 = 123;
- assertEquals(123, msg.optionalFixed64);
- msg.clear()
- .optionalFixed64 = 456;
- assertEquals(456, msg.optionalFixed64);
- msg.clear();
- assertEquals(0, msg.optionalFixed64);
-
- msg.optionalFixed64 = 123;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 12);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(123, newMsg.optionalFixed64);
- }
-
- public void testNanoOptionalSfixed32() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalSfixed32 = 123;
- assertEquals(123, msg.optionalSfixed32);
- msg.clear()
- .optionalSfixed32 = 456;
- assertEquals(456, msg.optionalSfixed32);
- msg.clear();
- assertEquals(0, msg.optionalSfixed32);
-
- msg.optionalSfixed32 = 123;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 8);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(123, newMsg.optionalSfixed32);
- }
-
- public void testNanoOptionalSfixed64() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalSfixed64 = 123;
- assertEquals(123, msg.optionalSfixed64);
- msg.clear()
- .optionalSfixed64 = 456;
- assertEquals(456, msg.optionalSfixed64);
- msg.clear();
- assertEquals(0, msg.optionalSfixed64);
-
- msg.optionalSfixed64 = -123;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 12);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(-123, newMsg.optionalSfixed64);
- }
-
- public void testNanoOptionalFloat() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalFloat = 123f;
- assertTrue(123.0f == msg.optionalFloat);
- msg.clear()
- .optionalFloat = 456.0f;
- assertTrue(456.0f == msg.optionalFloat);
- msg.clear();
- assertTrue(0.0f == msg.optionalFloat);
-
- msg.optionalFloat = -123.456f;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 8);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertTrue(-123.456f == newMsg.optionalFloat);
- }
-
- public void testNanoOptionalDouble() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalDouble = 123;
- assertTrue(123.0 == msg.optionalDouble);
- msg.clear()
- .optionalDouble = 456.0;
- assertTrue(456.0 == msg.optionalDouble);
- msg.clear();
- assertTrue(0.0 == msg.optionalDouble);
-
- msg.optionalDouble = -123.456;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 12);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertTrue(-123.456 == newMsg.optionalDouble);
- }
-
- public void testNanoOptionalBool() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalBool = true;
- assertTrue(msg.optionalBool);
- msg.clear()
- .optionalBool = true;
- assertTrue(msg.optionalBool);
- msg.clear();
- assertFalse(msg.optionalBool);
-
- msg.optionalBool = true;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 5);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertTrue(newMsg.optionalBool);
- }
-
- public void testNanoOptionalString() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalString = "hello";
- assertEquals("hello", msg.optionalString);
- msg.clear();
- assertTrue(msg.optionalString.isEmpty());
- msg.clear()
- .optionalString = "hello2";
- assertEquals("hello2", msg.optionalString);
- msg.clear();
- assertTrue(msg.optionalString.isEmpty());
-
- msg.optionalString = "bye";
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 8);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertTrue(newMsg.optionalString != null);
- assertEquals("bye", newMsg.optionalString);
- }
-
- public void testNanoOptionalBytes() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertFalse(msg.optionalBytes.length > 0);
- msg.optionalBytes = InternalNano.copyFromUtf8("hello");
- assertTrue(msg.optionalBytes.length > 0);
- assertEquals("hello", new String(msg.optionalBytes, InternalNano.UTF_8));
- msg.clear();
- assertFalse(msg.optionalBytes.length > 0);
- msg.clear()
- .optionalBytes = InternalNano.copyFromUtf8("hello");
- assertTrue(msg.optionalBytes.length > 0);
- msg.clear();
- assertFalse(msg.optionalBytes.length > 0);
-
- msg.optionalBytes = InternalNano.copyFromUtf8("bye");
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 8);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertTrue(newMsg.optionalBytes.length > 0);
- assertEquals("bye", new String(newMsg.optionalBytes, InternalNano.UTF_8));
- }
-
- public void testNanoOptionalGroup() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- TestAllTypesNano.OptionalGroup grp = new TestAllTypesNano.OptionalGroup();
- grp.a = 1;
- assertFalse(msg.optionalGroup != null);
- msg.optionalGroup = grp;
- assertTrue(msg.optionalGroup != null);
- assertEquals(1, msg.optionalGroup.a);
- msg.clear();
- assertFalse(msg.optionalGroup != null);
- msg.clear()
- .optionalGroup = new TestAllTypesNano.OptionalGroup();
- msg.optionalGroup.a = 2;
- assertTrue(msg.optionalGroup != null);
- msg.clear();
- assertFalse(msg.optionalGroup != null);
-
- msg.optionalGroup = grp;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 10);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertTrue(newMsg.optionalGroup != null);
- assertEquals(1, newMsg.optionalGroup.a);
- }
-
- public void testNanoOptionalGroupWithUnknownFieldsEnabled() throws Exception {
- MessageWithGroup msg = new MessageWithGroup();
- MessageWithGroup.Group grp = new MessageWithGroup.Group();
- grp.a = 1;
- msg.group = grp;
- byte [] serialized = MessageNano.toByteArray(msg);
-
- MessageWithGroup parsed = MessageWithGroup.parseFrom(serialized);
- assertEquals(1, parsed.group.a);
-
- byte [] serialized2 = MessageNano.toByteArray(parsed);
- assertEquals(serialized.length, serialized2.length);
- MessageWithGroup parsed2 = MessageWithGroup.parseFrom(serialized2);
- assertEquals(1, parsed2.group.a);
- }
-
- public void testNanoOptionalNestedMessage() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- TestAllTypesNano.NestedMessage nestedMsg = new TestAllTypesNano.NestedMessage();
- nestedMsg.bb = 1;
- assertFalse(msg.optionalNestedMessage != null);
- msg.optionalNestedMessage = nestedMsg;
- assertTrue(msg.optionalNestedMessage != null);
- assertEquals(1, msg.optionalNestedMessage.bb);
- msg.clear();
- assertFalse(msg.optionalNestedMessage != null);
- msg.clear()
- .optionalNestedMessage = new TestAllTypesNano.NestedMessage();
- msg.optionalNestedMessage.bb = 2;
- assertTrue(msg.optionalNestedMessage != null);
- msg.clear();
- assertFalse(msg.optionalNestedMessage != null);
-
- msg.optionalNestedMessage = nestedMsg;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 8);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertTrue(newMsg.optionalNestedMessage != null);
- assertEquals(1, newMsg.optionalNestedMessage.bb);
- }
-
- public void testNanoOptionalForeignMessage() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- NanoOuterClass.ForeignMessageNano nestedMsg = new NanoOuterClass.ForeignMessageNano();
- nestedMsg.c = 1;
- assertFalse(msg.optionalForeignMessage != null);
- msg.optionalForeignMessage = nestedMsg;
- assertTrue(msg.optionalForeignMessage != null);
- assertEquals(1, msg.optionalForeignMessage.c);
- msg.clear();
- assertFalse(msg.optionalForeignMessage != null);
- msg.clear()
- .optionalForeignMessage = new NanoOuterClass.ForeignMessageNano();
- msg.optionalForeignMessage.c = 2;
- assertTrue(msg.optionalForeignMessage != null);
- msg.clear();
- assertFalse(msg.optionalForeignMessage != null);
-
- msg.optionalForeignMessage = nestedMsg;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 8);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertTrue(newMsg.optionalForeignMessage != null);
- assertEquals(1, newMsg.optionalForeignMessage.c);
- }
-
- public void testNanoOptionalImportMessage() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- UnittestImportNano.ImportMessageNano nestedMsg = new UnittestImportNano.ImportMessageNano();
- nestedMsg.d = 1;
- assertFalse(msg.optionalImportMessage != null);
- msg.optionalImportMessage = nestedMsg;
- assertTrue(msg.optionalImportMessage != null);
- assertEquals(1, msg.optionalImportMessage.d);
- msg.clear();
- assertFalse(msg.optionalImportMessage != null);
- msg.clear()
- .optionalImportMessage = new UnittestImportNano.ImportMessageNano();
- msg.optionalImportMessage.d = 2;
- assertTrue(msg.optionalImportMessage != null);
- msg.clear();
- assertFalse(msg.optionalImportMessage != null);
-
- msg.optionalImportMessage = nestedMsg;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 8);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertTrue(newMsg.optionalImportMessage != null);
- assertEquals(1, newMsg.optionalImportMessage.d);
- }
-
- public void testNanoOptionalNestedEnum() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalNestedEnum = TestAllTypesNano.BAR;
- assertEquals(TestAllTypesNano.BAR, msg.optionalNestedEnum);
- msg.clear()
- .optionalNestedEnum = TestAllTypesNano.BAZ;
- assertEquals(TestAllTypesNano.BAZ, msg.optionalNestedEnum);
- msg.clear();
- assertEquals(TestAllTypesNano.FOO, msg.optionalNestedEnum);
-
- msg.optionalNestedEnum = TestAllTypesNano.BAR;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(TestAllTypesNano.BAR, newMsg.optionalNestedEnum);
- }
-
- public void testNanoOptionalForeignEnum() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalForeignEnum = NanoOuterClass.FOREIGN_NANO_BAR;
- assertEquals(NanoOuterClass.FOREIGN_NANO_BAR, msg.optionalForeignEnum);
- msg.clear()
- .optionalForeignEnum = NanoOuterClass.FOREIGN_NANO_BAZ;
- assertEquals(NanoOuterClass.FOREIGN_NANO_BAZ, msg.optionalForeignEnum);
- msg.clear();
- assertEquals(NanoOuterClass.FOREIGN_NANO_FOO, msg.optionalForeignEnum);
-
- msg.optionalForeignEnum = NanoOuterClass.FOREIGN_NANO_BAR;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(NanoOuterClass.FOREIGN_NANO_BAR, newMsg.optionalForeignEnum);
- }
-
- public void testNanoOptionalImportEnum() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalImportEnum = UnittestImportNano.IMPORT_NANO_BAR;
- assertEquals(UnittestImportNano.IMPORT_NANO_BAR, msg.optionalImportEnum);
- msg.clear()
- .optionalImportEnum = UnittestImportNano.IMPORT_NANO_BAZ;
- assertEquals(UnittestImportNano.IMPORT_NANO_BAZ, msg.optionalImportEnum);
- msg.clear();
- assertEquals(UnittestImportNano.IMPORT_NANO_FOO, msg.optionalImportEnum);
-
- msg.optionalImportEnum = UnittestImportNano.IMPORT_NANO_BAR;
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(UnittestImportNano.IMPORT_NANO_BAR, newMsg.optionalImportEnum);
- }
-
- public void testNanoOptionalStringPiece() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalStringPiece = "hello";
- assertEquals("hello", msg.optionalStringPiece);
- msg.clear();
- assertTrue(msg.optionalStringPiece.isEmpty());
- msg.clear()
- .optionalStringPiece = "hello2";
- assertEquals("hello2", msg.optionalStringPiece);
- msg.clear();
- assertTrue(msg.optionalStringPiece.isEmpty());
-
- msg.optionalStringPiece = "bye";
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 9);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertTrue(newMsg.optionalStringPiece != null);
- assertEquals("bye", newMsg.optionalStringPiece);
- }
-
- public void testNanoOptionalCord() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalCord = "hello";
- assertEquals("hello", msg.optionalCord);
- msg.clear();
- assertTrue(msg.optionalCord.isEmpty());
- msg.clear()
- .optionalCord = "hello2";
- assertEquals("hello2", msg.optionalCord);
- msg.clear();
- assertTrue(msg.optionalCord.isEmpty());
-
- msg.optionalCord = "bye";
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 9);
- assertEquals(result.length, msgSerializedSize);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertTrue(newMsg.optionalCord != null);
- assertEquals("bye", newMsg.optionalCord);
- }
-
- public void testNanoRepeatedInt32() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedInt32.length);
- msg.repeatedInt32 = new int[] { 123, 789, 456 };
- assertEquals(789, msg.repeatedInt32[1]);
- assertEquals(456, msg.repeatedInt32[2]);
- msg.clear();
- assertEquals(0, msg.repeatedInt32.length);
- msg.clear()
- .repeatedInt32 = new int[] { 456 };
- assertEquals(1, msg.repeatedInt32.length);
- assertEquals(456, msg.repeatedInt32[0]);
- msg.clear();
- assertEquals(0, msg.repeatedInt32.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedInt32 = new int[] { 123 };
- assertEquals(1, msg.repeatedInt32.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedInt32.length);
- assertEquals(123, newMsg.repeatedInt32[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedInt32 = new int[] { 123, 456 };
- assertEquals(2, msg.repeatedInt32.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 10);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedInt32.length);
- assertEquals(123, newMsg.repeatedInt32[0]);
- assertEquals(456, newMsg.repeatedInt32[1]);
- }
-
- public void testNanoRepeatedInt64() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedInt64.length);
- msg.repeatedInt64 = new long[] { 123, 789, 456 };
- assertEquals(789, msg.repeatedInt64[1]);
- assertEquals(456, msg.repeatedInt64[2]);
- msg.clear();
- assertEquals(0, msg.repeatedInt64.length);
- msg.clear()
- .repeatedInt64 = new long[] { 456 };
- assertEquals(1, msg.repeatedInt64.length);
- assertEquals(456, msg.repeatedInt64[0]);
- msg.clear();
- assertEquals(0, msg.repeatedInt64.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedInt64 = new long[] { 123 };
- assertEquals(1, msg.repeatedInt64.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedInt64.length);
- assertEquals(123, newMsg.repeatedInt64[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedInt64 = new long[] { 123, 456 };
- assertEquals(2, msg.repeatedInt64.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 10);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedInt64.length);
- assertEquals(123, newMsg.repeatedInt64[0]);
- assertEquals(456, newMsg.repeatedInt64[1]);
- }
-
- public void testNanoRepeatedUint32() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedUint32.length);
- msg.repeatedUint32 = new int[] { 123, 789, 456 };
- assertEquals(789, msg.repeatedUint32[1]);
- assertEquals(456, msg.repeatedUint32[2]);
- msg.clear();
- assertEquals(0, msg.repeatedUint32.length);
- msg.clear()
- .repeatedUint32 = new int[] { 456 };
- assertEquals(1, msg.repeatedUint32.length);
- assertEquals(456, msg.repeatedUint32[0]);
- msg.clear();
- assertEquals(0, msg.repeatedUint32.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedUint32 = new int[] { 123 };
- assertEquals(1, msg.repeatedUint32.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedUint32.length);
- assertEquals(123, newMsg.repeatedUint32[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedUint32 = new int[] { 123, 456 };
- assertEquals(2, msg.repeatedUint32.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 10);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedUint32.length);
- assertEquals(123, newMsg.repeatedUint32[0]);
- assertEquals(456, newMsg.repeatedUint32[1]);
- }
-
- public void testNanoRepeatedUint64() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedUint64.length);
- msg.repeatedUint64 = new long[] { 123, 789, 456 };
- assertEquals(789, msg.repeatedUint64[1]);
- assertEquals(456, msg.repeatedUint64[2]);
- msg.clear();
- assertEquals(0, msg.repeatedUint64.length);
- msg.clear()
- .repeatedUint64 = new long[] { 456 };
- assertEquals(1, msg.repeatedUint64.length);
- assertEquals(456, msg.repeatedUint64[0]);
- msg.clear();
- assertEquals(0, msg.repeatedUint64.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedUint64 = new long[] { 123 };
- assertEquals(1, msg.repeatedUint64.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedUint64.length);
- assertEquals(123, newMsg.repeatedUint64[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedUint64 = new long[] { 123, 456 };
- assertEquals(2, msg.repeatedUint64.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 10);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedUint64.length);
- assertEquals(123, newMsg.repeatedUint64[0]);
- assertEquals(456, newMsg.repeatedUint64[1]);
- }
-
- public void testNanoRepeatedSint32() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedSint32.length);
- msg.repeatedSint32 = new int[] { 123, 789, 456 };
- assertEquals(789, msg.repeatedSint32[1]);
- assertEquals(456, msg.repeatedSint32[2]);
- msg.clear();
- assertEquals(0, msg.repeatedSint32.length);
- msg.clear()
- .repeatedSint32 = new int[] { 456 };
- assertEquals(1, msg.repeatedSint32.length);
- assertEquals(456, msg.repeatedSint32[0]);
- msg.clear();
- assertEquals(0, msg.repeatedSint32.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedSint32 = new int[] { 123 };
- assertEquals(1, msg.repeatedSint32.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 7);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedSint32.length);
- assertEquals(123, newMsg.repeatedSint32[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedSint32 = new int[] { 123, 456 };
- assertEquals(2, msg.repeatedSint32.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 11);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedSint32.length);
- assertEquals(123, newMsg.repeatedSint32[0]);
- assertEquals(456, newMsg.repeatedSint32[1]);
- }
-
- public void testNanoRepeatedSint64() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedSint64.length);
- msg.repeatedSint64 = new long[] { 123, 789, 456 };
- assertEquals(789, msg.repeatedSint64[1]);
- assertEquals(456, msg.repeatedSint64[2]);
- msg.clear();
- assertEquals(0, msg.repeatedSint64.length);
- msg.clear()
- .repeatedSint64 = new long[] { 456 };
- assertEquals(1, msg.repeatedSint64.length);
- assertEquals(456, msg.repeatedSint64[0]);
- msg.clear();
- assertEquals(0, msg.repeatedSint64.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedSint64 = new long[] { 123 };
- assertEquals(1, msg.repeatedSint64.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 7);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedSint64.length);
- assertEquals(123, newMsg.repeatedSint64[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedSint64 = new long[] { 123, 456 };
- assertEquals(2, msg.repeatedSint64.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 11);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedSint64.length);
- assertEquals(123, newMsg.repeatedSint64[0]);
- assertEquals(456, newMsg.repeatedSint64[1]);
- }
-
- public void testNanoRepeatedFixed32() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedFixed32.length);
- msg.repeatedFixed32 = new int[] { 123, 789, 456 };
- assertEquals(789, msg.repeatedFixed32[1]);
- assertEquals(456, msg.repeatedFixed32[2]);
- msg.clear();
- assertEquals(0, msg.repeatedFixed32.length);
- msg.clear()
- .repeatedFixed32 = new int[] { 456 };
- assertEquals(1, msg.repeatedFixed32.length);
- assertEquals(456, msg.repeatedFixed32[0]);
- msg.clear();
- assertEquals(0, msg.repeatedFixed32.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedFixed32 = new int[] { 123 };
- assertEquals(1, msg.repeatedFixed32.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 9);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedFixed32.length);
- assertEquals(123, newMsg.repeatedFixed32[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedFixed32 = new int[] { 123, 456 };
- assertEquals(2, msg.repeatedFixed32.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 15);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedFixed32.length);
- assertEquals(123, newMsg.repeatedFixed32[0]);
- assertEquals(456, newMsg.repeatedFixed32[1]);
- }
-
- public void testNanoRepeatedFixed64() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedFixed64.length);
- msg.repeatedFixed64 = new long[] { 123, 789, 456 };
- assertEquals(789, msg.repeatedFixed64[1]);
- assertEquals(456, msg.repeatedFixed64[2]);
- msg.clear();
- assertEquals(0, msg.repeatedFixed64.length);
- msg.clear()
- .repeatedFixed64 = new long[] { 456 };
- assertEquals(1, msg.repeatedFixed64.length);
- assertEquals(456, msg.repeatedFixed64[0]);
- msg.clear();
- assertEquals(0, msg.repeatedFixed64.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedFixed64 = new long[] { 123 };
- assertEquals(1, msg.repeatedFixed64.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 13);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedFixed64.length);
- assertEquals(123, newMsg.repeatedFixed64[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedFixed64 = new long[] { 123, 456 };
- assertEquals(2, msg.repeatedFixed64.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 23);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedFixed64.length);
- assertEquals(123, newMsg.repeatedFixed64[0]);
- assertEquals(456, newMsg.repeatedFixed64[1]);
- }
-
- public void testNanoRepeatedSfixed32() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedSfixed32.length);
- msg.repeatedSfixed32 = new int[] { 123, 789, 456 };
- assertEquals(789, msg.repeatedSfixed32[1]);
- assertEquals(456, msg.repeatedSfixed32[2]);
- msg.clear();
- assertEquals(0, msg.repeatedSfixed32.length);
- msg.clear()
- .repeatedSfixed32 = new int[] { 456 };
- assertEquals(1, msg.repeatedSfixed32.length);
- assertEquals(456, msg.repeatedSfixed32[0]);
- msg.clear();
- assertEquals(0, msg.repeatedSfixed32.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedSfixed32 = new int[] { 123 };
- assertEquals(1, msg.repeatedSfixed32.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 9);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedSfixed32.length);
- assertEquals(123, newMsg.repeatedSfixed32[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedSfixed32 = new int[] { 123, 456 };
- assertEquals(2, msg.repeatedSfixed32.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 15);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedSfixed32.length);
- assertEquals(123, newMsg.repeatedSfixed32[0]);
- assertEquals(456, newMsg.repeatedSfixed32[1]);
- }
-
- public void testNanoRepeatedSfixed64() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedSfixed64.length);
- msg.repeatedSfixed64 = new long[] { 123, 789, 456 };
- assertEquals(789, msg.repeatedSfixed64[1]);
- assertEquals(456, msg.repeatedSfixed64[2]);
- msg.clear();
- assertEquals(0, msg.repeatedSfixed64.length);
- msg.clear()
- .repeatedSfixed64 = new long[] { 456 };
- assertEquals(1, msg.repeatedSfixed64.length);
- assertEquals(456, msg.repeatedSfixed64[0]);
- msg.clear();
- assertEquals(0, msg.repeatedSfixed64.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedSfixed64 = new long[] { 123 };
- assertEquals(1, msg.repeatedSfixed64.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 13);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedSfixed64.length);
- assertEquals(123, newMsg.repeatedSfixed64[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedSfixed64 = new long[] { 123, 456 };
- assertEquals(2, msg.repeatedSfixed64.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 23);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedSfixed64.length);
- assertEquals(123, newMsg.repeatedSfixed64[0]);
- assertEquals(456, newMsg.repeatedSfixed64[1]);
- }
-
- public void testNanoRepeatedFloat() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedFloat.length);
- msg.repeatedFloat = new float[] { 123f, 789f, 456f };
- assertEquals(789f, msg.repeatedFloat[1]);
- assertEquals(456f, msg.repeatedFloat[2]);
- msg.clear();
- assertEquals(0, msg.repeatedFloat.length);
- msg.clear()
- .repeatedFloat = new float[] { 456f };
- assertEquals(1, msg.repeatedFloat.length);
- assertEquals(456f, msg.repeatedFloat[0]);
- msg.clear();
- assertEquals(0, msg.repeatedFloat.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedFloat = new float[] { 123f };
- assertEquals(1, msg.repeatedFloat.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 9);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedFloat.length);
- assertEquals(123f, newMsg.repeatedFloat[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedFloat = new float[] { 123f, 456f };
- assertEquals(2, msg.repeatedFloat.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 15);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedFloat.length);
- assertEquals(123f, newMsg.repeatedFloat[0]);
- assertEquals(456f, newMsg.repeatedFloat[1]);
- }
-
- public void testNanoRepeatedDouble() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedDouble.length);
- msg.repeatedDouble = new double[] { 123.0, 789.0, 456.0 };
- assertEquals(789.0, msg.repeatedDouble[1]);
- assertEquals(456.0, msg.repeatedDouble[2]);
- msg.clear();
- assertEquals(0, msg.repeatedDouble.length);
- msg.clear()
- .repeatedDouble = new double[] { 456.0 };
- assertEquals(1, msg.repeatedDouble.length);
- assertEquals(456.0, msg.repeatedDouble[0]);
- msg.clear();
- assertEquals(0, msg.repeatedDouble.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedDouble = new double[] { 123.0 };
- assertEquals(1, msg.repeatedDouble.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 13);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedDouble.length);
- assertEquals(123.0, newMsg.repeatedDouble[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedDouble = new double[] { 123.0, 456.0 };
- assertEquals(2, msg.repeatedDouble.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 23);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedDouble.length);
- assertEquals(123.0, newMsg.repeatedDouble[0]);
- assertEquals(456.0, newMsg.repeatedDouble[1]);
- }
-
- public void testNanoRepeatedBool() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedBool.length);
- msg.repeatedBool = new boolean[] { false, true, false };
- assertTrue(msg.repeatedBool[1]);
- assertFalse(msg.repeatedBool[2]);
- msg.clear();
- assertEquals(0, msg.repeatedBool.length);
- msg.clear()
- .repeatedBool = new boolean[] { true };
- assertEquals(1, msg.repeatedBool.length);
- assertTrue(msg.repeatedBool[0]);
- msg.clear();
- assertEquals(0, msg.repeatedBool.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedBool = new boolean[] { false };
- assertEquals(1, msg.repeatedBool.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedBool.length);
- assertFalse(newMsg.repeatedBool[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedBool = new boolean[] { true, false };
- assertEquals(2, msg.repeatedBool.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 9);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedBool.length);
- assertTrue(newMsg.repeatedBool[0]);
- assertFalse(newMsg.repeatedBool[1]);
- }
-
- public void testNanoRepeatedString() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedString.length);
- msg.repeatedString = new String[] { "hello", "bye", "boo" };
- assertEquals("bye", msg.repeatedString[1]);
- assertEquals("boo", msg.repeatedString[2]);
- msg.clear();
- assertEquals(0, msg.repeatedString.length);
- msg.clear()
- .repeatedString = new String[] { "boo" };
- assertEquals(1, msg.repeatedString.length);
- assertEquals("boo", msg.repeatedString[0]);
- msg.clear();
- assertEquals(0, msg.repeatedString.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedString = new String[] { "" };
- assertEquals(1, msg.repeatedString.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedString.length);
- assertTrue(newMsg.repeatedString[0].isEmpty());
-
- // Test 2 entries
- msg.clear()
- .repeatedString = new String[] { "hello", "world" };
- assertEquals(2, msg.repeatedString.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 19);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedString.length);
- assertEquals("hello", newMsg.repeatedString[0]);
- assertEquals("world", newMsg.repeatedString[1]);
- }
-
- public void testNanoRepeatedBytes() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedBytes.length);
- msg.repeatedBytes = new byte[][] {
- InternalNano.copyFromUtf8("hello"),
- InternalNano.copyFromUtf8("bye"),
- InternalNano.copyFromUtf8("boo")
- };
- assertEquals("bye", new String(msg.repeatedBytes[1], InternalNano.UTF_8));
- assertEquals("boo", new String(msg.repeatedBytes[2], InternalNano.UTF_8));
- msg.clear();
- assertEquals(0, msg.repeatedBytes.length);
- msg.clear()
- .repeatedBytes = new byte[][] { InternalNano.copyFromUtf8("boo") };
- assertEquals(1, msg.repeatedBytes.length);
- assertEquals("boo", new String(msg.repeatedBytes[0], InternalNano.UTF_8));
- msg.clear();
- assertEquals(0, msg.repeatedBytes.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedBytes = new byte[][] { InternalNano.copyFromUtf8("") };
- assertEquals(1, msg.repeatedBytes.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedBytes.length);
- assertTrue(newMsg.repeatedBytes[0].length == 0);
-
- // Test 2 entries
- msg.clear()
- .repeatedBytes = new byte[][] {
- InternalNano.copyFromUtf8("hello"),
- InternalNano.copyFromUtf8("world")
- };
- assertEquals(2, msg.repeatedBytes.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 19);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedBytes.length);
- assertEquals("hello", new String(newMsg.repeatedBytes[0], InternalNano.UTF_8));
- assertEquals("world", new String(newMsg.repeatedBytes[1], InternalNano.UTF_8));
- }
-
- public void testNanoRepeatedGroup() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- TestAllTypesNano.RepeatedGroup group0 =
- new TestAllTypesNano.RepeatedGroup();
- group0.a = 0;
- TestAllTypesNano.RepeatedGroup group1 =
- new TestAllTypesNano.RepeatedGroup();
- group1.a = 1;
- TestAllTypesNano.RepeatedGroup group2 =
- new TestAllTypesNano.RepeatedGroup();
- group2.a = 2;
-
- msg.repeatedGroup = new TestAllTypesNano.RepeatedGroup[] { group0, group1, group2 };
- assertEquals(3, msg.repeatedGroup.length);
- assertEquals(0, msg.repeatedGroup[0].a);
- assertEquals(1, msg.repeatedGroup[1].a);
- assertEquals(2, msg.repeatedGroup[2].a);
- msg.clear();
- assertEquals(0, msg.repeatedGroup.length);
- msg.clear()
- .repeatedGroup = new TestAllTypesNano.RepeatedGroup[] { group1 };
- assertEquals(1, msg.repeatedGroup.length);
- assertEquals(1, msg.repeatedGroup[0].a);
- msg.clear();
- assertEquals(0, msg.repeatedGroup.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedGroup = new TestAllTypesNano.RepeatedGroup[] { group0 };
- assertEquals(1, msg.repeatedGroup.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 7);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedGroup.length);
- assertEquals(0, newMsg.repeatedGroup[0].a);
-
- // Test 2 entries
- msg.clear()
- .repeatedGroup = new TestAllTypesNano.RepeatedGroup[] { group0, group1 };
- assertEquals(2, msg.repeatedGroup.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 14);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedGroup.length);
- assertEquals(0, newMsg.repeatedGroup[0].a);
- assertEquals(1, newMsg.repeatedGroup[1].a);
- }
-
- public void testNanoRepeatedNestedMessage() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- TestAllTypesNano.NestedMessage nestedMsg0 =
- new TestAllTypesNano.NestedMessage();
- nestedMsg0.bb = 0;
- TestAllTypesNano.NestedMessage nestedMsg1 =
- new TestAllTypesNano.NestedMessage();
- nestedMsg1.bb = 1;
- TestAllTypesNano.NestedMessage nestedMsg2 =
- new TestAllTypesNano.NestedMessage();
- nestedMsg2.bb = 2;
-
- msg.repeatedNestedMessage =
- new TestAllTypesNano.NestedMessage[] { nestedMsg0, nestedMsg1, nestedMsg2 };
- assertEquals(3, msg.repeatedNestedMessage.length);
- assertEquals(0, msg.repeatedNestedMessage[0].bb);
- assertEquals(1, msg.repeatedNestedMessage[1].bb);
- assertEquals(2, msg.repeatedNestedMessage[2].bb);
- msg.clear();
- assertEquals(0, msg.repeatedNestedMessage.length);
- msg.clear()
- .repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] { nestedMsg1 };
- assertEquals(1, msg.repeatedNestedMessage.length);
- assertEquals(1, msg.repeatedNestedMessage[0].bb);
- msg.clear();
- assertEquals(0, msg.repeatedNestedMessage.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] { nestedMsg0 };
- assertEquals(1, msg.repeatedNestedMessage.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedNestedMessage.length);
- assertEquals(0, newMsg.repeatedNestedMessage[0].bb);
-
- // Test 2 entries
- msg.clear()
- .repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] { nestedMsg0, nestedMsg1 };
- assertEquals(2, msg.repeatedNestedMessage.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 11);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedNestedMessage.length);
- assertEquals(0, newMsg.repeatedNestedMessage[0].bb);
- assertEquals(1, newMsg.repeatedNestedMessage[1].bb);
- }
-
- public void testNanoRepeatedForeignMessage() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- NanoOuterClass.ForeignMessageNano foreignMsg0 =
- new NanoOuterClass.ForeignMessageNano();
- foreignMsg0.c = 0;
- NanoOuterClass.ForeignMessageNano foreignMsg1 =
- new NanoOuterClass.ForeignMessageNano();
- foreignMsg1.c = 1;
- NanoOuterClass.ForeignMessageNano foreignMsg2 =
- new NanoOuterClass.ForeignMessageNano();
- foreignMsg2.c = 2;
-
- msg.repeatedForeignMessage =
- new NanoOuterClass.ForeignMessageNano[] { foreignMsg0, foreignMsg1, foreignMsg2 };
- assertEquals(3, msg.repeatedForeignMessage.length);
- assertEquals(0, msg.repeatedForeignMessage[0].c);
- assertEquals(1, msg.repeatedForeignMessage[1].c);
- assertEquals(2, msg.repeatedForeignMessage[2].c);
- msg.clear();
- assertEquals(0, msg.repeatedForeignMessage.length);
- msg.clear()
- .repeatedForeignMessage = new NanoOuterClass.ForeignMessageNano[] { foreignMsg1 };
- assertEquals(1, msg.repeatedForeignMessage.length);
- assertEquals(1, msg.repeatedForeignMessage[0].c);
- msg.clear();
- assertEquals(0, msg.repeatedForeignMessage.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedForeignMessage = new NanoOuterClass.ForeignMessageNano[] { foreignMsg0 };
- assertEquals(1, msg.repeatedForeignMessage.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedForeignMessage.length);
- assertEquals(0, newMsg.repeatedForeignMessage[0].c);
-
- // Test 2 entries
- msg.clear()
- .repeatedForeignMessage = new NanoOuterClass.ForeignMessageNano[] { foreignMsg0, foreignMsg1 };
- assertEquals(2, msg.repeatedForeignMessage.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 11);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedForeignMessage.length);
- assertEquals(0, newMsg.repeatedForeignMessage[0].c);
- assertEquals(1, newMsg.repeatedForeignMessage[1].c);
- }
-
- public void testNanoRepeatedImportMessage() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- UnittestImportNano.ImportMessageNano foreignMsg0 =
- new UnittestImportNano.ImportMessageNano();
- foreignMsg0.d = 0;
- UnittestImportNano.ImportMessageNano foreignMsg1 =
- new UnittestImportNano.ImportMessageNano();
- foreignMsg1.d = 1;
- UnittestImportNano.ImportMessageNano foreignMsg2 =
- new UnittestImportNano.ImportMessageNano();
- foreignMsg2.d = 2;
-
- msg.repeatedImportMessage =
- new UnittestImportNano.ImportMessageNano[] { foreignMsg0, foreignMsg1, foreignMsg2 };
- assertEquals(3, msg.repeatedImportMessage.length);
- assertEquals(0, msg.repeatedImportMessage[0].d);
- assertEquals(1, msg.repeatedImportMessage[1].d);
- assertEquals(2, msg.repeatedImportMessage[2].d);
- msg.clear();
- assertEquals(0, msg.repeatedImportMessage.length);
- msg.clear()
- .repeatedImportMessage = new UnittestImportNano.ImportMessageNano[] { foreignMsg1 };
- assertEquals(1, msg.repeatedImportMessage.length);
- assertEquals(1, msg.repeatedImportMessage[0].d);
- msg.clear();
- assertEquals(0, msg.repeatedImportMessage.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedImportMessage = new UnittestImportNano.ImportMessageNano[] { foreignMsg0 };
- assertEquals(1, msg.repeatedImportMessage.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedImportMessage.length);
- assertEquals(0, newMsg.repeatedImportMessage[0].d);
-
- // Test 2 entries
- msg.clear()
- .repeatedImportMessage = new UnittestImportNano.ImportMessageNano[] { foreignMsg0, foreignMsg1 };
- assertEquals(2, msg.repeatedImportMessage.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 11);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedImportMessage.length);
- assertEquals(0, newMsg.repeatedImportMessage[0].d);
- assertEquals(1, newMsg.repeatedImportMessage[1].d);
- }
-
- public void testNanoRepeatedNestedEnum() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.repeatedNestedEnum = new int[] {
- TestAllTypesNano.FOO,
- TestAllTypesNano.BAR,
- TestAllTypesNano.BAZ
- };
- assertEquals(3, msg.repeatedNestedEnum.length);
- assertEquals(TestAllTypesNano.FOO, msg.repeatedNestedEnum[0]);
- assertEquals(TestAllTypesNano.BAR, msg.repeatedNestedEnum[1]);
- assertEquals(TestAllTypesNano.BAZ, msg.repeatedNestedEnum[2]);
- msg.clear();
- assertEquals(0, msg.repeatedNestedEnum.length);
- msg.clear()
- .repeatedNestedEnum = new int[] { TestAllTypesNano.BAR };
- assertEquals(1, msg.repeatedNestedEnum.length);
- assertEquals(TestAllTypesNano.BAR, msg.repeatedNestedEnum[0]);
- msg.clear();
- assertEquals(0, msg.repeatedNestedEnum.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedNestedEnum = new int[] { TestAllTypesNano.FOO };
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedNestedEnum.length);
- assertEquals(TestAllTypesNano.FOO, msg.repeatedNestedEnum[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedNestedEnum = new int[] { TestAllTypesNano.FOO, TestAllTypesNano.BAR };
- assertEquals(2, msg.repeatedNestedEnum.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 9);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedNestedEnum.length);
- assertEquals(TestAllTypesNano.FOO, msg.repeatedNestedEnum[0]);
- assertEquals(TestAllTypesNano.BAR, msg.repeatedNestedEnum[1]);
- }
-
- public void testNanoRepeatedForeignEnum() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.repeatedForeignEnum = new int[] {
- NanoOuterClass.FOREIGN_NANO_FOO,
- NanoOuterClass.FOREIGN_NANO_BAR,
- NanoOuterClass.FOREIGN_NANO_BAZ
- };
- assertEquals(3, msg.repeatedForeignEnum.length);
- assertEquals(NanoOuterClass.FOREIGN_NANO_FOO, msg.repeatedForeignEnum[0]);
- assertEquals(NanoOuterClass.FOREIGN_NANO_BAR, msg.repeatedForeignEnum[1]);
- assertEquals(NanoOuterClass.FOREIGN_NANO_BAZ, msg.repeatedForeignEnum[2]);
- msg.clear();
- assertEquals(0, msg.repeatedForeignEnum.length);
- msg.clear()
- .repeatedForeignEnum = new int[] { NanoOuterClass.FOREIGN_NANO_BAR };
- assertEquals(1, msg.repeatedForeignEnum.length);
- assertEquals(NanoOuterClass.FOREIGN_NANO_BAR, msg.repeatedForeignEnum[0]);
- msg.clear();
- assertEquals(0, msg.repeatedForeignEnum.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedForeignEnum = new int[] { NanoOuterClass.FOREIGN_NANO_FOO };
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedForeignEnum.length);
- assertEquals(NanoOuterClass.FOREIGN_NANO_FOO, msg.repeatedForeignEnum[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedForeignEnum = new int[] {
- NanoOuterClass.FOREIGN_NANO_FOO,
- NanoOuterClass.FOREIGN_NANO_BAR
- };
- assertEquals(2, msg.repeatedForeignEnum.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 9);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedForeignEnum.length);
- assertEquals(NanoOuterClass.FOREIGN_NANO_FOO, msg.repeatedForeignEnum[0]);
- assertEquals(NanoOuterClass.FOREIGN_NANO_BAR, msg.repeatedForeignEnum[1]);
- }
-
- public void testNanoRepeatedImportEnum() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.repeatedImportEnum = new int[] {
- UnittestImportNano.IMPORT_NANO_FOO,
- UnittestImportNano.IMPORT_NANO_BAR,
- UnittestImportNano.IMPORT_NANO_BAZ
- };
- assertEquals(3, msg.repeatedImportEnum.length);
- assertEquals(UnittestImportNano.IMPORT_NANO_FOO, msg.repeatedImportEnum[0]);
- assertEquals(UnittestImportNano.IMPORT_NANO_BAR, msg.repeatedImportEnum[1]);
- assertEquals(UnittestImportNano.IMPORT_NANO_BAZ, msg.repeatedImportEnum[2]);
- msg.clear();
- assertEquals(0, msg.repeatedImportEnum.length);
- msg.clear()
- .repeatedImportEnum = new int[] { UnittestImportNano.IMPORT_NANO_BAR };
- assertEquals(1, msg.repeatedImportEnum.length);
- assertEquals(UnittestImportNano.IMPORT_NANO_BAR, msg.repeatedImportEnum[0]);
- msg.clear();
- assertEquals(0, msg.repeatedImportEnum.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedImportEnum = new int[] { UnittestImportNano.IMPORT_NANO_FOO };
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedImportEnum.length);
- assertEquals(UnittestImportNano.IMPORT_NANO_FOO, msg.repeatedImportEnum[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedImportEnum = new int[] {
- UnittestImportNano.IMPORT_NANO_FOO,
- UnittestImportNano.IMPORT_NANO_BAR
- };
- assertEquals(2, msg.repeatedImportEnum.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 9);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedImportEnum.length);
- assertEquals(UnittestImportNano.IMPORT_NANO_FOO, msg.repeatedImportEnum[0]);
- assertEquals(UnittestImportNano.IMPORT_NANO_BAR, msg.repeatedImportEnum[1]);
- }
-
- public void testNanoRepeatedStringPiece() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedStringPiece.length);
- msg.repeatedStringPiece = new String[] { "hello", "bye", "boo" };
- assertEquals("bye", msg.repeatedStringPiece[1]);
- assertEquals("boo", msg.repeatedStringPiece[2]);
- msg.clear();
- assertEquals(0, msg.repeatedStringPiece.length);
- msg.clear()
- .repeatedStringPiece = new String[] { "boo" };
- assertEquals(1, msg.repeatedStringPiece.length);
- assertEquals("boo", msg.repeatedStringPiece[0]);
- msg.clear();
- assertEquals(0, msg.repeatedStringPiece.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedStringPiece = new String[] { "" };
- assertEquals(1, msg.repeatedStringPiece.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedStringPiece.length);
- assertTrue(newMsg.repeatedStringPiece[0].isEmpty());
-
- // Test 2 entries
- msg.clear()
- .repeatedStringPiece = new String[] { "hello", "world" };
- assertEquals(2, msg.repeatedStringPiece.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 19);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedStringPiece.length);
- assertEquals("hello", newMsg.repeatedStringPiece[0]);
- assertEquals("world", newMsg.repeatedStringPiece[1]);
- }
-
- public void testNanoRepeatedCord() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedCord.length);
- msg.repeatedCord = new String[] { "hello", "bye", "boo" };
- assertEquals("bye", msg.repeatedCord[1]);
- assertEquals("boo", msg.repeatedCord[2]);
- msg.clear();
- assertEquals(0, msg.repeatedCord.length);
- msg.clear()
- .repeatedCord = new String[] { "boo" };
- assertEquals(1, msg.repeatedCord.length);
- assertEquals("boo", msg.repeatedCord[0]);
- msg.clear();
- assertEquals(0, msg.repeatedCord.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedCord = new String[] { "" };
- assertEquals(1, msg.repeatedCord.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 6);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedCord.length);
- assertTrue(newMsg.repeatedCord[0].isEmpty());
-
- // Test 2 entries
- msg.clear()
- .repeatedCord = new String[] { "hello", "world" };
- assertEquals(2, msg.repeatedCord.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 19);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedCord.length);
- assertEquals("hello", newMsg.repeatedCord[0]);
- assertEquals("world", newMsg.repeatedCord[1]);
- }
-
- public void testNanoRepeatedPackedInt32() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedPackedInt32.length);
- msg.repeatedPackedInt32 = new int[] { 123, 789, 456 };
- assertEquals(789, msg.repeatedPackedInt32[1]);
- assertEquals(456, msg.repeatedPackedInt32[2]);
- msg.clear();
- assertEquals(0, msg.repeatedPackedInt32.length);
- msg.clear()
- .repeatedPackedInt32 = new int[] { 456 };
- assertEquals(1, msg.repeatedPackedInt32.length);
- assertEquals(456, msg.repeatedPackedInt32[0]);
- msg.clear();
- assertEquals(0, msg.repeatedPackedInt32.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedPackedInt32 = new int[] { 123 };
- assertEquals(1, msg.repeatedPackedInt32.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 7);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedPackedInt32.length);
- assertEquals(123, newMsg.repeatedPackedInt32[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedPackedInt32 = new int[] { 123, 456 };
- assertEquals(2, msg.repeatedPackedInt32.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 9);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedPackedInt32.length);
- assertEquals(123, newMsg.repeatedPackedInt32[0]);
- assertEquals(456, newMsg.repeatedPackedInt32[1]);
- }
-
- public void testNanoRepeatedPackedSfixed64() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- assertEquals(0, msg.repeatedPackedSfixed64.length);
- msg.repeatedPackedSfixed64 = new long[] { 123, 789, 456 };
- assertEquals(789, msg.repeatedPackedSfixed64[1]);
- assertEquals(456, msg.repeatedPackedSfixed64[2]);
- msg.clear();
- assertEquals(0, msg.repeatedPackedSfixed64.length);
- msg.clear()
- .repeatedPackedSfixed64 = new long[] { 456 };
- assertEquals(1, msg.repeatedPackedSfixed64.length);
- assertEquals(456, msg.repeatedPackedSfixed64[0]);
- msg.clear();
- assertEquals(0, msg.repeatedPackedSfixed64.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedPackedSfixed64 = new long[] { 123 };
- assertEquals(1, msg.repeatedPackedSfixed64.length);
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 14);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedPackedSfixed64.length);
- assertEquals(123, newMsg.repeatedPackedSfixed64[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedPackedSfixed64 = new long[] { 123, 456 };
- assertEquals(2, msg.repeatedPackedSfixed64.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 22);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedPackedSfixed64.length);
- assertEquals(123, newMsg.repeatedPackedSfixed64[0]);
- assertEquals(456, newMsg.repeatedPackedSfixed64[1]);
- }
-
- public void testNanoRepeatedPackedNestedEnum() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.repeatedPackedNestedEnum = new int[] {
- TestAllTypesNano.FOO,
- TestAllTypesNano.BAR,
- TestAllTypesNano.BAZ
- };
- assertEquals(3, msg.repeatedPackedNestedEnum.length);
- assertEquals(TestAllTypesNano.FOO, msg.repeatedPackedNestedEnum[0]);
- assertEquals(TestAllTypesNano.BAR, msg.repeatedPackedNestedEnum[1]);
- assertEquals(TestAllTypesNano.BAZ, msg.repeatedPackedNestedEnum[2]);
- msg.clear();
- assertEquals(0, msg.repeatedPackedNestedEnum.length);
- msg.clear()
- .repeatedPackedNestedEnum = new int[] { TestAllTypesNano.BAR };
- assertEquals(1, msg.repeatedPackedNestedEnum.length);
- assertEquals(TestAllTypesNano.BAR, msg.repeatedPackedNestedEnum[0]);
- msg.clear();
- assertEquals(0, msg.repeatedPackedNestedEnum.length);
-
- // Test 1 entry
- msg.clear()
- .repeatedPackedNestedEnum = new int[] { TestAllTypesNano.FOO };
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 7);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(1, newMsg.repeatedPackedNestedEnum.length);
- assertEquals(TestAllTypesNano.FOO, msg.repeatedPackedNestedEnum[0]);
-
- // Test 2 entries
- msg.clear()
- .repeatedPackedNestedEnum = new int[] { TestAllTypesNano.FOO, TestAllTypesNano.BAR };
- assertEquals(2, msg.repeatedPackedNestedEnum.length);
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 8);
- assertEquals(result.length, msgSerializedSize);
-
- newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(2, newMsg.repeatedPackedNestedEnum.length);
- assertEquals(TestAllTypesNano.FOO, msg.repeatedPackedNestedEnum[0]);
- assertEquals(TestAllTypesNano.BAR, msg.repeatedPackedNestedEnum[1]);
- }
-
- public void testNanoRepeatedPackedSerializedSize() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.repeatedPackedInt32 = new int[] { 123, 789, 456 };
- int msgSerializedSize = msg.getSerializedSize();
- byte [] result = MessageNano.toByteArray(msg);
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 11);
- assertEquals(result.length, msgSerializedSize);
- TestAllTypesNano msg2 = new TestAllTypesNano();
- msg2.repeatedPackedInt32 = new int[] { 123, 789, 456 };
- byte [] result2 = new byte[msgSerializedSize];
- MessageNano.toByteArray(msg2, result2, 0, msgSerializedSize);
-
- // Check equal size and content.
- assertEquals(msgSerializedSize, msg2.getSerializedSize());
- assertTrue(Arrays.equals(result, result2));
- }
-
- public void testNanoRepeatedInt32ReMerge() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.repeatedInt32 = new int[] { 234 };
- byte [] result1 = MessageNano.toByteArray(msg);
-
- msg.clear().optionalInt32 = 789;
- byte [] result2 = MessageNano.toByteArray(msg);
-
- msg.clear().repeatedInt32 = new int[] { 123, 456 };
- byte [] result3 = MessageNano.toByteArray(msg);
-
- // Concatenate the three serializations and read as one message.
- byte [] result = new byte[result1.length + result2.length + result3.length];
- System.arraycopy(result1, 0, result, 0, result1.length);
- System.arraycopy(result2, 0, result, result1.length, result2.length);
- System.arraycopy(result3, 0, result, result1.length + result2.length, result3.length);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(789, newMsg.optionalInt32);
- assertEquals(3, newMsg.repeatedInt32.length);
- assertEquals(234, newMsg.repeatedInt32[0]);
- assertEquals(123, newMsg.repeatedInt32[1]);
- assertEquals(456, newMsg.repeatedInt32[2]);
- }
-
- public void testNanoRepeatedNestedEnumReMerge() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.repeatedNestedEnum = new int[] { TestAllTypesNano.FOO };
- byte [] result1 = MessageNano.toByteArray(msg);
-
- msg.clear().optionalInt32 = 789;
- byte [] result2 = MessageNano.toByteArray(msg);
-
- msg.clear().repeatedNestedEnum = new int[] { TestAllTypesNano.BAR, TestAllTypesNano.FOO };
- byte [] result3 = MessageNano.toByteArray(msg);
-
- // Concatenate the three serializations and read as one message.
- byte [] result = new byte[result1.length + result2.length + result3.length];
- System.arraycopy(result1, 0, result, 0, result1.length);
- System.arraycopy(result2, 0, result, result1.length, result2.length);
- System.arraycopy(result3, 0, result, result1.length + result2.length, result3.length);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(789, newMsg.optionalInt32);
- assertEquals(3, newMsg.repeatedNestedEnum.length);
- assertEquals(TestAllTypesNano.FOO, newMsg.repeatedNestedEnum[0]);
- assertEquals(TestAllTypesNano.BAR, newMsg.repeatedNestedEnum[1]);
- assertEquals(TestAllTypesNano.FOO, newMsg.repeatedNestedEnum[2]);
- }
-
- public void testNanoRepeatedNestedMessageReMerge() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- TestAllTypesNano.NestedMessage nestedMsg0 =
- new TestAllTypesNano.NestedMessage();
- nestedMsg0.bb = 0;
- TestAllTypesNano.NestedMessage nestedMsg1 =
- new TestAllTypesNano.NestedMessage();
- nestedMsg1.bb = 1;
- TestAllTypesNano.NestedMessage nestedMsg2 =
- new TestAllTypesNano.NestedMessage();
- nestedMsg2.bb = 2;
-
- msg.repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] { nestedMsg0 };
- byte [] result1 = MessageNano.toByteArray(msg);
-
- msg.clear().optionalInt32 = 789;
- byte [] result2 = MessageNano.toByteArray(msg);
-
- msg.clear().repeatedNestedMessage =
- new TestAllTypesNano.NestedMessage[] { nestedMsg1, nestedMsg2 };
- byte [] result3 = MessageNano.toByteArray(msg);
-
- // Concatenate the three serializations and read as one message.
- byte [] result = new byte[result1.length + result2.length + result3.length];
- System.arraycopy(result1, 0, result, 0, result1.length);
- System.arraycopy(result2, 0, result, result1.length, result2.length);
- System.arraycopy(result3, 0, result, result1.length + result2.length, result3.length);
-
- TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result);
- assertEquals(789, newMsg.optionalInt32);
- assertEquals(3, newMsg.repeatedNestedMessage.length);
- assertEquals(nestedMsg0.bb, newMsg.repeatedNestedMessage[0].bb);
- assertEquals(nestedMsg1.bb, newMsg.repeatedNestedMessage[1].bb);
- assertEquals(nestedMsg2.bb, newMsg.repeatedNestedMessage[2].bb);
- }
-
- /**
- * Tests that invalid enum values from the wire are not accepted.
- */
- public void testNanoEnumValidity() throws Exception {
- final int invalid = 120;
- final int alsoInvalid = 121;
-
- EnumValidity.M m = new EnumValidity.M();
- // Sanity check & baseline of the assertions for the first case below.
- assertEquals(EnumValidity.E.default_, m.optionalE);
- assertEquals(EnumValidity.E.BAZ, m.defaultE);
-
- m.optionalE = invalid;
- m.defaultE = invalid;
- // E contains all valid values
- m.repeatedE = new int[] {EnumValidity.E.FOO, EnumValidity.E.BAR};
- m.packedE = new int[] {EnumValidity.E.FOO, EnumValidity.E.BAZ};
- // E2 contains some invalid values
- m.repeatedE2 = new int[] {invalid, EnumValidity.E.BAR, alsoInvalid};
- m.packedE2 = new int[] {EnumValidity.E.FOO, invalid, alsoInvalid};
- // E3 contains all invalid values
- m.repeatedE3 = new int[] {invalid, invalid};
- m.packedE3 = new int[] {alsoInvalid, alsoInvalid};
- byte[] serialized = MessageNano.toByteArray(m);
- // Sanity check that we do have all data in the byte array.
- assertEquals(31, serialized.length);
-
- // Test 1: tests that invalid values aren't included in the deserialized message.
- EnumValidity.M deserialized = MessageNano.mergeFrom(new EnumValidity.M(), serialized);
- assertEquals(EnumValidity.E.default_, deserialized.optionalE);
- assertEquals(EnumValidity.E.BAZ, deserialized.defaultE);
- assertTrue(Arrays.equals(
- new int[] {EnumValidity.E.FOO, EnumValidity.E.BAR}, deserialized.repeatedE));
- assertTrue(Arrays.equals(
- new int[] {EnumValidity.E.FOO, EnumValidity.E.BAZ}, deserialized.packedE));
- assertTrue(Arrays.equals(
- new int[] {EnumValidity.E.BAR}, deserialized.repeatedE2));
- assertTrue(Arrays.equals(
- new int[] {EnumValidity.E.FOO}, deserialized.packedE2));
- assertEquals(0, deserialized.repeatedE3.length);
- assertEquals(0, deserialized.packedE3.length);
-
- // Test 2: tests that invalid values do not override previous values in the field, including
- // arrays, including pre-existing invalid values.
- deserialized.optionalE = EnumValidity.E.BAR;
- deserialized.defaultE = alsoInvalid;
- deserialized.repeatedE = new int[] {EnumValidity.E.BAZ};
- deserialized.packedE = new int[] {EnumValidity.E.BAZ, alsoInvalid};
- deserialized.repeatedE2 = new int[] {invalid, alsoInvalid};
- deserialized.packedE2 = null;
- deserialized.repeatedE3 = null;
- deserialized.packedE3 = new int[0];
- MessageNano.mergeFrom(deserialized, serialized);
- assertEquals(EnumValidity.E.BAR, deserialized.optionalE);
- assertEquals(alsoInvalid, deserialized.defaultE);
- assertTrue(Arrays.equals(
- new int[] {EnumValidity.E.BAZ, /* + */ EnumValidity.E.FOO, EnumValidity.E.BAR},
- deserialized.repeatedE));
- assertTrue(Arrays.equals(
- new int[] {EnumValidity.E.BAZ, alsoInvalid, /* + */ EnumValidity.E.FOO, EnumValidity.E.BAZ},
- deserialized.packedE));
- assertTrue(Arrays.equals(
- new int[] {invalid, alsoInvalid, /* + */ EnumValidity.E.BAR},
- deserialized.repeatedE2));
- assertTrue(Arrays.equals(
- new int[] {/* <null> + */ EnumValidity.E.FOO},
- deserialized.packedE2));
- assertNull(deserialized.repeatedE3); // null + all invalid == null
- assertEquals(0, deserialized.packedE3.length); // empty + all invalid == empty
-
- // Test 3: reading by alternative forms
- EnumValidity.Alt alt = MessageNano.mergeFrom(new EnumValidity.Alt(), serialized);
- assertEquals(EnumValidity.E.BAR, // last valid value in m.repeatedE2
- alt.repeatedE2AsOptional);
- assertTrue(Arrays.equals(new int[] {EnumValidity.E.FOO}, alt.packedE2AsNonPacked));
- assertEquals(0, alt.nonPackedE3AsPacked.length);
- }
-
- /**
- * Tests the same as {@link #testNanoEnumValidity()} with accessor style. Repeated fields are
- * not re-tested here because they are not affected by the accessor style.
- */
- public void testNanoEnumValidityAccessors() throws Exception {
- final int invalid = 120;
- final int alsoInvalid = 121;
-
- EnumValidityAccessors.M m = new EnumValidityAccessors.M();
- // Sanity check & baseline of the assertions for the first case below.
- assertEquals(EnumValidityAccessors.default_, m.getOptionalE());
- assertEquals(EnumValidityAccessors.BAZ, m.getDefaultE());
-
- m.setOptionalE(invalid);
- m.setDefaultE(invalid);
- // Set repeatedE2 for Alt.repeatedE2AsOptional
- m.repeatedE2 = new int[] {invalid, EnumValidityAccessors.BAR, alsoInvalid};
- byte[] serialized = MessageNano.toByteArray(m);
- // Sanity check that we do have all data in the byte array.
- assertEquals(10, serialized.length);
-
- // Test 1: tests that invalid values aren't included in the deserialized message.
- EnumValidityAccessors.M deserialized =
- MessageNano.mergeFrom(new EnumValidityAccessors.M(), serialized);
- assertEquals(EnumValidityAccessors.default_, deserialized.getOptionalE());
- assertEquals(EnumValidityAccessors.BAZ, deserialized.getDefaultE());
-
- // Test 2: tests that invalid values do not override previous values in the field, including
- // pre-existing invalid values.
- deserialized.setOptionalE(EnumValidityAccessors.BAR);
- deserialized.setDefaultE(alsoInvalid);
- MessageNano.mergeFrom(deserialized, serialized);
- assertEquals(EnumValidityAccessors.BAR, deserialized.getOptionalE());
- assertEquals(alsoInvalid, deserialized.getDefaultE());
-
- // Test 3: reading by alternative forms
- EnumValidityAccessors.Alt alt =
- MessageNano.mergeFrom(new EnumValidityAccessors.Alt(), serialized);
- assertEquals(EnumValidityAccessors.BAR, // last valid value in m.repeatedE2
- alt.getRepeatedE2AsOptional());
- }
-
- /**
- * Tests that code generation correctly wraps a single message into its outer
- * class. The class {@code SingleMessageNano} is imported from the outer
- * class {@code UnittestSingleNano}, whose name is implicit. Any error would
- * cause this method to fail compilation.
- */
- public void testNanoSingle() throws Exception {
- SingleMessageNano msg = new SingleMessageNano();
- assertNotNull(msg);
- }
-
- /**
- * Tests that code generation correctly skips generating the outer class if
- * unnecessary, letting a file-scope entity have the same name. The class
- * {@code MultipleNameClashNano} shares the same name with the file's outer
- * class defined explicitly, but the file contains no other entities and has
- * java_multiple_files set. Any error would cause this method to fail
- * compilation.
- */
- public void testNanoMultipleNameClash() throws Exception {
- MultipleNameClashNano msg = new MultipleNameClashNano();
- msg.field = 0;
- }
-
- /**
- * Tests that code generation correctly handles enums in different scopes in
- * a source file with the option java_multiple_files set to true. Any error
- * would cause this method to fail compilation.
- */
- public void testNanoMultipleEnumScoping() throws Exception {
- FileScopeEnumRefNano msg1 = new FileScopeEnumRefNano();
- msg1.enumField = UnittestMultipleNano.ONE;
- MessageScopeEnumRefNano msg2 = new MessageScopeEnumRefNano();
- msg2.enumField = MessageScopeEnumRefNano.TWO;
- }
-
- /**
- * Tests that code generation with mixed values of the java_multiple_files
- * options between the main source file and the imported source files would
- * generate correct references. Any error would cause this method to fail
- * compilation.
- */
- public void testNanoMultipleImportingNonMultiple() throws Exception {
- UnittestImportNano.ImportMessageNano importMsg = new UnittestImportNano.ImportMessageNano();
- MultipleImportingNonMultipleNano1 nano1 = new MultipleImportingNonMultipleNano1();
- nano1.field = importMsg;
- MultipleImportingNonMultipleNano2 nano2 = new MultipleImportingNonMultipleNano2();
- nano2.nano1 = nano1;
- }
-
- public void testNanoDefaults() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- for (int i = 0; i < 2; i++) {
- assertEquals(41, msg.defaultInt32);
- assertEquals(42, msg.defaultInt64);
- assertEquals(43, msg.defaultUint32);
- assertEquals(44, msg.defaultUint64);
- assertEquals(-45, msg.defaultSint32);
- assertEquals(46, msg.defaultSint64);
- assertEquals(47, msg.defaultFixed32);
- assertEquals(48, msg.defaultFixed64);
- assertEquals(49, msg.defaultSfixed32);
- assertEquals(-50, msg.defaultSfixed64);
- assertTrue(51.5f == msg.defaultFloat);
- assertTrue(52.0e3 == msg.defaultDouble);
- assertEquals(true, msg.defaultBool);
- assertEquals("hello", msg.defaultString);
- assertEquals("world", new String(msg.defaultBytes, InternalNano.UTF_8));
- assertEquals("dünya", msg.defaultStringNonascii);
- assertEquals("dünyab", new String(msg.defaultBytesNonascii, InternalNano.UTF_8));
- assertEquals(TestAllTypesNano.BAR, msg.defaultNestedEnum);
- assertEquals(NanoOuterClass.FOREIGN_NANO_BAR, msg.defaultForeignEnum);
- assertEquals(UnittestImportNano.IMPORT_NANO_BAR, msg.defaultImportEnum);
- assertEquals(Float.POSITIVE_INFINITY, msg.defaultFloatInf);
- assertEquals(Float.NEGATIVE_INFINITY, msg.defaultFloatNegInf);
- assertEquals(Float.NaN, msg.defaultFloatNan);
- assertEquals(Double.POSITIVE_INFINITY, msg.defaultDoubleInf);
- assertEquals(Double.NEGATIVE_INFINITY, msg.defaultDoubleNegInf);
- assertEquals(Double.NaN, msg.defaultDoubleNan);
-
- // Default values are not output, except for required fields.
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 3);
- assertEquals(result.length, msgSerializedSize);
- msg.clear();
- }
- }
-
- public void testDifferentStringLengthsNano() throws Exception {
- // Test string serialization roundtrip using strings of the following lengths,
- // 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
- };
- for (int i : lengths) {
- testEncodingOfString('q', i); // 1 byte per char
- testEncodingOfString('\u07FF', i); // 2 bytes per char
- testEncodingOfString('\u0981', i); // 3 bytes per char
- }
- }
-
- /** Regression test for https://github.com/google/protobuf/issues/292 */
- public void testCorrectExceptionThrowWhenEncodingStringsWithoutEnoughSpace() throws Exception {
- String testCase = "Foooooooo";
- assertEquals(CodedOutputByteBufferNano.computeRawVarint32Size(testCase.length()),
- CodedOutputByteBufferNano.computeRawVarint32Size(testCase.length() * 3));
- assertEquals(11, CodedOutputByteBufferNano.computeStringSize(1, testCase));
- // Tag is one byte, varint describing string length is 1 byte, string length is 9 bytes.
- // An array of size 1 will cause a failure when trying to write the varint.
- for (int i = 0; i < 11; i++) {
- CodedOutputByteBufferNano bufferNano = CodedOutputByteBufferNano.newInstance(new byte[i]);
- try {
- bufferNano.writeString(1, testCase);
- fail("Should have thrown an out of space exception");
- } catch (CodedOutputByteBufferNano.OutOfSpaceException expected) {}
- }
- }
-
- private void testEncodingOfString(char c, int length) throws InvalidProtocolBufferNanoException {
- TestAllTypesNano testAllTypesNano = new TestAllTypesNano();
- final String fullString = fullString(c, length);
- testAllTypesNano.optionalString = fullString;
- final TestAllTypesNano resultNano = new TestAllTypesNano();
- MessageNano.mergeFrom(resultNano, MessageNano.toByteArray(testAllTypesNano));
- assertEquals(fullString, resultNano.optionalString);
- }
-
- private String fullString(char c, int length) {
- char[] result = new char[length];
- Arrays.fill(result, c);
- return new String(result);
- }
-
- public void testNanoWithHasParseFrom() throws Exception {
- TestAllTypesNanoHas msg = null;
- // Test false on creation, after clear and upon empty parse.
- for (int i = 0; i < 3; i++) {
- if (i == 0) {
- msg = new TestAllTypesNanoHas();
- } else if (i == 1) {
- msg.clear();
- } else if (i == 2) {
- msg = TestAllTypesNanoHas.parseFrom(new byte[0]);
- }
- assertFalse(msg.hasOptionalInt32);
- assertFalse(msg.hasOptionalString);
- assertFalse(msg.hasOptionalBytes);
- assertFalse(msg.hasOptionalNestedEnum);
- assertFalse(msg.hasDefaultInt32);
- assertFalse(msg.hasDefaultString);
- assertFalse(msg.hasDefaultBytes);
- assertFalse(msg.hasDefaultFloatNan);
- assertFalse(msg.hasDefaultNestedEnum);
- assertFalse(msg.hasId);
- assertFalse(msg.hasRequiredEnum);
- msg.optionalInt32 = 123;
- msg.optionalNestedMessage = new TestAllTypesNanoHas.NestedMessage();
- msg.optionalNestedMessage.bb = 2;
- msg.optionalNestedEnum = TestAllTypesNano.BAZ;
- }
-
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 10);
- assertEquals(result.length, msgSerializedSize);
-
- // Has fields true upon parse.
- TestAllTypesNanoHas newMsg = TestAllTypesNanoHas.parseFrom(result);
- assertEquals(123, newMsg.optionalInt32);
- assertTrue(newMsg.hasOptionalInt32);
- assertEquals(2, newMsg.optionalNestedMessage.bb);
- assertTrue(newMsg.optionalNestedMessage.hasBb);
- assertEquals(TestAllTypesNanoHas.BAZ, newMsg.optionalNestedEnum);
- assertTrue(newMsg.hasOptionalNestedEnum);
- }
-
- public void testNanoWithHasSerialize() throws Exception {
- TestAllTypesNanoHas msg = new TestAllTypesNanoHas();
- msg.hasOptionalInt32 = true;
- msg.hasOptionalString = true;
- msg.hasOptionalBytes = true;
- msg.optionalNestedMessage = new TestAllTypesNanoHas.NestedMessage();
- msg.optionalNestedMessage.hasBb = true;
- msg.hasOptionalNestedEnum = true;
- msg.hasDefaultInt32 = true;
- msg.hasDefaultString = true;
- msg.hasDefaultBytes = true;
- msg.hasDefaultFloatNan = true;
- msg.hasDefaultNestedEnum = true;
- msg.hasId = true;
- msg.hasRequiredEnum = true;
-
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- assertEquals(result.length, msgSerializedSize);
-
- // Now deserialize and find that all fields are set and equal to their defaults.
- TestAllTypesNanoHas newMsg = TestAllTypesNanoHas.parseFrom(result);
- assertTrue(newMsg.hasOptionalInt32);
- assertTrue(newMsg.hasOptionalString);
- assertTrue(newMsg.hasOptionalBytes);
- assertTrue(newMsg.optionalNestedMessage.hasBb);
- assertTrue(newMsg.hasOptionalNestedEnum);
- assertTrue(newMsg.hasDefaultInt32);
- assertTrue(newMsg.hasDefaultString);
- assertTrue(newMsg.hasDefaultBytes);
- assertTrue(newMsg.hasDefaultFloatNan);
- assertTrue(newMsg.hasDefaultNestedEnum);
- assertTrue(newMsg.hasId);
- assertTrue(newMsg.hasRequiredEnum);
- assertEquals(0, newMsg.optionalInt32);
- assertEquals(0, newMsg.optionalString.length());
- assertEquals(0, newMsg.optionalBytes.length);
- assertEquals(0, newMsg.optionalNestedMessage.bb);
- assertEquals(TestAllTypesNanoHas.FOO, newMsg.optionalNestedEnum);
- assertEquals(41, newMsg.defaultInt32);
- assertEquals("hello", newMsg.defaultString);
- assertEquals("world", new String(newMsg.defaultBytes, InternalNano.UTF_8));
- assertEquals(TestAllTypesNanoHas.BAR, newMsg.defaultNestedEnum);
- assertEquals(Float.NaN, newMsg.defaultFloatNan);
- assertEquals(0, newMsg.id);
- assertEquals(TestAllTypesNanoHas.FOO, newMsg.requiredEnum);
- }
-
- public void testNanoWithAccessorsBasic() throws Exception {
- TestNanoAccessors msg = new TestNanoAccessors();
-
- // Makes sure required, repeated, and message fields are still public
- msg.id = 3;
- msg.repeatedBytes = new byte[2][3];
- msg.optionalNestedMessage = null;
-
- // Test accessors
- assertEquals(0, msg.getOptionalInt32());
- assertFalse(msg.hasOptionalInt32());
- msg.setOptionalInt32(135);
- assertEquals(135, msg.getOptionalInt32());
- assertTrue(msg.hasOptionalInt32());
- msg.clearOptionalInt32();
- assertFalse(msg.hasOptionalInt32());
- msg.setOptionalInt32(0); // default value
- assertTrue(msg.hasOptionalInt32());
-
- // Test NPE
- try {
- msg.setOptionalBytes(null);
- fail();
- } catch (NullPointerException expected) {}
- try {
- msg.setOptionalString(null);
- fail();
- } catch (NullPointerException expected) {}
-
- // Test has bit on bytes field with defaults and clear() re-clones the default array
- assertFalse(msg.hasDefaultBytes());
- byte[] defaultBytes = msg.getDefaultBytes();
- msg.setDefaultBytes(defaultBytes);
- assertTrue(msg.hasDefaultBytes());
- msg.clearDefaultBytes();
- assertFalse(msg.hasDefaultBytes());
- defaultBytes[0]++; // modify original array
- assertFalse(Arrays.equals(defaultBytes, msg.getDefaultBytes()));
-
- // Test has bits that require additional bit fields
- assertFalse(msg.hasBitFieldCheck());
- msg.setBitFieldCheck(0);
- assertTrue(msg.hasBitFieldCheck());
- assertFalse(msg.hasBeforeBitFieldCheck()); // checks bit field does not leak
- assertFalse(msg.hasAfterBitFieldCheck());
-
- // Test clear() clears has bits
- msg.setOptionalString("hi");
- msg.setDefaultString("there");
- msg.clear();
- assertFalse(msg.hasOptionalString());
- assertFalse(msg.hasDefaultString());
- assertFalse(msg.hasBitFieldCheck());
-
- // Test set() and clear() returns itself (compiles = success)
- msg.clear()
- .setOptionalInt32(3)
- .clearDefaultBytes()
- .setOptionalString("4");
- }
-
- public void testNanoWithAccessorsParseFrom() throws Exception {
- TestNanoAccessors msg = null;
- // Test false on creation, after clear and upon empty parse.
- for (int i = 0; i < 3; i++) {
- if (i == 0) {
- msg = new TestNanoAccessors();
- } else if (i == 1) {
- msg.clear();
- } else if (i == 2) {
- msg = TestNanoAccessors.parseFrom(new byte[0]);
- }
- assertFalse(msg.hasOptionalInt32());
- assertFalse(msg.hasOptionalString());
- assertFalse(msg.hasOptionalBytes());
- assertFalse(msg.hasOptionalNestedEnum());
- assertFalse(msg.hasDefaultInt32());
- assertFalse(msg.hasDefaultString());
- assertFalse(msg.hasDefaultBytes());
- assertFalse(msg.hasDefaultFloatNan());
- assertFalse(msg.hasDefaultNestedEnum());
- msg.optionalNestedMessage = new TestNanoAccessors.NestedMessage();
- msg.optionalNestedMessage.setBb(2);
- msg.setOptionalNestedEnum(TestNanoAccessors.BAZ);
- msg.setDefaultInt32(msg.getDefaultInt32());
- }
-
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length);
- assertTrue(msgSerializedSize == 14);
- assertEquals(result.length, msgSerializedSize);
-
- // Has fields true upon parse.
- TestNanoAccessors newMsg = TestNanoAccessors.parseFrom(result);
- assertEquals(2, newMsg.optionalNestedMessage.getBb());
- assertTrue(newMsg.optionalNestedMessage.hasBb());
- assertEquals(TestNanoAccessors.BAZ, newMsg.getOptionalNestedEnum());
- assertTrue(newMsg.hasOptionalNestedEnum());
-
- // Has field true on fields with explicit default values from wire.
- assertTrue(newMsg.hasDefaultInt32());
- assertEquals(41, newMsg.getDefaultInt32());
- }
-
- public void testNanoWithAccessorsPublicFieldTypes() throws Exception {
- TestNanoAccessors msg = new TestNanoAccessors();
- assertNull(msg.optionalNestedMessage);
- assertEquals(0, msg.id);
- assertEquals(0, msg.repeatedNestedEnum.length);
-
- TestNanoAccessors newMsg = TestNanoAccessors.parseFrom(MessageNano.toByteArray(msg));
- assertNull(newMsg.optionalNestedMessage);
- assertEquals(0, newMsg.id);
- assertEquals(0, newMsg.repeatedNestedEnum.length);
-
- TestNanoAccessors.NestedMessage nestedMessage = new TestNanoAccessors.NestedMessage();
- nestedMessage.setBb(5);
- newMsg.optionalNestedMessage = nestedMessage;
- newMsg.id = -1;
- newMsg.repeatedNestedEnum = new int[] { TestAllTypesNano.FOO };
-
- TestNanoAccessors newMsg2 = TestNanoAccessors.parseFrom(MessageNano.toByteArray(newMsg));
- assertEquals(nestedMessage.getBb(), newMsg2.optionalNestedMessage.getBb());
- assertEquals(-1, newMsg2.id);
- assertEquals(TestAllTypesNano.FOO, newMsg2.repeatedNestedEnum[0]);
-
- newMsg2.optionalNestedMessage = null;
- newMsg2.id = 0;
- newMsg2.repeatedNestedEnum = null;
-
- TestNanoAccessors newMsg3 = TestNanoAccessors.parseFrom(MessageNano.toByteArray(newMsg2));
- assertNull(newMsg3.optionalNestedMessage);
- assertEquals(0, newMsg3.id);
- assertEquals(0, newMsg3.repeatedNestedEnum.length);
- }
-
- public void testNanoWithAccessorsSerialize() throws Exception {
- TestNanoAccessors msg = new TestNanoAccessors();
- msg.setOptionalInt32(msg.getOptionalInt32());
- msg.setOptionalString(msg.getOptionalString());
- msg.setOptionalBytes(msg.getOptionalBytes());
- TestNanoAccessors.NestedMessage nestedMessage = new TestNanoAccessors.NestedMessage();
- nestedMessage.setBb(nestedMessage.getBb());
- msg.optionalNestedMessage = nestedMessage;
- msg.setOptionalNestedEnum(msg.getOptionalNestedEnum());
- msg.setDefaultInt32(msg.getDefaultInt32());
- msg.setDefaultString(msg.getDefaultString());
- msg.setDefaultBytes(msg.getDefaultBytes());
- msg.setDefaultFloatNan(msg.getDefaultFloatNan());
- msg.setDefaultNestedEnum(msg.getDefaultNestedEnum());
-
- byte [] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- assertEquals(result.length, msgSerializedSize);
-
- // Now deserialize and find that all fields are set and equal to their defaults.
- TestNanoAccessors newMsg = TestNanoAccessors.parseFrom(result);
- assertTrue(newMsg.hasOptionalInt32());
- assertTrue(newMsg.hasOptionalString());
- assertTrue(newMsg.hasOptionalBytes());
- assertTrue(newMsg.optionalNestedMessage.hasBb());
- assertTrue(newMsg.hasOptionalNestedEnum());
- assertTrue(newMsg.hasDefaultInt32());
- assertTrue(newMsg.hasDefaultString());
- assertTrue(newMsg.hasDefaultBytes());
- assertTrue(newMsg.hasDefaultFloatNan());
- assertTrue(newMsg.hasDefaultNestedEnum());
- assertEquals(0, newMsg.getOptionalInt32());
- assertEquals(0, newMsg.getOptionalString().length());
- assertEquals(0, newMsg.getOptionalBytes().length);
- assertEquals(0, newMsg.optionalNestedMessage.getBb());
- assertEquals(TestNanoAccessors.FOO, newMsg.getOptionalNestedEnum());
- assertEquals(41, newMsg.getDefaultInt32());
- assertEquals("hello", newMsg.getDefaultString());
- assertEquals("world", new String(newMsg.getDefaultBytes(), InternalNano.UTF_8));
- assertEquals(TestNanoAccessors.BAR, newMsg.getDefaultNestedEnum());
- assertEquals(Float.NaN, newMsg.getDefaultFloatNan());
- assertEquals(0, newMsg.id);
- }
-
- public void testNanoJavaEnumStyle() throws Exception {
- EnumClassNanos.EnumClassNano msg = new EnumClassNanos.EnumClassNano();
- assertEquals(EnumClassNanos.FileScopeEnum.ONE, msg.one);
- assertEquals(EnumClassNanos.EnumClassNano.MessageScopeEnum.TWO, msg.two);
-
- EnumClassNanoMultiple msg2 = new EnumClassNanoMultiple();
- assertEquals(FileScopeEnumMultiple.THREE, msg2.three);
- assertEquals(EnumClassNanoMultiple.MessageScopeEnumMultiple.FOUR, msg2.four);
- }
-
- /**
- * Tests that fields with a default value of NaN are not serialized when
- * set to NaN. This is a special case as NaN != NaN, so normal equality
- * checks don't work.
- */
- public void testNanoNotANumberDefaults() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.defaultDoubleNan = 0;
- msg.defaultFloatNan = 0;
- byte[] result = MessageNano.toByteArray(msg);
- int msgSerializedSize = msg.getSerializedSize();
- assertTrue(result.length == msgSerializedSize);
- assertTrue(msgSerializedSize > 3);
-
- msg.defaultDoubleNan = Double.NaN;
- msg.defaultFloatNan = Float.NaN;
- result = MessageNano.toByteArray(msg);
- msgSerializedSize = msg.getSerializedSize();
- assertEquals(3, result.length);
- assertEquals(3, msgSerializedSize);
- }
-
- /**
- * Test that a bug in skipRawBytes() has been fixed: if the skip skips
- * exactly up to a limit, this should not break things.
- */
- public void testSkipRawBytesBug() throws Exception {
- byte[] rawBytes = new byte[] { 1, 2 };
- CodedInputByteBufferNano input = CodedInputByteBufferNano.newInstance(rawBytes);
-
- int limit = input.pushLimit(1);
- input.skipRawBytes(1);
- input.popLimit(limit);
- assertEquals(2, input.readRawByte());
- }
-
- /**
- * Test that a bug in skipRawBytes() has been fixed: if the skip skips
- * past the end of a buffer with a limit that has been set past the end of
- * that buffer, this should not break things.
- */
- public void testSkipRawBytesPastEndOfBufferWithLimit() throws Exception {
- byte[] rawBytes = new byte[] { 1, 2, 3, 4, 5 };
- CodedInputByteBufferNano input = CodedInputByteBufferNano.newInstance(rawBytes);
-
- int limit = input.pushLimit(4);
- // In order to expose the bug we need to read at least one byte to prime the
- // buffer inside the CodedInputStream.
- assertEquals(1, input.readRawByte());
- // Skip to the end of the limit.
- input.skipRawBytes(3);
- assertTrue(input.isAtEnd());
- input.popLimit(limit);
- assertEquals(5, input.readRawByte());
- }
-
- // Test a smattering of various proto types for printing
- public void testMessageNanoPrinter() {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.optionalInt32 = 14;
- msg.optionalFloat = 42.3f;
- msg.optionalString = "String \"with' both quotes";
- msg.optionalBytes = new byte[] {'"', '\0', 1, 8};
- msg.optionalGroup = new TestAllTypesNano.OptionalGroup();
- msg.optionalGroup.a = 15;
- msg.repeatedInt64 = new long[2];
- msg.repeatedInt64[0] = 1L;
- msg.repeatedInt64[1] = -1L;
- msg.repeatedBytes = new byte[2][];
- msg.repeatedBytes[1] = new byte[] {'h', 'e', 'l', 'l', 'o'};
- msg.repeatedGroup = new TestAllTypesNano.RepeatedGroup[2];
- msg.repeatedGroup[0] = new TestAllTypesNano.RepeatedGroup();
- msg.repeatedGroup[0].a = -27;
- msg.repeatedGroup[1] = new TestAllTypesNano.RepeatedGroup();
- msg.repeatedGroup[1].a = -72;
- msg.optionalNestedMessage = new TestAllTypesNano.NestedMessage();
- msg.optionalNestedMessage.bb = 7;
- msg.repeatedNestedMessage = new TestAllTypesNano.NestedMessage[2];
- msg.repeatedNestedMessage[0] = new TestAllTypesNano.NestedMessage();
- msg.repeatedNestedMessage[0].bb = 77;
- msg.repeatedNestedMessage[1] = new TestAllTypesNano.NestedMessage();
- msg.repeatedNestedMessage[1].bb = 88;
- msg.optionalNestedEnum = TestAllTypesNano.BAZ;
- msg.repeatedNestedEnum = new int[2];
- msg.repeatedNestedEnum[0] = TestAllTypesNano.BAR;
- msg.repeatedNestedEnum[1] = TestAllTypesNano.FOO;
- msg.repeatedStringPiece = new String[] {null, "world"};
- msg.setOneofString("hello");
-
- String protoPrint = msg.toString();
- assertTrue(protoPrint.contains("optional_int32: 14"));
- assertTrue(protoPrint.contains("optional_float: 42.3"));
- assertTrue(protoPrint.contains("optional_double: 0.0"));
- assertTrue(protoPrint.contains("optional_string: \"String \\u0022with\\u0027 both quotes\""));
- assertTrue(protoPrint.contains("optional_bytes: \"\\\"\\000\\001\\010\""));
- assertTrue(protoPrint.contains("optional_group <\n a: 15\n>"));
-
- assertTrue(protoPrint.contains("repeated_int64: 1\nrepeated_int64: -1"));
- assertFalse(protoPrint.contains("repeated_bytes: \"\"")); // null should be dropped
- assertTrue(protoPrint.contains("repeated_bytes: \"hello\""));
- assertTrue(protoPrint.contains("repeated_group <\n a: -27\n>\n"
- + "repeated_group <\n a: -72\n>"));
- assertTrue(protoPrint.contains("optional_nested_message <\n bb: 7\n>"));
- assertTrue(protoPrint.contains("repeated_nested_message <\n bb: 77\n>\n"
- + "repeated_nested_message <\n bb: 88\n>"));
- assertTrue(protoPrint.contains("optional_nested_enum: 3"));
- assertTrue(protoPrint.contains("repeated_nested_enum: 2\nrepeated_nested_enum: 1"));
- assertTrue(protoPrint.contains("default_int32: 41"));
- assertTrue(protoPrint.contains("default_string: \"hello\""));
- assertFalse(protoPrint.contains("repeated_string_piece: \"\"")); // null should be dropped
- assertTrue(protoPrint.contains("repeated_string_piece: \"world\""));
- assertTrue(protoPrint.contains("oneof_string: \"hello\""));
- }
-
- public void testMessageNanoPrinterAccessors() throws Exception {
- TestNanoAccessors msg = new TestNanoAccessors();
- msg.setOptionalInt32(13);
- msg.setOptionalString("foo");
- msg.setOptionalBytes(new byte[] {'"', '\0', 1, 8});
- msg.optionalNestedMessage = new TestNanoAccessors.NestedMessage();
- msg.optionalNestedMessage.setBb(7);
- msg.setOptionalNestedEnum(TestNanoAccessors.BAZ);
- msg.repeatedInt32 = new int[] { 1, -1 };
- msg.repeatedString = new String[] { "Hello", "world" };
- msg.repeatedBytes = new byte[2][];
- msg.repeatedBytes[1] = new byte[] {'h', 'e', 'l', 'l', 'o'};
- msg.repeatedNestedMessage = new TestNanoAccessors.NestedMessage[2];
- msg.repeatedNestedMessage[0] = new TestNanoAccessors.NestedMessage();
- msg.repeatedNestedMessage[0].setBb(5);
- msg.repeatedNestedMessage[1] = new TestNanoAccessors.NestedMessage();
- msg.repeatedNestedMessage[1].setBb(6);
- msg.repeatedNestedEnum = new int[] { TestNanoAccessors.FOO, TestNanoAccessors.BAR };
- msg.id = 33;
-
- String protoPrint = msg.toString();
- assertTrue(protoPrint.contains("optional_int32: 13"));
- assertTrue(protoPrint.contains("optional_string: \"foo\""));
- assertTrue(protoPrint.contains("optional_bytes: \"\\\"\\000\\001\\010\""));
- assertTrue(protoPrint.contains("optional_nested_message <\n bb: 7\n>"));
- assertTrue(protoPrint.contains("optional_nested_enum: 3"));
- assertTrue(protoPrint.contains("repeated_int32: 1\nrepeated_int32: -1"));
- assertTrue(protoPrint.contains("repeated_string: \"Hello\"\nrepeated_string: \"world\""));
- assertFalse(protoPrint.contains("repeated_bytes: \"\"")); // null should be dropped
- assertTrue(protoPrint.contains("repeated_bytes: \"hello\""));
- assertTrue(protoPrint.contains("repeated_nested_message <\n bb: 5\n>\n"
- + "repeated_nested_message <\n bb: 6\n>"));
- assertTrue(protoPrint.contains("repeated_nested_enum: 1\nrepeated_nested_enum: 2"));
- assertTrue(protoPrint.contains("id: 33"));
- }
-
- public void testMessageNanoPrinterForMaps() throws Exception {
- TestMap msg = new TestMap();
- MessageValue msgValues[] = new MessageValue[] {
- new MessageValue(), new MessageValue()
- };
- msgValues[0].value = 1;
- msgValues[1].value = 2;
- msg.int32ToBytesField = new HashMap<Integer, byte[]>();
- msg.int32ToBytesField.put(1, new byte[] {'"', '\0'});
- msg.int32ToBytesField.put(2, new byte[] {1, 8});
- msg.stringToInt32Field = new HashMap<String, Integer>();
- msg.stringToInt32Field.put("hello", 1);
- msg.stringToInt32Field.put("world", 2);
- msg.int32ToMessageField = new HashMap<Integer, MapTestProto.TestMap.MessageValue>();
- msg.int32ToMessageField.put(0, msgValues[0]);
- msg.int32ToMessageField.put(1, msgValues[1]);
- msg.int32ToEnumField = new HashMap<Integer, Integer>();
- msg.int32ToEnumField.put(1, 2);
- msg.int32ToEnumField.put(2, 3);
- String protoPrint = msg.toString();
-
- assertTrue(protoPrint.contains(
- "int32_to_bytes_field <\n key: 1\n value: \"\\\"\\000\"\n>"));
- assertTrue(protoPrint.contains(
- "int32_to_bytes_field <\n key: 2\n value: \"\\001\\010\"\n>"));
- assertTrue(protoPrint.contains(
- "string_to_int32_field <\n key: \"hello\"\n value: 1\n>"));
- assertTrue(protoPrint.contains(
- "string_to_int32_field <\n key: \"world\"\n value: 2\n>"));
- assertTrue(protoPrint.contains(
- "int32_to_message_field <\n key: 0\n value <\n value: 1\n"));
- assertTrue(protoPrint.contains(
- "int32_to_message_field <\n key: 1\n value <\n value: 2\n"));
- assertTrue(protoPrint.contains(
- "int32_to_enum_field <\n key: 1\n value: 2\n>"));
- assertTrue(protoPrint.contains(
- "int32_to_enum_field <\n key: 2\n value: 3\n>"));
- }
-
- public void testExtensions() throws Exception {
- Extensions.ExtendableMessage message = new Extensions.ExtendableMessage();
- message.field = 5;
- int[] int32s = {1, 2};
- int[] uint32s = {3, 4};
- int[] sint32s = {-5, -6};
- long[] int64s = {7, 8};
- long[] uint64s = {9, 10};
- long[] sint64s = {-11, -12};
- int[] fixed32s = {13, 14};
- int[] sfixed32s = {-15, -16};
- long[] fixed64s = {17, 18};
- long[] sfixed64s = {-19, -20};
- boolean[] bools = {true, false};
- float[] floats = {2.1f, 2.2f};
- double[] doubles = {2.3, 2.4};
- int[] enums = {Extensions.SECOND_VALUE, Extensions.FIRST_VALUE};
- String[] strings = {"vijfentwintig", "twenty-six"};
- byte[][] bytess = {{2, 7}, {2, 8}};
- AnotherMessage another1 = new AnotherMessage();
- another1.string = "er shi jiu";
- another1.value = false;
- AnotherMessage another2 = new AnotherMessage();
- another2.string = "trente";
- another2.value = true;
- AnotherMessage[] messages = {another1, another2};
- RepeatedExtensions.RepeatedGroup group1 = new RepeatedExtensions.RepeatedGroup();
- group1.a = 31;
- RepeatedExtensions.RepeatedGroup group2 = new RepeatedExtensions.RepeatedGroup();
- group2.a = 32;
- RepeatedExtensions.RepeatedGroup[] groups = {group1, group2};
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedInt32));
- message.setExtension(RepeatedExtensions.repeatedInt32, int32s);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedInt32));
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedUint32));
- message.setExtension(RepeatedExtensions.repeatedUint32, uint32s);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedUint32));
- message.setExtension(RepeatedExtensions.repeatedSint32, sint32s);
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedInt64));
- message.setExtension(RepeatedExtensions.repeatedInt64, int64s);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedInt64));
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedUint64));
- message.setExtension(RepeatedExtensions.repeatedUint64, uint64s);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedUint64));
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedSint64));
- message.setExtension(RepeatedExtensions.repeatedSint64, sint64s);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedSint64));
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedFixed32));
- message.setExtension(RepeatedExtensions.repeatedFixed32, fixed32s);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedFixed32));
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedSfixed32));
- message.setExtension(RepeatedExtensions.repeatedSfixed32, sfixed32s);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedSfixed32));
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedFixed64));
- message.setExtension(RepeatedExtensions.repeatedFixed64, fixed64s);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedFixed64));
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedSfixed64));
- message.setExtension(RepeatedExtensions.repeatedSfixed64, sfixed64s);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedSfixed64));
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedBool));
- message.setExtension(RepeatedExtensions.repeatedBool, bools);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedBool));
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedFloat));
- message.setExtension(RepeatedExtensions.repeatedFloat, floats);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedFloat));
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedDouble));
- message.setExtension(RepeatedExtensions.repeatedDouble, doubles);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedDouble));
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedEnum));
- message.setExtension(RepeatedExtensions.repeatedEnum, enums);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedEnum));
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedString));
- message.setExtension(RepeatedExtensions.repeatedString, strings);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedString));
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedBytes));
- message.setExtension(RepeatedExtensions.repeatedBytes, bytess);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedBytes));
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedMessage));
- message.setExtension(RepeatedExtensions.repeatedMessage, messages);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedMessage));
- assertFalse(message.hasExtension(RepeatedExtensions.repeatedGroup));
- message.setExtension(RepeatedExtensions.repeatedGroup, groups);
- assertTrue(message.hasExtension(RepeatedExtensions.repeatedGroup));
-
- byte[] data = MessageNano.toByteArray(message);
- message = Extensions.ExtendableMessage.parseFrom(data);
- assertEquals(5, message.field);
-
- // Test reading back using SingularExtensions: the retrieved value should equal the last
- // in each array.
- assertEquals(int32s[1], (int) message.getExtension(SingularExtensions.someInt32));
- assertEquals(uint32s[1], (int) message.getExtension(SingularExtensions.someUint32));
- assertEquals(sint32s[1], (int) message.getExtension(SingularExtensions.someSint32));
- assertEquals(int64s[1], (long) message.getExtension(SingularExtensions.someInt64));
- assertEquals(uint64s[1], (long) message.getExtension(SingularExtensions.someUint64));
- assertEquals(sint64s[1], (long) message.getExtension(SingularExtensions.someSint64));
- assertEquals(fixed32s[1], (int) message.getExtension(SingularExtensions.someFixed32));
- assertEquals(sfixed32s[1], (int) message.getExtension(SingularExtensions.someSfixed32));
- assertEquals(fixed64s[1], (long) message.getExtension(SingularExtensions.someFixed64));
- assertEquals(sfixed64s[1], (long) message.getExtension(SingularExtensions.someSfixed64));
- assertEquals(bools[1], (boolean) message.getExtension(SingularExtensions.someBool));
- assertEquals(floats[1], (float) message.getExtension(SingularExtensions.someFloat));
- assertEquals(doubles[1], (double) message.getExtension(SingularExtensions.someDouble));
- assertEquals(enums[1], (int) message.getExtension(SingularExtensions.someEnum));
- assertEquals(strings[1], message.getExtension(SingularExtensions.someString));
- assertTrue(Arrays.equals(bytess[1], message.getExtension(SingularExtensions.someBytes)));
- AnotherMessage deserializedMessage = message.getExtension(SingularExtensions.someMessage);
- assertEquals(another2.string, deserializedMessage.string);
- assertEquals(another2.value, deserializedMessage.value);
- assertEquals(group2.a, message.getExtension(SingularExtensions.someGroup).a);
-
- // Test reading back using RepeatedExtensions: the arrays should be equal.
- message = Extensions.ExtendableMessage.parseFrom(data);
- assertEquals(5, message.field);
- assertTrue(Arrays.equals(int32s, message.getExtension(RepeatedExtensions.repeatedInt32)));
- assertTrue(Arrays.equals(uint32s, message.getExtension(RepeatedExtensions.repeatedUint32)));
- assertTrue(Arrays.equals(sint32s, message.getExtension(RepeatedExtensions.repeatedSint32)));
- assertTrue(Arrays.equals(int64s, message.getExtension(RepeatedExtensions.repeatedInt64)));
- assertTrue(Arrays.equals(uint64s, message.getExtension(RepeatedExtensions.repeatedUint64)));
- assertTrue(Arrays.equals(sint64s, message.getExtension(RepeatedExtensions.repeatedSint64)));
- assertTrue(Arrays.equals(fixed32s, message.getExtension(RepeatedExtensions.repeatedFixed32)));
- assertTrue(Arrays.equals(sfixed32s, message.getExtension(RepeatedExtensions.repeatedSfixed32)));
- assertTrue(Arrays.equals(fixed64s, message.getExtension(RepeatedExtensions.repeatedFixed64)));
- assertTrue(Arrays.equals(sfixed64s, message.getExtension(RepeatedExtensions.repeatedSfixed64)));
- assertTrue(Arrays.equals(bools, message.getExtension(RepeatedExtensions.repeatedBool)));
- assertTrue(Arrays.equals(floats, message.getExtension(RepeatedExtensions.repeatedFloat)));
- assertTrue(Arrays.equals(doubles, message.getExtension(RepeatedExtensions.repeatedDouble)));
- assertTrue(Arrays.equals(enums, message.getExtension(RepeatedExtensions.repeatedEnum)));
- assertTrue(Arrays.equals(strings, message.getExtension(RepeatedExtensions.repeatedString)));
- byte[][] deserializedRepeatedBytes = message.getExtension(RepeatedExtensions.repeatedBytes);
- assertEquals(2, deserializedRepeatedBytes.length);
- assertTrue(Arrays.equals(bytess[0], deserializedRepeatedBytes[0]));
- assertTrue(Arrays.equals(bytess[1], deserializedRepeatedBytes[1]));
- AnotherMessage[] deserializedRepeatedMessage =
- message.getExtension(RepeatedExtensions.repeatedMessage);
- assertEquals(2, deserializedRepeatedMessage.length);
- assertEquals(another1.string, deserializedRepeatedMessage[0].string);
- assertEquals(another1.value, deserializedRepeatedMessage[0].value);
- assertEquals(another2.string, deserializedRepeatedMessage[1].string);
- assertEquals(another2.value, deserializedRepeatedMessage[1].value);
- RepeatedExtensions.RepeatedGroup[] deserializedRepeatedGroup =
- message.getExtension(RepeatedExtensions.repeatedGroup);
- assertEquals(2, deserializedRepeatedGroup.length);
- assertEquals(group1.a, deserializedRepeatedGroup[0].a);
- assertEquals(group2.a, deserializedRepeatedGroup[1].a);
-
- message = Extensions.ExtendableMessage.parseFrom(data);
- assertEquals(5, message.field);
- // Test hasExtension using PackedExtensions.
- assertTrue(message.hasExtension(PackedExtensions.packedInt32));
- assertTrue(message.hasExtension(PackedExtensions.packedUint32));
- assertTrue(message.hasExtension(PackedExtensions.packedSint32));
- assertTrue(message.hasExtension(PackedExtensions.packedInt64));
- assertTrue(message.hasExtension(PackedExtensions.packedUint64));
- assertTrue(message.hasExtension(PackedExtensions.packedSint64));
- assertTrue(message.hasExtension(PackedExtensions.packedFixed32));
- assertTrue(message.hasExtension(PackedExtensions.packedSfixed32));
- assertTrue(message.hasExtension(PackedExtensions.packedFixed64));
- assertTrue(message.hasExtension(PackedExtensions.packedSfixed64));
- assertTrue(message.hasExtension(PackedExtensions.packedBool));
- assertTrue(message.hasExtension(PackedExtensions.packedFloat));
- assertTrue(message.hasExtension(PackedExtensions.packedDouble));
- assertTrue(message.hasExtension(PackedExtensions.packedEnum));
-
- // Test reading back using PackedExtensions: the arrays should be equal, even the fields
- // are non-packed.
- assertTrue(Arrays.equals(int32s, message.getExtension(PackedExtensions.packedInt32)));
- assertTrue(Arrays.equals(uint32s, message.getExtension(PackedExtensions.packedUint32)));
- assertTrue(Arrays.equals(sint32s, message.getExtension(PackedExtensions.packedSint32)));
- assertTrue(Arrays.equals(int64s, message.getExtension(PackedExtensions.packedInt64)));
- assertTrue(Arrays.equals(uint64s, message.getExtension(PackedExtensions.packedUint64)));
- assertTrue(Arrays.equals(sint64s, message.getExtension(PackedExtensions.packedSint64)));
- assertTrue(Arrays.equals(fixed32s, message.getExtension(PackedExtensions.packedFixed32)));
- assertTrue(Arrays.equals(sfixed32s, message.getExtension(PackedExtensions.packedSfixed32)));
- assertTrue(Arrays.equals(fixed64s, message.getExtension(PackedExtensions.packedFixed64)));
- assertTrue(Arrays.equals(sfixed64s, message.getExtension(PackedExtensions.packedSfixed64)));
- assertTrue(Arrays.equals(bools, message.getExtension(PackedExtensions.packedBool)));
- assertTrue(Arrays.equals(floats, message.getExtension(PackedExtensions.packedFloat)));
- assertTrue(Arrays.equals(doubles, message.getExtension(PackedExtensions.packedDouble)));
- assertTrue(Arrays.equals(enums, message.getExtension(PackedExtensions.packedEnum)));
-
- // Now set the packable extension values using PackedExtensions so they're serialized packed.
- message.setExtension(PackedExtensions.packedInt32, int32s);
- message.setExtension(PackedExtensions.packedUint32, uint32s);
- message.setExtension(PackedExtensions.packedSint32, sint32s);
- message.setExtension(PackedExtensions.packedInt64, int64s);
- message.setExtension(PackedExtensions.packedUint64, uint64s);
- message.setExtension(PackedExtensions.packedSint64, sint64s);
- message.setExtension(PackedExtensions.packedFixed32, fixed32s);
- message.setExtension(PackedExtensions.packedSfixed32, sfixed32s);
- message.setExtension(PackedExtensions.packedFixed64, fixed64s);
- message.setExtension(PackedExtensions.packedSfixed64, sfixed64s);
- message.setExtension(PackedExtensions.packedBool, bools);
- message.setExtension(PackedExtensions.packedFloat, floats);
- message.setExtension(PackedExtensions.packedDouble, doubles);
- message.setExtension(PackedExtensions.packedEnum, enums);
-
- // And read back using non-packed RepeatedExtensions.
- byte[] data2 = MessageNano.toByteArray(message);
- message = MessageNano.mergeFrom(new Extensions.ExtendableMessage(), data2);
- assertTrue(Arrays.equals(int32s, message.getExtension(RepeatedExtensions.repeatedInt32)));
- assertTrue(Arrays.equals(uint32s, message.getExtension(RepeatedExtensions.repeatedUint32)));
- assertTrue(Arrays.equals(sint32s, message.getExtension(RepeatedExtensions.repeatedSint32)));
- assertTrue(Arrays.equals(int64s, message.getExtension(RepeatedExtensions.repeatedInt64)));
- assertTrue(Arrays.equals(uint64s, message.getExtension(RepeatedExtensions.repeatedUint64)));
- assertTrue(Arrays.equals(sint64s, message.getExtension(RepeatedExtensions.repeatedSint64)));
- assertTrue(Arrays.equals(fixed32s, message.getExtension(RepeatedExtensions.repeatedFixed32)));
- assertTrue(Arrays.equals(sfixed32s, message.getExtension(RepeatedExtensions.repeatedSfixed32)));
- assertTrue(Arrays.equals(fixed64s, message.getExtension(RepeatedExtensions.repeatedFixed64)));
- assertTrue(Arrays.equals(sfixed64s, message.getExtension(RepeatedExtensions.repeatedSfixed64)));
- assertTrue(Arrays.equals(bools, message.getExtension(RepeatedExtensions.repeatedBool)));
- assertTrue(Arrays.equals(floats, message.getExtension(RepeatedExtensions.repeatedFloat)));
- assertTrue(Arrays.equals(doubles, message.getExtension(RepeatedExtensions.repeatedDouble)));
- assertTrue(Arrays.equals(enums, message.getExtension(RepeatedExtensions.repeatedEnum)));
-
- // Clone the message and ensure it's still equal.
- Extensions.ExtendableMessage clone = message.clone();
- assertEquals(clone, message);
- }
-
- public void testNullExtensions() throws Exception {
- // Check that clearing the extension on an empty message is a no-op.
- Extensions.ExtendableMessage message = new Extensions.ExtendableMessage();
- assertFalse(message.hasExtension(SingularExtensions.someMessage));
- message.setExtension(SingularExtensions.someMessage, null);
- assertFalse(message.hasExtension(SingularExtensions.someMessage));
- assertEquals(0, MessageNano.toByteArray(message).length);
-
- // Check that the message is empty after setting and clearing an extension.
- AnotherMessage another = new AnotherMessage();
- assertFalse(message.hasExtension(SingularExtensions.someMessage));
- message.setExtension(SingularExtensions.someMessage, another);
- assertTrue(message.hasExtension(SingularExtensions.someMessage));
- assertTrue(MessageNano.toByteArray(message).length > 0);
- message.setExtension(SingularExtensions.someMessage, null);
- assertFalse(message.hasExtension(SingularExtensions.someMessage));
- assertEquals(0, MessageNano.toByteArray(message).length);
- }
-
- public void testExtensionsMutation() {
- Extensions.ExtendableMessage extendableMessage = new Extensions.ExtendableMessage();
- extendableMessage.setExtension(SingularExtensions.someMessage,
- new Extensions.AnotherMessage());
-
- extendableMessage.getExtension(SingularExtensions.someMessage).string = "not empty";
-
- assertEquals("not empty",
- extendableMessage.getExtension(SingularExtensions.someMessage).string);
- }
-
- public void testExtensionsMutation_Equals() throws InvalidProtocolBufferNanoException {
- Extensions.ExtendableMessage extendableMessage = new Extensions.ExtendableMessage();
- extendableMessage.field = 5;
- int int32 = 42;
- int[] uint32s = {3, 4};
- int[] sint32s = {-5, -6};
- long[] int64s = {7, 8};
- long[] uint64s = {9, 10};
- long[] sint64s = {-11, -12};
- int[] fixed32s = {13, 14};
- int[] sfixed32s = {-15, -16};
- long[] fixed64s = {17, 18};
- long[] sfixed64s = {-19, -20};
- boolean[] bools = {true, false};
- float[] floats = {2.1f, 2.2f};
- double[] doubles = {2.3, 2.4};
- int[] enums = {Extensions.SECOND_VALUE, Extensions.FIRST_VALUE};
- String[] strings = {"vijfentwintig", "twenty-six"};
- byte[][] bytess = {{2, 7}, {2, 8}};
- AnotherMessage another1 = new AnotherMessage();
- another1.string = "er shi jiu";
- another1.value = false;
- AnotherMessage another2 = new AnotherMessage();
- another2.string = "trente";
- another2.value = true;
- AnotherMessage[] messages = {another1, another2};
- RepeatedExtensions.RepeatedGroup group1 = new RepeatedExtensions.RepeatedGroup();
- group1.a = 31;
- RepeatedExtensions.RepeatedGroup group2 = new RepeatedExtensions.RepeatedGroup();
- group2.a = 32;
- RepeatedExtensions.RepeatedGroup[] groups = {group1, group2};
- extendableMessage.setExtension(SingularExtensions.someInt32, int32);
- extendableMessage.setExtension(RepeatedExtensions.repeatedUint32, uint32s);
- extendableMessage.setExtension(RepeatedExtensions.repeatedSint32, sint32s);
- extendableMessage.setExtension(RepeatedExtensions.repeatedInt64, int64s);
- extendableMessage.setExtension(RepeatedExtensions.repeatedUint64, uint64s);
- extendableMessage.setExtension(RepeatedExtensions.repeatedSint64, sint64s);
- extendableMessage.setExtension(RepeatedExtensions.repeatedFixed32, fixed32s);
- extendableMessage.setExtension(RepeatedExtensions.repeatedSfixed32, sfixed32s);
- extendableMessage.setExtension(RepeatedExtensions.repeatedFixed64, fixed64s);
- extendableMessage.setExtension(RepeatedExtensions.repeatedSfixed64, sfixed64s);
- extendableMessage.setExtension(RepeatedExtensions.repeatedBool, bools);
- extendableMessage.setExtension(RepeatedExtensions.repeatedFloat, floats);
- extendableMessage.setExtension(RepeatedExtensions.repeatedDouble, doubles);
- extendableMessage.setExtension(RepeatedExtensions.repeatedEnum, enums);
- extendableMessage.setExtension(RepeatedExtensions.repeatedString, strings);
- extendableMessage.setExtension(RepeatedExtensions.repeatedBytes, bytess);
- extendableMessage.setExtension(RepeatedExtensions.repeatedMessage, messages);
- extendableMessage.setExtension(RepeatedExtensions.repeatedGroup, groups);
-
- byte[] data = MessageNano.toByteArray(extendableMessage);
-
- extendableMessage = Extensions.ExtendableMessage.parseFrom(data);
- Extensions.ExtendableMessage messageCopy = Extensions.ExtendableMessage.parseFrom(data);
-
- // Without deserialising.
- assertEquals(extendableMessage, messageCopy);
- assertEquals(extendableMessage.hashCode(), messageCopy.hashCode());
-
- // Only one deserialized.
- extendableMessage.getExtension(SingularExtensions.someInt32);
- extendableMessage.getExtension(RepeatedExtensions.repeatedUint32);
- extendableMessage.getExtension(RepeatedExtensions.repeatedSint32);
- extendableMessage.getExtension(RepeatedExtensions.repeatedInt64);
- extendableMessage.getExtension(RepeatedExtensions.repeatedUint64);
- extendableMessage.getExtension(RepeatedExtensions.repeatedSint64);
- extendableMessage.getExtension(RepeatedExtensions.repeatedFixed32);
- extendableMessage.getExtension(RepeatedExtensions.repeatedSfixed32);
- extendableMessage.getExtension(RepeatedExtensions.repeatedFixed64);
- extendableMessage.getExtension(RepeatedExtensions.repeatedSfixed64);
- extendableMessage.getExtension(RepeatedExtensions.repeatedBool);
- extendableMessage.getExtension(RepeatedExtensions.repeatedFloat);
- extendableMessage.getExtension(RepeatedExtensions.repeatedDouble);
- extendableMessage.getExtension(RepeatedExtensions.repeatedEnum);
- extendableMessage.getExtension(RepeatedExtensions.repeatedString);
- extendableMessage.getExtension(RepeatedExtensions.repeatedBytes);
- extendableMessage.getExtension(RepeatedExtensions.repeatedMessage);
- extendableMessage.getExtension(RepeatedExtensions.repeatedGroup);
- assertEquals(extendableMessage, messageCopy);
- assertEquals(extendableMessage.hashCode(), messageCopy.hashCode());
-
- // Both deserialized.
- messageCopy.getExtension(SingularExtensions.someInt32);
- messageCopy.getExtension(RepeatedExtensions.repeatedUint32);
- messageCopy.getExtension(RepeatedExtensions.repeatedSint32);
- messageCopy.getExtension(RepeatedExtensions.repeatedInt64);
- messageCopy.getExtension(RepeatedExtensions.repeatedUint64);
- messageCopy.getExtension(RepeatedExtensions.repeatedSint64);
- messageCopy.getExtension(RepeatedExtensions.repeatedFixed32);
- messageCopy.getExtension(RepeatedExtensions.repeatedSfixed32);
- messageCopy.getExtension(RepeatedExtensions.repeatedFixed64);
- messageCopy.getExtension(RepeatedExtensions.repeatedSfixed64);
- messageCopy.getExtension(RepeatedExtensions.repeatedBool);
- messageCopy.getExtension(RepeatedExtensions.repeatedFloat);
- messageCopy.getExtension(RepeatedExtensions.repeatedDouble);
- messageCopy.getExtension(RepeatedExtensions.repeatedEnum);
- messageCopy.getExtension(RepeatedExtensions.repeatedString);
- messageCopy.getExtension(RepeatedExtensions.repeatedBytes);
- messageCopy.getExtension(RepeatedExtensions.repeatedMessage);
- messageCopy.getExtension(RepeatedExtensions.repeatedGroup);
- assertEquals(extendableMessage, messageCopy);
- assertEquals(extendableMessage.hashCode(), messageCopy.hashCode());
-
- // Change one, make sure they are still different.
- messageCopy.getExtension(RepeatedExtensions.repeatedMessage)[0].string = "not empty";
- assertFalse(extendableMessage.equals(messageCopy));
-
- // Even if the extension hasn't been deserialized.
- extendableMessage = Extensions.ExtendableMessage.parseFrom(data);
- assertFalse(extendableMessage.equals(messageCopy));
- }
-
- public void testExtensionsCaching() {
- Extensions.ExtendableMessage extendableMessage = new Extensions.ExtendableMessage();
- extendableMessage.setExtension(SingularExtensions.someMessage,
- new Extensions.AnotherMessage());
- assertSame("Consecutive calls to getExtensions should return the same object",
- extendableMessage.getExtension(SingularExtensions.someMessage),
- extendableMessage.getExtension(SingularExtensions.someMessage));
- }
-
- public void testUnknownFields() throws Exception {
- // Check that we roundtrip (serialize and deserialize) unrecognized fields.
- AnotherMessage message = new AnotherMessage();
- message.string = "Hello World";
- message.value = false;
-
- byte[] bytes = MessageNano.toByteArray(message);
- int extraFieldSize = CodedOutputByteBufferNano.computeStringSize(
- 1001, "This is an unknown field");
- byte[] newBytes = new byte[bytes.length + extraFieldSize];
- System.arraycopy(bytes, 0, newBytes, 0, bytes.length);
- CodedOutputByteBufferNano.newInstance(newBytes, bytes.length, extraFieldSize)
- .writeString(1001, "This is an unknown field");
-
- // Deserialize with an unknown field.
- AnotherMessage deserialized = AnotherMessage.parseFrom(newBytes);
- byte[] serialized = MessageNano.toByteArray(deserialized);
-
- assertEquals(newBytes.length, serialized.length);
-
- // Clear, and make sure it clears everything.
- deserialized.clear();
- assertEquals(0, MessageNano.toByteArray(deserialized).length);
- }
-
- public void testMergeFrom() throws Exception {
- SimpleMessageNano message = new SimpleMessageNano();
- message.d = 123;
- byte[] bytes = MessageNano.toByteArray(message);
-
- SimpleMessageNano newMessage = MessageNano.mergeFrom(new SimpleMessageNano(), bytes);
- assertEquals(message.d, newMessage.d);
- }
-
- public void testJavaKeyword() throws Exception {
- TestAllTypesNano msg = new TestAllTypesNano();
- msg.synchronized_ = 123;
- assertEquals(123, msg.synchronized_);
- }
-
- public void testReferenceTypesForPrimitives() throws Exception {
- NanoReferenceTypes.TestAllTypesNano message = new NanoReferenceTypes.TestAllTypesNano();
-
- // Base check - when nothing is set, we serialize nothing.
- assertHasWireData(message, false);
-
- message.defaultBool = true;
- assertHasWireData(message, true);
-
- message.defaultBool = false;
- assertHasWireData(message, true);
-
- message.defaultBool = null;
- assertHasWireData(message, false);
-
- message.defaultInt32 = 5;
- assertHasWireData(message, true);
-
- message.defaultInt32 = null;
- assertHasWireData(message, false);
-
- message.defaultInt64 = 123456L;
- assertHasWireData(message, true);
-
- message.defaultInt64 = null;
- assertHasWireData(message, false);
-
- message.defaultFloat = 1f;
- assertHasWireData(message, true);
-
- message.defaultFloat = null;
- assertHasWireData(message, false);
-
- message.defaultDouble = 2.1;
- assertHasWireData(message, true);
-
- message.defaultDouble = null;
- assertHasWireData(message, false);
-
- message.defaultString = "hello";
- assertHasWireData(message, true);
-
- message.defaultString = null;
- assertHasWireData(message, false);
-
- message.defaultBytes = new byte[] { 1, 2, 3 };
- assertHasWireData(message, true);
-
- message.defaultBytes = null;
- assertHasWireData(message, false);
- }
-
- public void testHashCodeEquals() throws Exception {
- // Complete equality:
- TestAllTypesNano a = createMessageForHashCodeEqualsTest();
- TestAllTypesNano aEquivalent = createMessageForHashCodeEqualsTest();
-
- assertTrue(MessageNano.messageNanoEquals(a, aEquivalent));
- assertFalse(MessageNano.messageNanoEquals(a, new TestAllTypesNano()));
-
- // Null and empty array for repeated fields equality:
- TestAllTypesNano b = createMessageForHashCodeEqualsTest();
- b.repeatedBool = null;
- b.repeatedFloat = new float[0];
- TestAllTypesNano bEquivalent = createMessageForHashCodeEqualsTest();
- bEquivalent.repeatedBool = new boolean[0];
- bEquivalent.repeatedFloat = null;
-
- // Ref-element-type repeated fields use non-null subsequence equality:
- TestAllTypesNano c = createMessageForHashCodeEqualsTest();
- c.repeatedString = null;
- c.repeatedStringPiece = new String[] {null, "one", null, "two"};
- c.repeatedBytes = new byte[][] {{3, 4}, null};
- TestAllTypesNano cEquivalent = createMessageForHashCodeEqualsTest();
- cEquivalent.repeatedString = new String[3];
- cEquivalent.repeatedStringPiece = new String[] {"one", "two", null};
- cEquivalent.repeatedBytes = new byte[][] {{3, 4}};
-
- // Complete equality for messages with has fields:
- TestAllTypesNanoHas d = createMessageWithHasForHashCodeEqualsTest();
- TestAllTypesNanoHas dEquivalent = createMessageWithHasForHashCodeEqualsTest();
-
- // If has-fields exist, fields with the same default values but
- // different has-field values are different.
- TestAllTypesNanoHas e = createMessageWithHasForHashCodeEqualsTest();
- e.optionalInt32++; // make different from d
- e.hasDefaultString = false;
- TestAllTypesNanoHas eDifferent = createMessageWithHasForHashCodeEqualsTest();
- eDifferent.optionalInt32 = e.optionalInt32;
- eDifferent.hasDefaultString = true;
-
- // Complete equality for messages with accessors:
- TestNanoAccessors f = createMessageWithAccessorsForHashCodeEqualsTest();
- TestNanoAccessors fEquivalent = createMessageWithAccessorsForHashCodeEqualsTest();
-
- // If using accessors, explicitly setting a field to its default value
- // should make the message different.
- TestNanoAccessors g = createMessageWithAccessorsForHashCodeEqualsTest();
- g.setOptionalInt32(g.getOptionalInt32() + 1); // make different from f
- g.clearDefaultString();
- TestNanoAccessors gDifferent = createMessageWithAccessorsForHashCodeEqualsTest();
- gDifferent.setOptionalInt32(g.getOptionalInt32());
- gDifferent.setDefaultString(g.getDefaultString());
-
- // Complete equality for reference typed messages:
- NanoReferenceTypes.TestAllTypesNano h = createRefTypedMessageForHashCodeEqualsTest();
- NanoReferenceTypes.TestAllTypesNano hEquivalent = createRefTypedMessageForHashCodeEqualsTest();
-
- // Inequality of null and default value for reference typed messages:
- NanoReferenceTypes.TestAllTypesNano i = createRefTypedMessageForHashCodeEqualsTest();
- i.optionalInt32 = 1; // make different from h
- i.optionalFloat = null;
- NanoReferenceTypes.TestAllTypesNano iDifferent = createRefTypedMessageForHashCodeEqualsTest();
- iDifferent.optionalInt32 = i.optionalInt32;
- iDifferent.optionalFloat = 0.0f;
-
- HashMap<MessageNano, String> hashMap = new HashMap<MessageNano, String>();
- hashMap.put(a, "a");
- hashMap.put(b, "b");
- hashMap.put(c, "c");
- hashMap.put(d, "d");
- hashMap.put(e, "e");
- hashMap.put(f, "f");
- hashMap.put(g, "g");
- hashMap.put(h, "h");
- hashMap.put(i, "i");
-
- assertEquals(9, hashMap.size()); // a-i should be different from each other.
-
- assertEquals("a", hashMap.get(a));
- assertEquals("a", hashMap.get(aEquivalent));
-
- assertEquals("b", hashMap.get(b));
- assertEquals("b", hashMap.get(bEquivalent));
-
- assertEquals("c", hashMap.get(c));
- assertEquals("c", hashMap.get(cEquivalent));
-
- assertEquals("d", hashMap.get(d));
- assertEquals("d", hashMap.get(dEquivalent));
-
- assertEquals("e", hashMap.get(e));
- assertNull(hashMap.get(eDifferent));
-
- assertEquals("f", hashMap.get(f));
- assertEquals("f", hashMap.get(fEquivalent));
-
- assertEquals("g", hashMap.get(g));
- assertNull(hashMap.get(gDifferent));
-
- assertEquals("h", hashMap.get(h));
- assertEquals("h", hashMap.get(hEquivalent));
-
- assertEquals("i", hashMap.get(i));
- assertNull(hashMap.get(iDifferent));
- }
-
- private TestAllTypesNano createMessageForHashCodeEqualsTest() {
- TestAllTypesNano message = new TestAllTypesNano();
- message.optionalInt32 = 5;
- message.optionalInt64 = 777;
- message.optionalFloat = 1.0f;
- message.optionalDouble = 2.0;
- message.optionalBool = true;
- message.optionalString = "Hello";
- message.optionalBytes = new byte[] { 1, 2, 3 };
- message.optionalNestedMessage = new TestAllTypesNano.NestedMessage();
- message.optionalNestedMessage.bb = 27;
- message.optionalNestedEnum = TestAllTypesNano.BAR;
- message.repeatedInt32 = new int[] { 5, 6, 7, 8 };
- message.repeatedInt64 = new long[] { 27L, 28L, 29L };
- message.repeatedFloat = new float[] { 5.0f, 6.0f };
- message.repeatedDouble = new double[] { 99.1, 22.5 };
- message.repeatedBool = new boolean[] { true, false, true };
- message.repeatedString = new String[] { "One", "Two" };
- message.repeatedBytes = new byte[][] { { 2, 7 }, { 2, 7 } };
- message.repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] {
- message.optionalNestedMessage,
- message.optionalNestedMessage
- };
- message.repeatedNestedEnum = new int[] {
- TestAllTypesNano.BAR,
- TestAllTypesNano.BAZ
- };
- message.setOneofUint32(3);
- return message;
- }
-
- private TestAllTypesNanoHas createMessageWithHasForHashCodeEqualsTest() {
- TestAllTypesNanoHas message = new TestAllTypesNanoHas();
- message.optionalInt32 = 5;
- message.optionalString = "Hello";
- message.optionalBytes = new byte[] { 1, 2, 3 };
- message.optionalNestedMessage = new TestAllTypesNanoHas.NestedMessage();
- message.optionalNestedMessage.bb = 27;
- message.optionalNestedEnum = TestAllTypesNano.BAR;
- message.repeatedInt32 = new int[] { 5, 6, 7, 8 };
- message.repeatedString = new String[] { "One", "Two" };
- message.repeatedBytes = new byte[][] { { 2, 7 }, { 2, 7 } };
- message.repeatedNestedMessage = new TestAllTypesNanoHas.NestedMessage[] {
- message.optionalNestedMessage,
- message.optionalNestedMessage
- };
- message.repeatedNestedEnum = new int[] {
- TestAllTypesNano.BAR,
- TestAllTypesNano.BAZ
- };
- return message;
- }
-
- private TestNanoAccessors createMessageWithAccessorsForHashCodeEqualsTest() {
- TestNanoAccessors message = new TestNanoAccessors()
- .setOptionalInt32(5)
- .setOptionalString("Hello")
- .setOptionalBytes(new byte[] {1, 2, 3})
- .setOptionalNestedEnum(TestNanoAccessors.BAR);
- message.optionalNestedMessage = new TestNanoAccessors.NestedMessage().setBb(27);
- message.repeatedInt32 = new int[] { 5, 6, 7, 8 };
- message.repeatedString = new String[] { "One", "Two" };
- message.repeatedBytes = new byte[][] { { 2, 7 }, { 2, 7 } };
- message.repeatedNestedMessage = new TestNanoAccessors.NestedMessage[] {
- message.optionalNestedMessage,
- message.optionalNestedMessage
- };
- message.repeatedNestedEnum = new int[] {
- TestAllTypesNano.BAR,
- TestAllTypesNano.BAZ
- };
- return message;
- }
-
- private NanoReferenceTypes.TestAllTypesNano createRefTypedMessageForHashCodeEqualsTest() {
- NanoReferenceTypes.TestAllTypesNano message = new NanoReferenceTypes.TestAllTypesNano();
- message.optionalInt32 = 5;
- message.optionalInt64 = 777L;
- message.optionalFloat = 1.0f;
- message.optionalDouble = 2.0;
- message.optionalBool = true;
- message.optionalString = "Hello";
- message.optionalBytes = new byte[] { 1, 2, 3 };
- message.optionalNestedMessage =
- new NanoReferenceTypes.TestAllTypesNano.NestedMessage();
- message.optionalNestedMessage.foo = 27;
- message.optionalNestedEnum = NanoReferenceTypes.TestAllTypesNano.BAR;
- message.repeatedInt32 = new int[] { 5, 6, 7, 8 };
- message.repeatedInt64 = new long[] { 27L, 28L, 29L };
- message.repeatedFloat = new float[] { 5.0f, 6.0f };
- message.repeatedDouble = new double[] { 99.1, 22.5 };
- message.repeatedBool = new boolean[] { true, false, true };
- message.repeatedString = new String[] { "One", "Two" };
- message.repeatedBytes = new byte[][] { { 2, 7 }, { 2, 7 } };
- message.repeatedNestedMessage =
- new NanoReferenceTypes.TestAllTypesNano.NestedMessage[] {
- message.optionalNestedMessage,
- message.optionalNestedMessage
- };
- message.repeatedNestedEnum = new int[] {
- NanoReferenceTypes.TestAllTypesNano.BAR,
- NanoReferenceTypes.TestAllTypesNano.BAZ
- };
- return message;
- }
-
- public void testEqualsWithSpecialFloatingPointValues() throws Exception {
- // Checks that the nano implementation complies with Object.equals() when treating
- // floating point numbers, i.e. NaN == NaN and +0.0 != -0.0.
- // This test assumes that the generated equals() implementations are symmetric, so
- // there will only be one direction for each equality check.
-
- TestAllTypesNano m1 = new TestAllTypesNano();
- m1.optionalFloat = Float.NaN;
- m1.optionalDouble = Double.NaN;
- TestAllTypesNano m2 = new TestAllTypesNano();
- m2.optionalFloat = Float.NaN;
- m2.optionalDouble = Double.NaN;
- assertTrue(m1.equals(m2));
- assertTrue(m1.equals(
- MessageNano.mergeFrom(new TestAllTypesNano(), MessageNano.toByteArray(m1))));
-
- m1.optionalFloat = +0f;
- m2.optionalFloat = -0f;
- assertFalse(m1.equals(m2));
-
- m1.optionalFloat = -0f;
- m1.optionalDouble = +0d;
- m2.optionalDouble = -0d;
- assertFalse(m1.equals(m2));
-
- m1.optionalDouble = -0d;
- assertTrue(m1.equals(m2));
- assertFalse(m1.equals(new TestAllTypesNano())); // -0 does not equals() the default +0
- assertTrue(m1.equals(
- MessageNano.mergeFrom(new TestAllTypesNano(), MessageNano.toByteArray(m1))));
-
- // -------
-
- TestAllTypesNanoHas m3 = new TestAllTypesNanoHas();
- m3.optionalFloat = Float.NaN;
- m3.hasOptionalFloat = true;
- m3.optionalDouble = Double.NaN;
- m3.hasOptionalDouble = true;
- TestAllTypesNanoHas m4 = new TestAllTypesNanoHas();
- m4.optionalFloat = Float.NaN;
- m4.hasOptionalFloat = true;
- m4.optionalDouble = Double.NaN;
- m4.hasOptionalDouble = true;
- assertTrue(m3.equals(m4));
- assertTrue(m3.equals(
- MessageNano.mergeFrom(new TestAllTypesNanoHas(), MessageNano.toByteArray(m3))));
-
- m3.optionalFloat = +0f;
- m4.optionalFloat = -0f;
- assertFalse(m3.equals(m4));
-
- m3.optionalFloat = -0f;
- m3.optionalDouble = +0d;
- m4.optionalDouble = -0d;
- assertFalse(m3.equals(m4));
-
- m3.optionalDouble = -0d;
- m3.hasOptionalFloat = false; // -0 does not equals() the default +0,
- m3.hasOptionalDouble = false; // so these incorrect 'has' flags should be disregarded.
- assertTrue(m3.equals(m4)); // note: m4 has the 'has' flags set.
- assertFalse(m3.equals(new TestAllTypesNanoHas())); // note: the new message has +0 defaults
- assertTrue(m3.equals(
- MessageNano.mergeFrom(new TestAllTypesNanoHas(), MessageNano.toByteArray(m3))));
- // note: the deserialized message has the 'has' flags set.
-
- // -------
-
- TestNanoAccessors m5 = new TestNanoAccessors();
- m5.setOptionalFloat(Float.NaN);
- m5.setOptionalDouble(Double.NaN);
- TestNanoAccessors m6 = new TestNanoAccessors();
- m6.setOptionalFloat(Float.NaN);
- m6.setOptionalDouble(Double.NaN);
- assertTrue(m5.equals(m6));
- assertTrue(m5.equals(
- MessageNano.mergeFrom(new TestNanoAccessors(), MessageNano.toByteArray(m6))));
-
- m5.setOptionalFloat(+0f);
- m6.setOptionalFloat(-0f);
- assertFalse(m5.equals(m6));
-
- m5.setOptionalFloat(-0f);
- m5.setOptionalDouble(+0d);
- m6.setOptionalDouble(-0d);
- assertFalse(m5.equals(m6));
-
- m5.setOptionalDouble(-0d);
- assertTrue(m5.equals(m6));
- assertFalse(m5.equals(new TestNanoAccessors()));
- assertTrue(m5.equals(
- MessageNano.mergeFrom(new TestNanoAccessors(), MessageNano.toByteArray(m6))));
-
- // -------
-
- NanoReferenceTypes.TestAllTypesNano m7 = new NanoReferenceTypes.TestAllTypesNano();
- m7.optionalFloat = Float.NaN;
- m7.optionalDouble = Double.NaN;
- NanoReferenceTypes.TestAllTypesNano m8 = new NanoReferenceTypes.TestAllTypesNano();
- m8.optionalFloat = Float.NaN;
- m8.optionalDouble = Double.NaN;
- assertTrue(m7.equals(m8));
- assertTrue(m7.equals(MessageNano.mergeFrom(
- new NanoReferenceTypes.TestAllTypesNano(), MessageNano.toByteArray(m7))));
-
- m7.optionalFloat = +0f;
- m8.optionalFloat = -0f;
- assertFalse(m7.equals(m8));
-
- m7.optionalFloat = -0f;
- m7.optionalDouble = +0d;
- m8.optionalDouble = -0d;
- assertFalse(m7.equals(m8));
-
- m7.optionalDouble = -0d;
- assertTrue(m7.equals(m8));
- assertFalse(m7.equals(new NanoReferenceTypes.TestAllTypesNano()));
- assertTrue(m7.equals(MessageNano.mergeFrom(
- new NanoReferenceTypes.TestAllTypesNano(), MessageNano.toByteArray(m7))));
- }
-
- private static TestAllTypesNano generateMessageForOneof(int caseNumber) {
- TestAllTypesNano result = new TestAllTypesNano();
- TestAllTypesNano.NestedMessage nested =
- new TestAllTypesNano.NestedMessage();
- nested.bb = 2;
- switch (caseNumber) {
- case TestAllTypesNano.ONEOF_UINT32_FIELD_NUMBER:
- result.setOneofUint32(1);
- break;
- case TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER:
- result.setOneofEnum(TestAllTypesNano.BAR);
- break;
- case TestAllTypesNano.ONEOF_NESTED_MESSAGE_FIELD_NUMBER:
- result.setOneofNestedMessage(nested);
- break;
- case TestAllTypesNano.ONEOF_BYTES_FIELD_NUMBER:
- result.setOneofBytes(new byte[] {1, 2});
- break;
- case TestAllTypesNano.ONEOF_STRING_FIELD_NUMBER:
- result.setOneofString("hello");
- break;
- case TestAllTypesNano.ONEOF_FIXED64_FIELD_NUMBER:
- result.setOneofFixed64(-1L);
- break;
- default:
- throw new RuntimeException("unexpected case number: " + caseNumber);
- }
- return result;
- }
-
- public void testOneofHashCodeEquals() throws Exception {
- TestAllTypesNano m1 = generateMessageForOneof(
- TestAllTypesNano.ONEOF_UINT32_FIELD_NUMBER);
- assertEquals(m1, generateMessageForOneof(
- TestAllTypesNano.ONEOF_UINT32_FIELD_NUMBER));
- assertFalse(m1.equals(new TestAllTypesNano()));
-
- TestAllTypesNano m2 = generateMessageForOneof(
- TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER);
- assertEquals(m2, generateMessageForOneof(
- TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER));
- assertFalse(m2.equals(new TestAllTypesNano()));
-
- TestAllTypesNano m3 = generateMessageForOneof(
- TestAllTypesNano.ONEOF_NESTED_MESSAGE_FIELD_NUMBER);
- assertEquals(m3, generateMessageForOneof(
- TestAllTypesNano.ONEOF_NESTED_MESSAGE_FIELD_NUMBER));
- assertFalse(m3.equals(new TestAllTypesNano()));
-
- TestAllTypesNano m4 = generateMessageForOneof(
- TestAllTypesNano.ONEOF_BYTES_FIELD_NUMBER);
- assertEquals(m4, generateMessageForOneof(
- TestAllTypesNano.ONEOF_BYTES_FIELD_NUMBER));
- assertFalse(m4.equals(new TestAllTypesNano()));
-
- TestAllTypesNano m5 = generateMessageForOneof(
- TestAllTypesNano.ONEOF_STRING_FIELD_NUMBER);
- assertEquals(m5, generateMessageForOneof(
- TestAllTypesNano.ONEOF_STRING_FIELD_NUMBER));
- assertFalse(m5.equals(new TestAllTypesNano()));
-
- TestAllTypesNano m6 = generateMessageForOneof(
- TestAllTypesNano.ONEOF_FIXED64_FIELD_NUMBER);
- assertEquals(m6, generateMessageForOneof(
- TestAllTypesNano.ONEOF_FIXED64_FIELD_NUMBER));
- assertFalse(m6.equals(new TestAllTypesNano()));
-
- Map<TestAllTypesNano, Integer> map =
- new HashMap<TestAllTypesNano, Integer>();
- map.put(m1, 1);
- map.put(m2, 2);
- map.put(m3, 3);
- map.put(m4, 4);
- map.put(m5, 5);
- map.put(m6, 6);
-
- assertEquals(6, map.size());
- }
-
- private void checkOneofCase(TestAllTypesNano nano, int field)
- throws Exception {
- assertEquals(field, nano.getOneofFieldCase());
- assertEquals(
- field == TestAllTypesNano.ONEOF_BYTES_FIELD_NUMBER,
- nano.hasOneofBytes());
- assertEquals(
- field == TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER,
- nano.hasOneofEnum());
- assertEquals(
- field == TestAllTypesNano.ONEOF_FIXED64_FIELD_NUMBER,
- nano.hasOneofFixed64());
- assertEquals(
- field == TestAllTypesNano.ONEOF_NESTED_MESSAGE_FIELD_NUMBER,
- nano.hasOneofNestedMessage());
- assertEquals(
- field == TestAllTypesNano.ONEOF_STRING_FIELD_NUMBER,
- nano.hasOneofString());
- assertEquals(
- field == TestAllTypesNano.ONEOF_UINT32_FIELD_NUMBER,
- nano.hasOneofUint32());
-
- }
-
- public void testOneofDefault() throws Exception {
- TestAllTypesNano m1 = new TestAllTypesNano();
- checkOneofCase(m1, 0);
- assertEquals(WireFormatNano.EMPTY_BYTES, m1.getOneofBytes());
- assertEquals(TestAllTypesNano.FOO, m1.getOneofEnum());
- assertEquals(0L, m1.getOneofFixed64());
- assertEquals(null, m1.getOneofNestedMessage());
- assertEquals("", m1.getOneofString());
- assertEquals(0, m1.getOneofUint32());
- }
-
- public void testOneofExclusiveness() throws Exception {
- TestAllTypesNano m = new TestAllTypesNano();
- checkOneofCase(m, 0);
-
- m.setOneofBytes(new byte[]{0, 1});
- checkOneofCase(m, TestAllTypesNano.ONEOF_BYTES_FIELD_NUMBER);
- assertTrue(Arrays.equals(new byte[]{0, 1}, m.getOneofBytes()));
-
- m.setOneofEnum(TestAllTypesNano.BAZ);
- checkOneofCase(m, TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER);
- assertEquals(TestAllTypesNano.BAZ, m.getOneofEnum());
- assertEquals(WireFormatNano.EMPTY_BYTES, m.getOneofBytes());
-
- m.setOneofFixed64(-1L);
- checkOneofCase(m, TestAllTypesNano.ONEOF_FIXED64_FIELD_NUMBER);
- assertEquals(-1L, m.getOneofFixed64());
- assertEquals(TestAllTypesNano.FOO, m.getOneofEnum());
-
- m.setOneofNestedMessage(new TestAllTypesNano.NestedMessage());
- checkOneofCase(m, TestAllTypesNano.ONEOF_NESTED_MESSAGE_FIELD_NUMBER);
- assertEquals(
- new TestAllTypesNano.NestedMessage(), m.getOneofNestedMessage());
- assertEquals(0L, m.getOneofFixed64());
-
- m.setOneofString("hello");
- checkOneofCase(m, TestAllTypesNano.ONEOF_STRING_FIELD_NUMBER);
- assertEquals("hello", m.getOneofString());
- assertNull(m.getOneofNestedMessage());
-
- m.setOneofUint32(10);
- checkOneofCase(m, TestAllTypesNano.ONEOF_UINT32_FIELD_NUMBER);
- assertEquals(10, m.getOneofUint32());
- assertEquals("", m.getOneofString());
-
- m.setOneofBytes(new byte[]{0, 1});
- checkOneofCase(m, TestAllTypesNano.ONEOF_BYTES_FIELD_NUMBER);
- assertTrue(Arrays.equals(new byte[]{0, 1}, m.getOneofBytes()));
- assertEquals(0, m.getOneofUint32());
- }
-
- public void testOneofClear() throws Exception {
- TestAllTypesNano m = new TestAllTypesNano();
- m.setOneofBytes(new byte[]{0, 1});
- m.clearOneofField();
- checkOneofCase(m, 0);
-
- m.setOneofEnum(TestAllTypesNano.BAZ);
- m.clearOneofField();
- checkOneofCase(m, 0);
-
- m.setOneofFixed64(-1L);
- m.clearOneofField();
- checkOneofCase(m, 0);
-
- m.setOneofNestedMessage(new TestAllTypesNano.NestedMessage());
- m.clearOneofField();
- checkOneofCase(m, 0);
-
- m.setOneofString("hello");
- m.clearOneofField();
- checkOneofCase(m, 0);
-
- m.setOneofUint32(10);
- m.clearOneofField();
- checkOneofCase(m, 0);
- }
-
- public void testOneofMarshaling() throws Exception {
- TestAllTypesNano m = new TestAllTypesNano();
- TestAllTypesNano parsed = new TestAllTypesNano();
- {
- m.setOneofBytes(new byte[]{0, 1});
- byte[] serialized = MessageNano.toByteArray(m);
- MessageNano.mergeFrom(parsed, serialized);
- checkOneofCase(parsed, TestAllTypesNano.ONEOF_BYTES_FIELD_NUMBER);
- assertTrue(Arrays.equals(new byte[]{0, 1}, parsed.getOneofBytes()));
- }
- {
- m.setOneofEnum(TestAllTypesNano.BAZ);
- byte[] serialized = MessageNano.toByteArray(m);
- MessageNano.mergeFrom(parsed, serialized);
- checkOneofCase(m, TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER);
- assertEquals(TestAllTypesNano.BAZ, m.getOneofEnum());
- }
- {
- m.setOneofEnum(TestAllTypesNano.BAZ);
- byte[] serialized = MessageNano.toByteArray(m);
- MessageNano.mergeFrom(parsed, serialized);
- checkOneofCase(m, TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER);
- assertEquals(TestAllTypesNano.BAZ, m.getOneofEnum());
- }
- {
- m.setOneofFixed64(-1L);
- byte[] serialized = MessageNano.toByteArray(m);
- MessageNano.mergeFrom(parsed, serialized);
- checkOneofCase(m, TestAllTypesNano.ONEOF_FIXED64_FIELD_NUMBER);
- assertEquals(-1L, m.getOneofFixed64());
- }
- {
- m.setOneofNestedMessage(new TestAllTypesNano.NestedMessage());
- byte[] serialized = MessageNano.toByteArray(m);
- MessageNano.mergeFrom(parsed, serialized);
- checkOneofCase(m, TestAllTypesNano.ONEOF_NESTED_MESSAGE_FIELD_NUMBER);
- assertEquals(
- new TestAllTypesNano.NestedMessage(), m.getOneofNestedMessage());
- }
- {
- m.setOneofString("hello");
- byte[] serialized = MessageNano.toByteArray(m);
- MessageNano.mergeFrom(parsed, serialized);
- assertEquals("hello", m.getOneofString());
- assertNull(m.getOneofNestedMessage());
- }
- {
- m.setOneofUint32(10);
- byte[] serialized = MessageNano.toByteArray(m);
- MessageNano.mergeFrom(parsed, serialized);
- checkOneofCase(m, TestAllTypesNano.ONEOF_UINT32_FIELD_NUMBER);
- assertEquals(10, m.getOneofUint32());
- }
- }
-
- public void testOneofSerializedConcat() throws Exception {
- TestAllTypesNano m1 = new TestAllTypesNano();
- m1.setOneofBytes(new byte[] {0, 1});
- byte[] b1 = MessageNano.toByteArray(m1);
- TestAllTypesNano m2 = new TestAllTypesNano();
- m2.setOneofEnum(TestAllTypesNano.BAZ);
- byte[] b2 = MessageNano.toByteArray(m2);
- byte[] b3 = new byte[b1.length + b2.length];
- System.arraycopy(b1, 0, b3, 0, b1.length);
- System.arraycopy(b2, 0, b3, b1.length, b2.length);
- TestAllTypesNano parsed = new TestAllTypesNano();
- MessageNano.mergeFrom(parsed, b3);
- // the last on the wire wins.
- checkOneofCase(parsed, TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER);
- assertEquals(TestAllTypesNano.BAZ, parsed.getOneofEnum());
- }
-
- public void testNullRepeatedFields() throws Exception {
- // Check that serialization after explicitly setting a repeated field
- // to null doesn't NPE.
- TestAllTypesNano message = new TestAllTypesNano();
- message.repeatedInt32 = null;
- MessageNano.toByteArray(message); // should not NPE
- message.toString(); // should not NPE
-
- message.repeatedNestedEnum = null;
- MessageNano.toByteArray(message); // should not NPE
- message.toString(); // should not NPE
-
- message.repeatedBytes = null;
- MessageNano.toByteArray(message); // should not NPE
- message.toString(); // should not NPE
-
- message.repeatedNestedMessage = null;
- MessageNano.toByteArray(message); // should not NPE
- message.toString(); // should not NPE
-
- message.repeatedPackedInt32 = null;
- MessageNano.toByteArray(message); // should not NPE
- message.toString(); // should not NPE
-
- message.repeatedPackedNestedEnum = null;
- MessageNano.toByteArray(message); // should not NPE
- message.toString(); // should not NPE
-
- // Create a second message to merge into message.
- TestAllTypesNano secondMessage = new TestAllTypesNano();
- secondMessage.repeatedInt32 = new int[] {1, 2, 3};
- secondMessage.repeatedNestedEnum = new int[] {
- TestAllTypesNano.FOO, TestAllTypesNano.BAR
- };
- secondMessage.repeatedBytes = new byte[][] {{1, 2}, {3, 4}};
- TestAllTypesNano.NestedMessage nested =
- new TestAllTypesNano.NestedMessage();
- nested.bb = 55;
- secondMessage.repeatedNestedMessage =
- new TestAllTypesNano.NestedMessage[] {nested};
- secondMessage.repeatedPackedInt32 = new int[] {1, 2, 3};
- secondMessage.repeatedPackedNestedEnum = new int[] {
- TestAllTypesNano.FOO, TestAllTypesNano.BAR
- };
-
- // Should not NPE
- message.mergeFrom(CodedInputByteBufferNano.newInstance(
- MessageNano.toByteArray(secondMessage)));
- assertEquals(3, message.repeatedInt32.length);
- assertEquals(3, message.repeatedInt32[2]);
- assertEquals(2, message.repeatedNestedEnum.length);
- assertEquals(TestAllTypesNano.FOO, message.repeatedNestedEnum[0]);
- assertEquals(2, message.repeatedBytes.length);
- assertEquals(4, message.repeatedBytes[1][1]);
- assertEquals(1, message.repeatedNestedMessage.length);
- assertEquals(55, message.repeatedNestedMessage[0].bb);
- assertEquals(3, message.repeatedPackedInt32.length);
- assertEquals(2, message.repeatedPackedInt32[1]);
- assertEquals(2, message.repeatedPackedNestedEnum.length);
- assertEquals(TestAllTypesNano.BAR, message.repeatedPackedNestedEnum[1]);
- }
-
- public void testNullRepeatedFieldElements() throws Exception {
- // Check that serialization with null array elements doesn't NPE.
- String string1 = "1";
- String string2 = "2";
- byte[] bytes1 = {3, 4};
- byte[] bytes2 = {5, 6};
- TestAllTypesNano.NestedMessage msg1 = new TestAllTypesNano.NestedMessage();
- msg1.bb = 7;
- TestAllTypesNano.NestedMessage msg2 = new TestAllTypesNano.NestedMessage();
- msg2.bb = 8;
-
- TestAllTypesNano message = new TestAllTypesNano();
- message.repeatedString = new String[] {null, string1, string2};
- message.repeatedBytes = new byte[][] {bytes1, null, bytes2};
- message.repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] {msg1, msg2, null};
- message.repeatedGroup = new TestAllTypesNano.RepeatedGroup[] {null, null, null};
-
- byte[] serialized = MessageNano.toByteArray(message); // should not NPE
- TestAllTypesNano deserialized = MessageNano.mergeFrom(new TestAllTypesNano(), serialized);
- assertEquals(2, deserialized.repeatedString.length);
- assertEquals(string1, deserialized.repeatedString[0]);
- assertEquals(string2, deserialized.repeatedString[1]);
- assertEquals(2, deserialized.repeatedBytes.length);
- assertTrue(Arrays.equals(bytes1, deserialized.repeatedBytes[0]));
- assertTrue(Arrays.equals(bytes2, deserialized.repeatedBytes[1]));
- assertEquals(2, deserialized.repeatedNestedMessage.length);
- assertEquals(msg1.bb, deserialized.repeatedNestedMessage[0].bb);
- assertEquals(msg2.bb, deserialized.repeatedNestedMessage[1].bb);
- assertEquals(0, deserialized.repeatedGroup.length);
- }
-
- public void testRepeatedMerge() throws Exception {
- // Check that merging repeated fields cause the arrays to expand with
- // new data.
- TestAllTypesNano first = new TestAllTypesNano();
- first.repeatedInt32 = new int[] {1, 2, 3};
- TestAllTypesNano second = new TestAllTypesNano();
- second.repeatedInt32 = new int[] {4, 5};
- MessageNano.mergeFrom(first, MessageNano.toByteArray(second));
- assertEquals(5, first.repeatedInt32.length);
- assertEquals(1, first.repeatedInt32[0]);
- assertEquals(4, first.repeatedInt32[3]);
-
- first = new TestAllTypesNano();
- first.repeatedNestedEnum = new int[] {TestAllTypesNano.BAR};
- second = new TestAllTypesNano();
- second.repeatedNestedEnum = new int[] {TestAllTypesNano.FOO};
- MessageNano.mergeFrom(first, MessageNano.toByteArray(second));
- assertEquals(2, first.repeatedNestedEnum.length);
- assertEquals(TestAllTypesNano.BAR, first.repeatedNestedEnum[0]);
- assertEquals(TestAllTypesNano.FOO, first.repeatedNestedEnum[1]);
-
- first = new TestAllTypesNano();
- first.repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] {
- new TestAllTypesNano.NestedMessage()
- };
- first.repeatedNestedMessage[0].bb = 3;
- second = new TestAllTypesNano();
- second.repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] {
- new TestAllTypesNano.NestedMessage()
- };
- second.repeatedNestedMessage[0].bb = 5;
- MessageNano.mergeFrom(first, MessageNano.toByteArray(second));
- assertEquals(2, first.repeatedNestedMessage.length);
- assertEquals(3, first.repeatedNestedMessage[0].bb);
- assertEquals(5, first.repeatedNestedMessage[1].bb);
-
- first = new TestAllTypesNano();
- first.repeatedPackedSfixed64 = new long[] {-1, -2, -3};
- second = new TestAllTypesNano();
- second.repeatedPackedSfixed64 = new long[] {-4, -5};
- MessageNano.mergeFrom(first, MessageNano.toByteArray(second));
- assertEquals(5, first.repeatedPackedSfixed64.length);
- assertEquals(-1, first.repeatedPackedSfixed64[0]);
- assertEquals(-4, first.repeatedPackedSfixed64[3]);
-
- first = new TestAllTypesNano();
- first.repeatedPackedNestedEnum = new int[] {TestAllTypesNano.BAR};
- second = new TestAllTypesNano();
- second.repeatedPackedNestedEnum = new int[] {TestAllTypesNano.FOO};
- MessageNano.mergeFrom(first, MessageNano.toByteArray(second));
- assertEquals(2, first.repeatedPackedNestedEnum.length);
- assertEquals(TestAllTypesNano.BAR, first.repeatedPackedNestedEnum[0]);
- assertEquals(TestAllTypesNano.FOO, first.repeatedPackedNestedEnum[1]);
-
- // Now test repeated merging in a nested scope
- TestRepeatedMergeNano firstContainer = new TestRepeatedMergeNano();
- firstContainer.contained = new TestAllTypesNano();
- firstContainer.contained.repeatedInt32 = new int[] {10, 20};
- TestRepeatedMergeNano secondContainer = new TestRepeatedMergeNano();
- secondContainer.contained = new TestAllTypesNano();
- secondContainer.contained.repeatedInt32 = new int[] {30};
- MessageNano.mergeFrom(firstContainer, MessageNano.toByteArray(secondContainer));
- assertEquals(3, firstContainer.contained.repeatedInt32.length);
- assertEquals(20, firstContainer.contained.repeatedInt32[1]);
- assertEquals(30, firstContainer.contained.repeatedInt32[2]);
- }
-
- public void testRepeatedPackables() throws Exception {
- // Check that repeated fields with packable types can accept both packed and unpacked
- // serialized forms.
- NanoRepeatedPackables.NonPacked nonPacked = new NanoRepeatedPackables.NonPacked();
- // Exaggerates the first values of varint-typed arrays. This is to test that the parsing code
- // of packed fields handles non-packed data correctly. If the code incorrectly thinks it is
- // reading from a packed tag, it will read the first value as the byte length of the field,
- // and the large number will cause the input to go out of bounds, thus capturing the error.
- nonPacked.int32S = new int[] {1000, 2, 3};
- nonPacked.int64S = new long[] {4000, 5, 6};
- nonPacked.uint32S = new int[] {7000, 8, 9};
- nonPacked.uint64S = new long[] {10000, 11, 12};
- nonPacked.sint32S = new int[] {13000, 14, 15};
- nonPacked.sint64S = new long[] {16000, 17, 18};
- nonPacked.fixed32S = new int[] {19, 20, 21};
- nonPacked.fixed64S = new long[] {22, 23, 24};
- nonPacked.sfixed32S = new int[] {25, 26, 27};
- nonPacked.sfixed64S = new long[] {28, 29, 30};
- nonPacked.floats = new float[] {31, 32, 33};
- nonPacked.doubles = new double[] {34, 35, 36};
- nonPacked.bools = new boolean[] {false, true};
- nonPacked.enums = new int[] {
- NanoRepeatedPackables.Enum.OPTION_ONE,
- NanoRepeatedPackables.Enum.OPTION_TWO,
- };
- nonPacked.noise = 13579;
-
- byte[] nonPackedSerialized = MessageNano.toByteArray(nonPacked);
-
- NanoRepeatedPackables.Packed packed =
- MessageNano.mergeFrom(new NanoRepeatedPackables.Packed(), nonPackedSerialized);
- assertRepeatedPackablesEqual(nonPacked, packed);
-
- byte[] packedSerialized = MessageNano.toByteArray(packed);
- // Just a cautious check that the two serialized forms are different,
- // to make sure the remaining of this test is useful:
- assertFalse(Arrays.equals(nonPackedSerialized, packedSerialized));
-
- nonPacked = MessageNano.mergeFrom(new NanoRepeatedPackables.NonPacked(), packedSerialized);
- assertRepeatedPackablesEqual(nonPacked, packed);
-
- // Test mixed serialized form.
- byte[] mixedSerialized = new byte[nonPackedSerialized.length + packedSerialized.length];
- System.arraycopy(nonPackedSerialized, 0, mixedSerialized, 0, nonPackedSerialized.length);
- System.arraycopy(packedSerialized, 0,
- mixedSerialized, nonPackedSerialized.length, packedSerialized.length);
-
- nonPacked = MessageNano.mergeFrom(new NanoRepeatedPackables.NonPacked(), mixedSerialized);
- packed = MessageNano.mergeFrom(new NanoRepeatedPackables.Packed(), mixedSerialized);
- assertRepeatedPackablesEqual(nonPacked, packed);
- assertTrue(Arrays.equals(new int[] {1000, 2, 3, 1000, 2, 3}, nonPacked.int32S));
- assertTrue(Arrays.equals(new int[] {13000, 14, 15, 13000, 14, 15}, nonPacked.sint32S));
- assertTrue(Arrays.equals(new int[] {25, 26, 27, 25, 26, 27}, nonPacked.sfixed32S));
- assertTrue(Arrays.equals(new boolean[] {false, true, false, true}, nonPacked.bools));
- }
-
- public void testMapsSerializeAndParse() throws Exception {
- TestMap origin = new TestMap();
- setMapMessage(origin);
- assertMapMessageSet(origin);
-
- byte[] output = MessageNano.toByteArray(origin);
- TestMap parsed = new TestMap();
- MessageNano.mergeFrom(parsed, output);
- }
-
- public void testMapSerializeRejectNull() throws Exception {
- TestMap primitiveMap = new TestMap();
- primitiveMap.int32ToInt32Field = new HashMap<Integer, Integer>();
- primitiveMap.int32ToInt32Field.put(null, 1);
- try {
- MessageNano.toByteArray(primitiveMap);
- fail("should reject null keys");
- } catch (IllegalStateException e) {
- // pass.
- }
-
- TestMap messageMap = new TestMap();
- messageMap.int32ToMessageField =
- new HashMap<Integer, MapTestProto.TestMap.MessageValue>();
- messageMap.int32ToMessageField.put(0, null);
- try {
- MessageNano.toByteArray(messageMap);
- fail("should reject null values");
- } catch (IllegalStateException e) {
- // pass.
- }
- }
-
- /**
- * Tests that merging bytes containing conflicting keys with override the
- * message value instead of merging the message value into the existing entry.
- */
- public void testMapMergeOverrideMessageValues() throws Exception {
- TestMap.MessageValue origValue = new TestMap.MessageValue();
- origValue.value = 1;
- origValue.value2 = 2;
- TestMap.MessageValue newValue = new TestMap.MessageValue();
- newValue.value = 3;
-
- TestMap origMessage = new TestMap();
- origMessage.int32ToMessageField =
- new HashMap<Integer, MapTestProto.TestMap.MessageValue>();
- origMessage.int32ToMessageField.put(1, origValue);
-
- TestMap newMessage = new TestMap();
- newMessage.int32ToMessageField =
- new HashMap<Integer, MapTestProto.TestMap.MessageValue>();
- newMessage.int32ToMessageField.put(1, newValue);
- MessageNano.mergeFrom(origMessage,
- MessageNano.toByteArray(newMessage));
- TestMap.MessageValue mergedValue = origMessage.int32ToMessageField.get(1);
- assertEquals(3, mergedValue.value);
- assertEquals(0, mergedValue.value2);
- }
-
- /**
- * Tests that when merging with empty entries,
- * we will use default for the key and value, instead of null.
- */
- public void testMapMergeEmptyEntry() throws Exception {
- TestMap testMap = new TestMap();
- byte[] buffer = new byte[1024];
- CodedOutputByteBufferNano output =
- CodedOutputByteBufferNano.newInstance(buffer);
- // An empty entry for int32_to_int32 map.
- output.writeTag(1, WireFormatNano.WIRETYPE_LENGTH_DELIMITED);
- output.writeRawVarint32(0);
- // An empty entry for int32_to_message map.
- output.writeTag(5, WireFormatNano.WIRETYPE_LENGTH_DELIMITED);
- output.writeRawVarint32(0);
-
- CodedInputByteBufferNano input = CodedInputByteBufferNano.newInstance(
- buffer, 0, buffer.length - output.spaceLeft());
- testMap.mergeFrom(input);
- assertNotNull(testMap.int32ToInt32Field);;
- assertEquals(1, testMap.int32ToInt32Field.size());
- assertEquals(Integer.valueOf(0), testMap.int32ToInt32Field.get(0));
- assertNotNull(testMap.int32ToMessageField);
- assertEquals(1, testMap.int32ToMessageField.size());
- TestMap.MessageValue messageValue = testMap.int32ToMessageField.get(0);
- assertNotNull(messageValue);
- assertEquals(0, messageValue.value);
- assertEquals(0, messageValue.value2);
- }
-
- public void testMapEquals() throws Exception {
- TestMap a = new TestMap();
- TestMap b = new TestMap();
-
- // empty and null map fields are equal.
- assertTestMapEqual(a, b);
- a.int32ToBytesField = new HashMap<Integer, byte[]>();
- assertTestMapEqual(a, b);
-
- a.int32ToInt32Field = new HashMap<Integer, Integer>();
- b.int32ToInt32Field = new HashMap<Integer, Integer>();
- setMap(a.int32ToInt32Field, deepCopy(int32Values), deepCopy(int32Values));
- setMap(b.int32ToInt32Field, deepCopy(int32Values), deepCopy(int32Values));
- assertTestMapEqual(a, b);
-
- a.int32ToMessageField =
- new HashMap<Integer, MapTestProto.TestMap.MessageValue>();
- b.int32ToMessageField =
- new HashMap<Integer, MapTestProto.TestMap.MessageValue>();
- setMap(a.int32ToMessageField,
- deepCopy(int32Values), deepCopy(messageValues));
- setMap(b.int32ToMessageField,
- deepCopy(int32Values), deepCopy(messageValues));
- assertTestMapEqual(a, b);
-
- a.stringToInt32Field = new HashMap<String, Integer>();
- b.stringToInt32Field = new HashMap<String, Integer>();
- setMap(a.stringToInt32Field, deepCopy(stringValues), deepCopy(int32Values));
- setMap(b.stringToInt32Field, deepCopy(stringValues), deepCopy(int32Values));
- assertTestMapEqual(a, b);
-
- a.int32ToBytesField = new HashMap<Integer, byte[]>();
- b.int32ToBytesField = new HashMap<Integer, byte[]>();
- setMap(a.int32ToBytesField, deepCopy(int32Values), deepCopy(bytesValues));
- setMap(b.int32ToBytesField, deepCopy(int32Values), deepCopy(bytesValues));
- assertTestMapEqual(a, b);
-
- // Make sure the map implementation does not matter.
- a.int32ToStringField = new TreeMap<Integer, String>();
- b.int32ToStringField = new HashMap<Integer, String>();
- setMap(a.int32ToStringField, deepCopy(int32Values), deepCopy(stringValues));
- setMap(b.int32ToStringField, deepCopy(int32Values), deepCopy(stringValues));
- assertTestMapEqual(a, b);
-
- a.clear();
- b.clear();
-
- // unequal cases: different value
- a.int32ToInt32Field = new HashMap<Integer, Integer>();
- b.int32ToInt32Field = new HashMap<Integer, Integer>();
- a.int32ToInt32Field.put(1, 1);
- b.int32ToInt32Field.put(1, 2);
- assertTestMapUnequal(a, b);
- // unequal case: additional entry
- b.int32ToInt32Field.put(1, 1);
- b.int32ToInt32Field.put(2, 1);
- assertTestMapUnequal(a, b);
- a.int32ToInt32Field.put(2, 1);
- assertTestMapEqual(a, b);
-
- // unequal case: different message value.
- a.int32ToMessageField =
- new HashMap<Integer, MapTestProto.TestMap.MessageValue>();
- b.int32ToMessageField =
- new HashMap<Integer, MapTestProto.TestMap.MessageValue>();
- MessageValue va = new MessageValue();
- va.value = 1;
- MessageValue vb = new MessageValue();
- vb.value = 1;
- a.int32ToMessageField.put(1, va);
- b.int32ToMessageField.put(1, vb);
- assertTestMapEqual(a, b);
- vb.value = 2;
- assertTestMapUnequal(a, b);
- }
-
- private static void assertTestMapEqual(TestMap a, TestMap b)
- throws Exception {
- assertEquals(a.hashCode(), b.hashCode());
- assertTrue(a.equals(b));
- assertTrue(b.equals(a));
- }
-
- private static void assertTestMapUnequal(TestMap a, TestMap b)
- throws Exception {
- assertFalse(a.equals(b));
- assertFalse(b.equals(a));
- }
-
- private static final Integer[] int32Values = new Integer[] {
- 0, 1, -1, Integer.MAX_VALUE, Integer.MIN_VALUE,
- };
-
- private static final Long[] int64Values = new Long[] {
- 0L, 1L, -1L, Long.MAX_VALUE, Long.MIN_VALUE,
- };
-
- private static final String[] stringValues = new String[] {
- "", "hello", "world", "foo", "bar",
- };
-
- private static final byte[][] bytesValues = new byte[][] {
- new byte[] {},
- new byte[] {0},
- new byte[] {1, -1},
- new byte[] {127, -128},
- new byte[] {'a', 'b', '0', '1'},
- };
-
- private static final Boolean[] boolValues = new Boolean[] {
- false, true,
- };
-
- private static final Integer[] enumValues = new Integer[] {
- TestMap.FOO, TestMap.BAR, TestMap.BAZ, TestMap.QUX,
- Integer.MAX_VALUE /* unknown */,
- };
-
- private static final TestMap.MessageValue[] messageValues =
- new TestMap.MessageValue[] {
- newMapValueMessage(0),
- newMapValueMessage(1),
- newMapValueMessage(-1),
- newMapValueMessage(Integer.MAX_VALUE),
- newMapValueMessage(Integer.MIN_VALUE),
- };
-
- private static TestMap.MessageValue newMapValueMessage(int value) {
- TestMap.MessageValue result = new TestMap.MessageValue();
- result.value = value;
- return result;
- }
-
- @SuppressWarnings("unchecked")
- private static <T> T[] deepCopy(T[] orig) throws Exception {
- if (orig instanceof MessageValue[]) {
- MessageValue[] result = new MessageValue[orig.length];
- for (int i = 0; i < orig.length; i++) {
- result[i] = new MessageValue();
- MessageNano.mergeFrom(
- result[i], MessageNano.toByteArray((MessageValue) orig[i]));
- }
- return (T[]) result;
- }
- if (orig instanceof byte[][]) {
- byte[][] result = new byte[orig.length][];
- for (int i = 0; i < orig.length; i++) {
- byte[] origBytes = (byte[]) orig[i];
- result[i] = Arrays.copyOf(origBytes, origBytes.length);
- }
- }
- return Arrays.copyOf(orig, orig.length);
- }
-
- private <K, V> void setMap(Map<K, V> map, K[] keys, V[] values) {
- assert(keys.length == values.length);
- for (int i = 0; i < keys.length; i++) {
- map.put(keys[i], values[i]);
- }
- }
-
- private <K, V> void assertMapSet(
- Map<K, V> map, K[] keys, V[] values) throws Exception {
- assert(keys.length == values.length);
- for (int i = 0; i < values.length; i++) {
- assertEquals(values[i], map.get(keys[i]));
- }
- assertEquals(keys.length, map.size());
- }
-
- private void setMapMessage(TestMap testMap) {
- testMap.int32ToInt32Field = new HashMap<Integer, Integer>();
- testMap.int32ToBytesField = new HashMap<Integer, byte[]>();
- testMap.int32ToEnumField = new HashMap<Integer, Integer>();
- testMap.int32ToMessageField =
- new HashMap<Integer, MapTestProto.TestMap.MessageValue>();
- testMap.int32ToStringField = new HashMap<Integer, String>();
- testMap.stringToInt32Field = new HashMap<String, Integer>();
- testMap.boolToBoolField = new HashMap<Boolean, Boolean>();
- testMap.uint32ToUint32Field = new HashMap<Integer, Integer>();
- testMap.sint32ToSint32Field = new HashMap<Integer, Integer>();
- testMap.fixed32ToFixed32Field = new HashMap<Integer, Integer>();
- testMap.sfixed32ToSfixed32Field = new HashMap<Integer, Integer>();
- testMap.int64ToInt64Field = new HashMap<Long, Long>();
- testMap.uint64ToUint64Field = new HashMap<Long, Long>();
- testMap.sint64ToSint64Field = new HashMap<Long, Long>();
- testMap.fixed64ToFixed64Field = new HashMap<Long, Long>();
- testMap.sfixed64ToSfixed64Field = new HashMap<Long, Long>();
- setMap(testMap.int32ToInt32Field, int32Values, int32Values);
- setMap(testMap.int32ToBytesField, int32Values, bytesValues);
- setMap(testMap.int32ToEnumField, int32Values, enumValues);
- setMap(testMap.int32ToMessageField, int32Values, messageValues);
- setMap(testMap.int32ToStringField, int32Values, stringValues);
- setMap(testMap.stringToInt32Field, stringValues, int32Values);
- setMap(testMap.boolToBoolField, boolValues, boolValues);
- setMap(testMap.uint32ToUint32Field, int32Values, int32Values);
- setMap(testMap.sint32ToSint32Field, int32Values, int32Values);
- setMap(testMap.fixed32ToFixed32Field, int32Values, int32Values);
- setMap(testMap.sfixed32ToSfixed32Field, int32Values, int32Values);
- setMap(testMap.int64ToInt64Field, int64Values, int64Values);
- setMap(testMap.uint64ToUint64Field, int64Values, int64Values);
- setMap(testMap.sint64ToSint64Field, int64Values, int64Values);
- setMap(testMap.fixed64ToFixed64Field, int64Values, int64Values);
- setMap(testMap.sfixed64ToSfixed64Field, int64Values, int64Values);
- }
- private void assertMapMessageSet(TestMap testMap) throws Exception {
- assertMapSet(testMap.int32ToInt32Field, int32Values, int32Values);
- assertMapSet(testMap.int32ToBytesField, int32Values, bytesValues);
- assertMapSet(testMap.int32ToEnumField, int32Values, enumValues);
- assertMapSet(testMap.int32ToMessageField, int32Values, messageValues);
- assertMapSet(testMap.int32ToStringField, int32Values, stringValues);
- assertMapSet(testMap.stringToInt32Field, stringValues, int32Values);
- assertMapSet(testMap.boolToBoolField, boolValues, boolValues);
- assertMapSet(testMap.uint32ToUint32Field, int32Values, int32Values);
- assertMapSet(testMap.sint32ToSint32Field, int32Values, int32Values);
- assertMapSet(testMap.fixed32ToFixed32Field, int32Values, int32Values);
- assertMapSet(testMap.sfixed32ToSfixed32Field, int32Values, int32Values);
- assertMapSet(testMap.int64ToInt64Field, int64Values, int64Values);
- assertMapSet(testMap.uint64ToUint64Field, int64Values, int64Values);
- assertMapSet(testMap.sint64ToSint64Field, int64Values, int64Values);
- assertMapSet(testMap.fixed64ToFixed64Field, int64Values, int64Values);
- assertMapSet(testMap.sfixed64ToSfixed64Field, int64Values, int64Values);
- }
-
- public void testRepeatedFieldInitializedInReftypesCompatMode() {
- NanoReferenceTypesCompat.TestAllTypesNano proto = new NanoReferenceTypesCompat.TestAllTypesNano();
- assertNotNull(proto.repeatedString);
- }
-
- private void assertRepeatedPackablesEqual(
- NanoRepeatedPackables.NonPacked nonPacked, NanoRepeatedPackables.Packed packed) {
- // Not using MessageNano.equals() -- that belongs to a separate test.
- assertTrue(Arrays.equals(nonPacked.int32S, packed.int32S));
- assertTrue(Arrays.equals(nonPacked.int64S, packed.int64S));
- assertTrue(Arrays.equals(nonPacked.uint32S, packed.uint32S));
- assertTrue(Arrays.equals(nonPacked.uint64S, packed.uint64S));
- assertTrue(Arrays.equals(nonPacked.sint32S, packed.sint32S));
- assertTrue(Arrays.equals(nonPacked.sint64S, packed.sint64S));
- assertTrue(Arrays.equals(nonPacked.fixed32S, packed.fixed32S));
- assertTrue(Arrays.equals(nonPacked.fixed64S, packed.fixed64S));
- assertTrue(Arrays.equals(nonPacked.sfixed32S, packed.sfixed32S));
- assertTrue(Arrays.equals(nonPacked.sfixed64S, packed.sfixed64S));
- assertTrue(Arrays.equals(nonPacked.floats, packed.floats));
- assertTrue(Arrays.equals(nonPacked.doubles, packed.doubles));
- assertTrue(Arrays.equals(nonPacked.bools, packed.bools));
- assertTrue(Arrays.equals(nonPacked.enums, packed.enums));
- }
-
- public void testClone() throws Exception {
- // A simple message.
- AnotherMessage anotherMessage = new AnotherMessage();
- anotherMessage.string = "Hello";
- anotherMessage.value = true;
- anotherMessage.integers = new int[] { 1, 2, 3 };
-
- AnotherMessage clone = anotherMessage.clone();
- assertEquals(clone, anotherMessage);
-
- // Verify it was a deep clone - changes to the clone shouldn't affect the
- // original.
- clone.integers[1] = 100;
- assertFalse(clone.equals(anotherMessage));
- }
-
- private void assertHasWireData(MessageNano message, boolean expected) {
- byte[] bytes = MessageNano.toByteArray(message);
- int wireLength = bytes.length;
- if (expected) {
- assertFalse(wireLength == 0);
- } else {
- if (wireLength != 0) {
- fail("Expected no wire data for message \n" + message
- + "\nBut got:\n"
- + hexDump(bytes));
- }
- }
- }
-
- private static String hexDump(byte[] bytes) {
- StringBuilder sb = new StringBuilder();
- for (byte b : bytes) {
- sb.append(String.format("%02x ", b));
- }
- return sb.toString();
- }
-}
diff --git a/javanano/src/test/java/com/google/protobuf/nano/map_test.proto b/javanano/src/test/java/com/google/protobuf/nano/map_test.proto
deleted file mode 100644
index 51498a49..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/map_test.proto
+++ /dev/null
@@ -1,70 +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.
-
-syntax = "proto3";
-
-package map_test;
-
-option java_package = "com.google.protobuf";
-option java_outer_classname = "MapTestProto";
-
-message TestMap {
- message MessageValue {
- int32 value = 1;
- int32 value2 = 2;
- }
- enum EnumValue {
- FOO = 0;
- BAR = 1;
- BAZ = 2;
- QUX = 3;
- }
-
- map<int32, int32> int32_to_int32_field = 1;
- map<int32, string> int32_to_string_field = 2;
- map<int32, bytes> int32_to_bytes_field = 3;
- map<int32, EnumValue> int32_to_enum_field = 4;
- map<int32, MessageValue> int32_to_message_field = 5;
- map<string, int32> string_to_int32_field = 6;
- map<bool, bool> bool_to_bool_field = 7;
-
- // Test all the other primitive types. As the key and value are not coupled in
- // the implementation, we do not test all the combinations of key/value pairs,
- // so that we can keep the number of test cases manageable
- map<uint32, uint32> uint32_to_uint32_field = 11;
- map<sint32, sint32> sint32_to_sint32_field = 12;
- map<fixed32, fixed32> fixed32_to_fixed32_field = 13;
- map<sfixed32, sfixed32> sfixed32_to_sfixed32_field = 14;
- map<int64, int64> int64_to_int64_field = 15;
- map<uint64, uint64> uint64_to_uint64_field = 16;
- map<sint64, sint64> sint64_to_sint64_field = 17;
- map<fixed64, fixed64> fixed64_to_fixed64_field = 18;
- map<sfixed64, sfixed64> sfixed64_to_sfixed64_field = 19;
-}
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_accessors_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_accessors_nano.proto
deleted file mode 100644
index 6511e470..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_accessors_nano.proto
+++ /dev/null
@@ -1,118 +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: maxtroy@google.com (Max Cai)
-
-package protobuf_unittest;
-
-option java_package = "com.google.protobuf";
-option java_outer_classname = "NanoAccessorsOuterClass";
-
-message TestNanoAccessors {
-
- message NestedMessage {
- optional int32 bb = 1;
- }
-
- enum NestedEnum {
- FOO = 1;
- BAR = 2;
- BAZ = 3;
- }
-
- // Singular
- optional int32 optional_int32 = 1;
- optional float optional_float = 11;
- optional double optional_double = 12;
- optional string optional_string = 14;
- optional bytes optional_bytes = 15;
-
- optional NestedMessage optional_nested_message = 18;
-
- optional NestedEnum optional_nested_enum = 21;
-
- // Repeated
- repeated int32 repeated_int32 = 31;
- repeated string repeated_string = 44;
- repeated bytes repeated_bytes = 45;
-
- repeated NestedMessage repeated_nested_message = 48;
-
- repeated NestedEnum repeated_nested_enum = 51;
-
- // Singular with defaults
- optional int32 default_int32 = 61 [default = 41 ];
- optional string default_string = 74 [default = "hello"];
- optional bytes default_bytes = 75 [default = "world"];
-
- optional float default_float_nan = 99 [default = nan];
-
- optional NestedEnum default_nested_enum = 81 [default = BAR];
-
- // Required
- required int32 id = 86;
-
- // Add enough optional fields to make 2 bit fields in total
- optional int32 filler100 = 100;
- optional int32 filler101 = 101;
- optional int32 filler102 = 102;
- optional int32 filler103 = 103;
- optional int32 filler104 = 104;
- optional int32 filler105 = 105;
- optional int32 filler106 = 106;
- optional int32 filler107 = 107;
- optional int32 filler108 = 108;
- optional int32 filler109 = 109;
- optional int32 filler110 = 110;
- optional int32 filler111 = 111;
- optional int32 filler112 = 112;
- optional int32 filler113 = 113;
- optional int32 filler114 = 114;
- optional int32 filler115 = 115;
- optional int32 filler116 = 116;
- optional int32 filler117 = 117;
- optional int32 filler118 = 118;
- optional int32 filler119 = 119;
- optional int32 filler120 = 120;
- optional int32 filler121 = 121;
- optional int32 filler122 = 122;
- optional int32 filler123 = 123;
- optional int32 filler124 = 124;
- optional int32 filler125 = 125;
- optional int32 filler126 = 126;
- optional int32 filler127 = 127;
- optional int32 filler128 = 128;
- optional int32 filler129 = 129;
- optional int32 filler130 = 130;
-
- optional int32 before_bit_field_check = 139;
- optional int32 bit_field_check = 140;
- optional int32 after_bit_field_check = 141;
-}
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_validity_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_validity_nano.proto
deleted file mode 100644
index c0da8b42..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_validity_nano.proto
+++ /dev/null
@@ -1,28 +0,0 @@
-package protobuf_unittest;
-
-option java_package = "com.google.protobuf";
-option java_outer_classname = "EnumValidity";
-
-enum E {
- default = 1; // test java keyword renaming
- FOO = 2;
- BAR = 3;
- BAZ = 4;
-}
-
-message M {
- optional E optional_e = 1;
- optional E default_e = 2 [ default = BAZ ];
- repeated E repeated_e = 3;
- repeated E packed_e = 4 [ packed = true ];
- repeated E repeated_e2 = 5;
- repeated E packed_e2 = 6 [ packed = true ];
- repeated E repeated_e3 = 7;
- repeated E packed_e3 = 8 [ packed = true ];
-}
-
-message Alt {
- optional E repeated_e2_as_optional = 5;
- repeated E packed_e2_as_non_packed = 6;
- repeated E non_packed_e3_as_packed = 7 [ packed = true ];
-}
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_nano.proto
deleted file mode 100644
index ca56b3dd..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_nano.proto
+++ /dev/null
@@ -1,37 +0,0 @@
-syntax = "proto2";
-
-option java_outer_classname = "Extensions";
-option java_package = "com.google.protobuf.nano.testext";
-
-message ExtendableMessage {
- optional int32 field = 1;
- extensions 10 to max;
-}
-
-enum AnEnum {
- FIRST_VALUE = 1;
- SECOND_VALUE = 2;
-}
-
-message AnotherMessage {
- optional string string = 1;
- optional bool value = 2;
- repeated int32 integers = 3;
-}
-
-message ContainerMessage {
- extend ExtendableMessage {
- optional bool another_thing = 100;
- // The largest permitted field number, per
- // https://developers.google.com/protocol-buffers/docs/proto#simple
- optional bool large_field_number = 536870911;
- }
-}
-
-// For testNanoOptionalGroupWithUnknownFieldsEnabled;
-// not part of the extensions tests.
-message MessageWithGroup {
- optional group Group = 1 {
- optional int32 a = 2;
- }
-}
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_packed_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_packed_nano.proto
deleted file mode 100644
index 3b7a004c..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_packed_nano.proto
+++ /dev/null
@@ -1,29 +0,0 @@
-syntax = "proto2";
-
-option java_multiple_files = true;
-option java_package = "com.google.protobuf";
-
-import "google/protobuf/nano/unittest_extension_nano.proto";
-
-// Must be compiled separately due to extension number reuse.
-// The reuse is deliberate, for testing wire compatibility.
-
-message PackedExtensions {
- extend ExtendableMessage {
- repeated int32 packed_int32 = 10 [ packed = true ];
- repeated uint32 packed_uint32 = 11 [ packed = true ];
- repeated sint32 packed_sint32 = 12 [ packed = true ];
- repeated int64 packed_int64 = 13 [ packed = true ];
- repeated uint64 packed_uint64 = 14 [ packed = true ];
- repeated sint64 packed_sint64 = 15 [ packed = true ];
- repeated fixed32 packed_fixed32 = 16 [ packed = true ];
- repeated sfixed32 packed_sfixed32 = 17 [ packed = true ];
- repeated fixed64 packed_fixed64 = 18 [ packed = true ];
- repeated sfixed64 packed_sfixed64 = 19 [ packed = true ];
- repeated bool packed_bool = 20 [ packed = true ];
- repeated float packed_float = 21 [ packed = true ];
- repeated double packed_double = 22 [ packed = true ];
- repeated AnEnum packed_enum = 23 [ packed = true ];
- // Non-packable types omitted.
- }
-}
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_repeated_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_repeated_nano.proto
deleted file mode 100644
index e533c65b..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_repeated_nano.proto
+++ /dev/null
@@ -1,34 +0,0 @@
-syntax = "proto2";
-
-option java_multiple_files = true;
-option java_package = "com.google.protobuf";
-
-import "google/protobuf/nano/unittest_extension_nano.proto";
-
-// Must be compiled separately due to extension number reuse.
-// The reuse is deliberate, for testing wire compatibility.
-
-message RepeatedExtensions {
- extend ExtendableMessage {
- repeated int32 repeated_int32 = 10;
- repeated uint32 repeated_uint32 = 11;
- repeated sint32 repeated_sint32 = 12;
- repeated int64 repeated_int64 = 13;
- repeated uint64 repeated_uint64 = 14;
- repeated sint64 repeated_sint64 = 15;
- repeated fixed32 repeated_fixed32 = 16;
- repeated sfixed32 repeated_sfixed32 = 17;
- repeated fixed64 repeated_fixed64 = 18;
- repeated sfixed64 repeated_sfixed64 = 19;
- repeated bool repeated_bool = 20;
- repeated float repeated_float = 21;
- repeated double repeated_double = 22;
- repeated AnEnum repeated_enum = 23;
- repeated string repeated_string = 24;
- repeated bytes repeated_bytes = 25;
- repeated AnotherMessage repeated_message = 26;
- repeated group RepeatedGroup = 27 {
- optional int32 a = 1;
- }
- }
-}
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_singular_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_singular_nano.proto
deleted file mode 100644
index 8b2d9658..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_singular_nano.proto
+++ /dev/null
@@ -1,34 +0,0 @@
-syntax = "proto2";
-
-option java_multiple_files = true;
-option java_package = "com.google.protobuf";
-
-import "google/protobuf/nano/unittest_extension_nano.proto";
-
-// Must be compiled separately due to extension number reuse.
-// The reuse is deliberate, for testing wire compatibility.
-
-message SingularExtensions {
- extend ExtendableMessage {
- optional int32 some_int32 = 10;
- optional uint32 some_uint32 = 11;
- optional sint32 some_sint32 = 12;
- optional int64 some_int64 = 13;
- optional uint64 some_uint64 = 14;
- optional sint64 some_sint64 = 15;
- optional fixed32 some_fixed32 = 16;
- optional sfixed32 some_sfixed32 = 17;
- optional fixed64 some_fixed64 = 18;
- optional sfixed64 some_sfixed64 = 19;
- optional bool some_bool = 20;
- optional float some_float = 21;
- optional double some_double = 22;
- optional AnEnum some_enum = 23;
- optional string some_string = 24;
- optional bytes some_bytes = 25;
- optional AnotherMessage some_message = 26;
- optional group SomeGroup = 27 {
- optional int32 a = 1;
- }
- }
-}
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_has_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_has_nano.proto
deleted file mode 100644
index fe7d1794..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_has_nano.proto
+++ /dev/null
@@ -1,82 +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: ulas@google.com (Ulas Kirazci)
-
-package protobuf_unittest;
-
-option java_package = "com.google.protobuf";
-option java_outer_classname = "NanoHasOuterClass";
-
-message TestAllTypesNanoHas {
-
- message NestedMessage {
- optional int32 bb = 1;
- }
-
- enum NestedEnum {
- FOO = 1;
- BAR = 2;
- BAZ = 3;
- }
-
- // Singular
- optional int32 optional_int32 = 1;
- optional float optional_float = 11;
- optional double optional_double = 12;
- optional string optional_string = 14;
- optional bytes optional_bytes = 15;
-
- optional NestedMessage optional_nested_message = 18;
-
- optional NestedEnum optional_nested_enum = 21;
-
- // Repeated
- repeated int32 repeated_int32 = 31;
- repeated string repeated_string = 44;
- repeated bytes repeated_bytes = 45;
-
- repeated NestedMessage repeated_nested_message = 48;
-
- repeated NestedEnum repeated_nested_enum = 51;
-
- // Singular with defaults
- optional int32 default_int32 = 61 [default = 41 ];
- optional string default_string = 74 [default = "hello"];
- optional bytes default_bytes = 75 [default = "world"];
-
- optional float default_float_nan = 99 [default = nan];
-
- optional NestedEnum default_nested_enum = 81 [default = BAR];
-
- required int32 id = 86;
- required NestedEnum required_enum = 87;
-
-}
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_import_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_import_nano.proto
deleted file mode 100644
index 1a3ddc57..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_import_nano.proto
+++ /dev/null
@@ -1,48 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-//
-// This is like unittest_import.proto but with optimize_for = NANO_RUNTIME.
-
-package protobuf_unittest_import;
-
-option java_package = "com.google.protobuf.nano.testimport";
-option java_outer_classname = "UnittestImportNano";
-
-message ImportMessageNano {
- optional int32 d = 1;
-}
-
-enum ImportEnumNano {
- IMPORT_NANO_FOO = 7;
- IMPORT_NANO_BAR = 8;
- IMPORT_NANO_BAZ = 9;
-}
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_nano.proto
deleted file mode 100644
index 3fff24c0..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_nano.proto
+++ /dev/null
@@ -1,195 +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: wink@google.com (Wink Saville)
-
-package protobuf_unittest;
-
-import "google/protobuf/nano/unittest_import_nano.proto";
-
-option java_package = "com.google.protobuf";
-option java_outer_classname = "NanoOuterClass";
-
-// Same as TestAllTypes but with the nano runtime.
-message TestAllTypesNano {
-
- message NestedMessage {
- optional int32 bb = 1;
- }
-
- enum NestedEnum {
- FOO = 1;
- BAR = 2;
- BAZ = 3;
- }
-
- // Singular
- optional int32 optional_int32 = 1;
- optional int64 optional_int64 = 2;
- optional uint32 optional_uint32 = 3;
- optional uint64 optional_uint64 = 4;
- optional sint32 optional_sint32 = 5;
- optional sint64 optional_sint64 = 6;
- optional fixed32 optional_fixed32 = 7;
- optional fixed64 optional_fixed64 = 8;
- optional sfixed32 optional_sfixed32 = 9;
- optional sfixed64 optional_sfixed64 = 10;
- optional float optional_float = 11;
- optional double optional_double = 12;
- optional bool optional_bool = 13;
- optional string optional_string = 14;
- optional bytes optional_bytes = 15;
-
- optional group OptionalGroup = 16 {
- optional int32 a = 17;
- }
-
- optional NestedMessage optional_nested_message = 18;
- optional ForeignMessageNano optional_foreign_message = 19;
- optional protobuf_unittest_import.ImportMessageNano
- optional_import_message = 20;
-
- optional NestedEnum optional_nested_enum = 21;
- optional ForeignEnumNano optional_foreign_enum = 22;
- optional protobuf_unittest_import.ImportEnumNano optional_import_enum = 23;
-
- optional string optional_string_piece = 24 [ctype=STRING_PIECE];
- optional string optional_cord = 25 [ctype=CORD];
-
- // Repeated
- repeated int32 repeated_int32 = 31;
- repeated int64 repeated_int64 = 32;
- repeated uint32 repeated_uint32 = 33;
- repeated uint64 repeated_uint64 = 34;
- repeated sint32 repeated_sint32 = 35;
- repeated sint64 repeated_sint64 = 36;
- repeated fixed32 repeated_fixed32 = 37;
- repeated fixed64 repeated_fixed64 = 38;
- repeated sfixed32 repeated_sfixed32 = 39;
- repeated sfixed64 repeated_sfixed64 = 40;
- repeated float repeated_float = 41;
- repeated double repeated_double = 42;
- repeated bool repeated_bool = 43;
- repeated string repeated_string = 44;
- repeated bytes repeated_bytes = 45;
-
- repeated group RepeatedGroup = 46 {
- optional int32 a = 47;
- }
-
- repeated NestedMessage repeated_nested_message = 48;
- repeated ForeignMessageNano repeated_foreign_message = 49;
- repeated protobuf_unittest_import.ImportMessageNano
- repeated_import_message = 50;
-
- repeated NestedEnum repeated_nested_enum = 51;
- repeated ForeignEnumNano repeated_foreign_enum = 52;
- repeated protobuf_unittest_import.ImportEnumNano repeated_import_enum = 53;
-
- repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
- repeated string repeated_cord = 55 [ctype=CORD];
-
- // Repeated packed
- repeated int32 repeated_packed_int32 = 87 [packed=true];
- repeated sfixed64 repeated_packed_sfixed64 = 88 [packed=true];
-
- repeated NestedEnum repeated_packed_nested_enum = 89 [packed=true];
-
- // Singular with defaults
- optional int32 default_int32 = 61 [default = 41 ];
- optional int64 default_int64 = 62 [default = 42 ];
- optional uint32 default_uint32 = 63 [default = 43 ];
- optional uint64 default_uint64 = 64 [default = 44 ];
- optional sint32 default_sint32 = 65 [default = -45 ];
- optional sint64 default_sint64 = 66 [default = 46 ];
- optional fixed32 default_fixed32 = 67 [default = 47 ];
- optional fixed64 default_fixed64 = 68 [default = 48 ];
- optional sfixed32 default_sfixed32 = 69 [default = 49 ];
- optional sfixed64 default_sfixed64 = 70 [default = -50 ];
- optional float default_float = 71 [default = 51.5 ];
- optional double default_double = 72 [default = 52e3 ];
- optional bool default_bool = 73 [default = true ];
- optional string default_string = 74 [default = "hello"];
- optional bytes default_bytes = 75 [default = "world"];
-
- optional string default_string_nonascii = 76 [default = "dünya"];
- optional bytes default_bytes_nonascii = 77 [default = "dünyab"];
-
- optional float default_float_inf = 97 [default = inf];
- optional float default_float_neg_inf = 98 [default = -inf];
- optional float default_float_nan = 99 [default = nan];
- optional double default_double_inf = 100 [default = inf];
- optional double default_double_neg_inf = 101 [default = -inf];
- optional double default_double_nan = 102 [default = nan];
-
- optional NestedEnum default_nested_enum = 81 [default = BAR];
- optional ForeignEnumNano default_foreign_enum = 82
- [default = FOREIGN_NANO_BAR];
- optional protobuf_unittest_import.ImportEnumNano
- default_import_enum = 83 [default = IMPORT_NANO_BAR];
-
- optional string default_string_piece = 84 [ctype=STRING_PIECE,default="abc"];
- optional string default_cord = 85 [ctype=CORD,default="123"];
-
- required int32 id = 86;
-
- // Try to cause conflicts.
- optional int32 tag = 93;
- optional int32 get_serialized_size = 94;
- optional int32 write_to = 95;
-
- // Try to fail with java reserved keywords
- optional int32 synchronized = 96;
-
- oneof oneof_field {
- uint32 oneof_uint32 = 111;
- NestedMessage oneof_nested_message = 112;
- string oneof_string = 123;
- bytes oneof_bytes = 124;
- fixed64 oneof_fixed64 = 115;
- NestedEnum oneof_enum = 116;
- }
-}
-
-message ForeignMessageNano {
- optional int32 c = 1;
-}
-
-enum ForeignEnumNano {
- FOREIGN_NANO_FOO = 4;
- FOREIGN_NANO_BAR = 5;
- FOREIGN_NANO_BAZ = 6;
-}
-
-// Test that deprecated fields work. We only verify that they compile (at one
-// point this failed).
-message TestDeprecatedNano {
- optional int32 deprecated_field = 1 [deprecated = true];
-}
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_recursive_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_recursive_nano.proto
deleted file mode 100644
index 29b944f0..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_recursive_nano.proto
+++ /dev/null
@@ -1,49 +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: wink@google.com (Wink Saville)
-//
-
-package protobuf_unittest_import;
-
-option java_package = "com.google.protobuf";
-// Explicit outer classname to suppress legacy info.
-option java_outer_classname = "UnittestRecursiveNano";
-
-message RecursiveMessageNano {
- message NestedMessage {
- optional RecursiveMessageNano a = 1;
- }
-
- required int32 id = 1;
- optional NestedMessage nested_message = 2;
- optional RecursiveMessageNano optional_recursive_message_nano = 3;
- repeated RecursiveMessageNano repeated_recursive_message_nano = 4;
-}
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_reference_types_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_reference_types_nano.proto
deleted file mode 100644
index 82eb8d11..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_reference_types_nano.proto
+++ /dev/null
@@ -1,116 +0,0 @@
-package protobuf_unittest;
-
-option java_package = "com.google.protobuf";
-option java_outer_classname = "NanoReferenceTypes";
-
-message TestAllTypesNano {
-
- enum NestedEnum {
- FOO = 1;
- BAR = 2;
- BAZ = 3;
- }
-
- message NestedMessage {
- optional int32 foo = 1;
- }
-
- // Singular
- optional int32 optional_int32 = 1;
- optional int64 optional_int64 = 2;
- optional uint32 optional_uint32 = 3;
- optional uint64 optional_uint64 = 4;
- optional sint32 optional_sint32 = 5;
- optional sint64 optional_sint64 = 6;
- optional fixed32 optional_fixed32 = 7;
- optional fixed64 optional_fixed64 = 8;
- optional sfixed32 optional_sfixed32 = 9;
- optional sfixed64 optional_sfixed64 = 10;
- optional float optional_float = 11;
- optional double optional_double = 12;
- optional bool optional_bool = 13;
- optional string optional_string = 14;
- optional bytes optional_bytes = 15;
-
- optional group OptionalGroup = 16 {
- optional int32 a = 17;
- }
-
- optional NestedMessage optional_nested_message = 18;
-
- optional NestedEnum optional_nested_enum = 21;
-
- optional string optional_string_piece = 24 [ctype=STRING_PIECE];
- optional string optional_cord = 25 [ctype=CORD];
-
- // Repeated
- repeated int32 repeated_int32 = 31;
- repeated int64 repeated_int64 = 32;
- repeated uint32 repeated_uint32 = 33;
- repeated uint64 repeated_uint64 = 34;
- repeated sint32 repeated_sint32 = 35;
- repeated sint64 repeated_sint64 = 36;
- repeated fixed32 repeated_fixed32 = 37;
- repeated fixed64 repeated_fixed64 = 38;
- repeated sfixed32 repeated_sfixed32 = 39;
- repeated sfixed64 repeated_sfixed64 = 40;
- repeated float repeated_float = 41;
- repeated double repeated_double = 42;
- repeated bool repeated_bool = 43;
- repeated string repeated_string = 44;
- repeated bytes repeated_bytes = 45;
-
- repeated group RepeatedGroup = 46 {
- optional int32 a = 47;
- }
-
- repeated NestedMessage repeated_nested_message = 48;
-
- repeated NestedEnum repeated_nested_enum = 51;
-
- repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
- repeated string repeated_cord = 55 [ctype=CORD];
-
- // Repeated packed
- repeated int32 repeated_packed_int32 = 87 [packed=true];
- repeated sfixed64 repeated_packed_sfixed64 = 88 [packed=true];
-
- repeated NestedEnum repeated_packed_nested_enum = 89 [packed=true];
-
- // Singular with defaults
- optional int32 default_int32 = 61 [default = 41 ];
- optional int64 default_int64 = 62 [default = 42 ];
- optional uint32 default_uint32 = 63 [default = 43 ];
- optional uint64 default_uint64 = 64 [default = 44 ];
- optional sint32 default_sint32 = 65 [default = -45 ];
- optional sint64 default_sint64 = 66 [default = 46 ];
- optional fixed32 default_fixed32 = 67 [default = 47 ];
- optional fixed64 default_fixed64 = 68 [default = 48 ];
- optional sfixed32 default_sfixed32 = 69 [default = 49 ];
- optional sfixed64 default_sfixed64 = 70 [default = -50 ];
- optional float default_float = 71 [default = 51.5 ];
- optional double default_double = 72 [default = 52e3 ];
- optional bool default_bool = 73 [default = true ];
- optional string default_string = 74 [default = "hello"];
- optional bytes default_bytes = 75 [default = "world"];
-
-
- optional float default_float_inf = 97 [default = inf];
- optional float default_float_neg_inf = 98 [default = -inf];
- optional float default_float_nan = 99 [default = nan];
- optional double default_double_inf = 100 [default = inf];
- optional double default_double_neg_inf = 101 [default = -inf];
- optional double default_double_nan = 102 [default = nan];
-
-}
-
-message ForeignMessageNano {
- optional int32 c = 1;
-}
-
-enum ForeignEnumNano {
- FOREIGN_NANO_FOO = 4;
- FOREIGN_NANO_BAR = 5;
- FOREIGN_NANO_BAZ = 6;
-}
-
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_packables_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_packables_nano.proto
deleted file mode 100644
index 96af8856..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_packables_nano.proto
+++ /dev/null
@@ -1,95 +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: maxtroy@google.com (Max Cai)
-
-package protobuf_unittest;
-
-option java_package = "com.google.protobuf";
-option java_outer_classname = "NanoRepeatedPackables";
-
-enum Enum {
- OPTION_ONE = 1;
- OPTION_TWO = 2;
-}
-
-// Two almost identical messages with all packable repeated field types.
-// One with none marked as packed and the other all packed. For
-// compatibility, they should be able to parse each other's serialized
-// forms.
-
-message NonPacked {
-
- // All packable types, none marked as packed.
-
- repeated int32 int32s = 1;
- repeated int64 int64s = 2;
- repeated uint32 uint32s = 3;
- repeated uint64 uint64s = 4;
- repeated sint32 sint32s = 5;
- repeated sint64 sint64s = 6;
- repeated fixed32 fixed32s = 7;
- repeated fixed64 fixed64s = 8;
- repeated sfixed32 sfixed32s = 9;
- repeated sfixed64 sfixed64s = 10;
- repeated float floats = 11;
- repeated double doubles = 12;
- repeated bool bools = 13;
- repeated Enum enums = 14;
-
- // Noise for testing merged deserialization.
- optional int32 noise = 15;
-
-}
-
-message Packed {
-
- // All packable types, all matching the field numbers in NonPacked,
- // all marked as packed.
-
- repeated int32 int32s = 1 [ packed = true ];
- repeated int64 int64s = 2 [ packed = true ];
- repeated uint32 uint32s = 3 [ packed = true ];
- repeated uint64 uint64s = 4 [ packed = true ];
- repeated sint32 sint32s = 5 [ packed = true ];
- repeated sint64 sint64s = 6 [ packed = true ];
- repeated fixed32 fixed32s = 7 [ packed = true ];
- repeated fixed64 fixed64s = 8 [ packed = true ];
- repeated sfixed32 sfixed32s = 9 [ packed = true ];
- repeated sfixed64 sfixed64s = 10 [ packed = true ];
- repeated float floats = 11 [ packed = true ];
- repeated double doubles = 12 [ packed = true ];
- repeated bool bools = 13 [ packed = true ];
- repeated Enum enums = 14 [ packed = true ];
-
- // Noise for testing merged deserialization.
- optional int32 noise = 15;
-
-}
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_simple_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_simple_nano.proto
deleted file mode 100644
index 25786cc2..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_simple_nano.proto
+++ /dev/null
@@ -1,54 +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: wink@google.com (Wink Saville)
-//
-
-package protobuf_unittest_import;
-
-option java_package = "com.google.protobuf";
-// Explicit outer classname to suppress legacy info.
-option java_outer_classname = "UnittestSimpleNano";
-
-message SimpleMessageNano {
- message NestedMessage {
- optional int32 bb = 1;
- }
-
- enum NestedEnum {
- FOO = 1;
- BAR = 2;
- BAZ = 3;
- }
-
- optional int32 d = 1 [default = 123];
- optional NestedMessage nested_msg = 2;
- optional NestedEnum default_nested_enum = 3 [default = BAZ];
-}
diff --git a/jenkins/README.md b/jenkins/README.md
deleted file mode 100644
index 29f664f2..00000000
--- a/jenkins/README.md
+++ /dev/null
@@ -1,6 +0,0 @@
-
-Jenkins Infrastructure
-----------------------
-
-The scripts in this directory serve as plumbing for running the protobuf
-tests under Jenkins.
diff --git a/jenkins/build_and_run_docker.sh b/jenkins/build_and_run_docker.sh
deleted file mode 100755
index 50e1e8c6..00000000
--- a/jenkins/build_and_run_docker.sh
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/bin/bash
-#
-# Builds docker image and runs a command under it.
-# This is a generic script that is configured with the following variables:
-#
-# DOCKERFILE_DIR - Directory in which Dockerfile file is located.
-# DOCKER_RUN_SCRIPT - Script to run under docker (relative to protobuf repo root)
-# OUTPUT_DIR - Directory that will be copied from inside docker after finishing.
-# $@ - Extra args to pass to docker run
-
-
-set -ex
-
-cd $(dirname $0)/..
-git_root=$(pwd)
-cd -
-
-# Use image name based on Dockerfile location checksum
-DOCKER_IMAGE_NAME=$(basename $DOCKERFILE_DIR)_$(sha1sum $DOCKERFILE_DIR/Dockerfile | cut -f1 -d\ )
-
-# Make sure docker image has been built. Should be instantaneous if so.
-docker build -t $DOCKER_IMAGE_NAME $DOCKERFILE_DIR
-
-# Ensure existence of ccache directory
-CCACHE_DIR=/tmp/protobuf-ccache
-mkdir -p $CCACHE_DIR
-
-# Choose random name for docker container
-CONTAINER_NAME="build_and_run_docker_$(uuidgen)"
-
-# Run command inside docker
-docker run \
- "$@" \
- -e CCACHE_DIR=$CCACHE_DIR \
- -e EXTERNAL_GIT_ROOT="/var/local/jenkins/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/jenkins/protobuf:ro" \
- -v $CCACHE_DIR:$CCACHE_DIR \
- -w /var/local/git/protobuf \
- --name=$CONTAINER_NAME \
- $DOCKER_IMAGE_NAME \
- bash -l "/var/local/jenkins/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" || FAILED="true"
-fi
-
-# remove the container, possibly killing it first
-docker rm -f $CONTAINER_NAME || true
-
-if [ "$FAILED" != "" ]
-then
- exit 1
-fi
diff --git a/jenkins/buildcmds/README.md b/jenkins/buildcmds/README.md
deleted file mode 100644
index 7a48f2d5..00000000
--- a/jenkins/buildcmds/README.md
+++ /dev/null
@@ -1,6 +0,0 @@
-
-Jenkins Build Commands
-----------------------
-
-The scripts in this directory are designed to be top-level entry points for
-Jenkins projects.
diff --git a/jenkins/buildcmds/pull_request.sh b/jenkins/buildcmds/pull_request.sh
deleted file mode 100755
index 51e4bfa4..00000000
--- a/jenkins/buildcmds/pull_request.sh
+++ /dev/null
@@ -1,16 +0,0 @@
-#!/bin/bash
-#
-# This is the top-level script we give to Jenkins as the entry point for
-# running the "pull request" project:
-#
-# https://grpc-testing.appspot.com/view/Protocol%20Buffers/job/protobuf_pull_request/
-#
-# This script selects a specific Dockerfile (for building a Docker image) and
-# a script to run inside that image. Then we delegate to the general
-# build_and_run_docker.sh script.
-
-export DOCKERFILE_DIR=jenkins/docker
-export DOCKER_RUN_SCRIPT=jenkins/pull_request_in_docker.sh
-export OUTPUT_DIR=testoutput
-export TEST_SET="csharp java_jdk7 javanano_jdk7 java_oracle7 javanano_oracle7 python python_cpp ruby_all javascript golang php_all"
-./jenkins/build_and_run_docker.sh
diff --git a/jenkins/buildcmds/pull_request_32.sh b/jenkins/buildcmds/pull_request_32.sh
deleted file mode 100755
index bf0fb7ff..00000000
--- a/jenkins/buildcmds/pull_request_32.sh
+++ /dev/null
@@ -1,16 +0,0 @@
-#!/bin/bash
-#
-# This is the top-level script we give to Jenkins as the entry point for
-# running the "pull request 32" project:
-#
-# https://grpc-testing.appspot.com/view/Protocol%20Buffers/job/Protocol%20Buffers%20Pull%20Request%2032/
-#
-# This script selects a specific Dockerfile (for building a Docker image) and
-# a script to run inside that image. Then we delegate to the general
-# build_and_run_docker.sh script.
-
-export DOCKERFILE_DIR=jenkins/docker32
-export DOCKER_RUN_SCRIPT=jenkins/pull_request_in_docker.sh
-export OUTPUT_DIR=testoutput
-export TEST_SET="php_all_32"
-./jenkins/build_and_run_docker.sh
diff --git a/jenkins/docker/Dockerfile b/jenkins/docker/Dockerfile
deleted file mode 100644
index 3a279e66..00000000
--- a/jenkins/docker/Dockerfile
+++ /dev/null
@@ -1,244 +0,0 @@
-# This Dockerfile specifies the recipe for creating an image for the tests
-# to run in.
-#
-# We install as many test dependencies here as we can, because these setup
-# steps can be cached. They do *not* run every time we run the build.
-# The Docker image is only rebuilt when the Dockerfile (ie. this file)
-# changes.
-
-# Base Dockerfile for gRPC dev images
-FROM debian:latest
-
-# Apt source for old Python versions.
-RUN echo 'deb http://ppa.launchpad.net/fkrull/deadsnakes/ubuntu trusty main' > /etc/apt/sources.list.d/deadsnakes.list && \
- apt-key adv --keyserver keyserver.ubuntu.com --recv-keys DB82666C
-
-# Apt source for Oracle Java.
-RUN echo 'deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main' > /etc/apt/sources.list.d/webupd8team-java-trusty.list && \
- apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EEA14886 && \
- echo "oracle-java7-installer shared/accepted-oracle-license-v1-1 select true" | debconf-set-selections
-
-# Apt source for Mono
-RUN echo "deb http://download.mono-project.com/repo/debian wheezy main" | tee /etc/apt/sources.list.d/mono-xamarin.list && \
- echo "deb http://download.mono-project.com/repo/debian wheezy-libjpeg62-compat main" | tee -a /etc/apt/sources.list.d/mono-xamarin.list && \
- apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
-
-# Apt source for php
-RUN echo "deb http://ppa.launchpad.net/ondrej/php/ubuntu trusty main" | tee /etc/apt/sources.list.d/various-php.list && \
- apt-key adv --keyserver keyserver.ubuntu.com --recv-keys F4FCBB07
-
-# Install dotnet SDK based on https://www.microsoft.com/net/core#debian
-# (Ubuntu instructions need apt to support https)
-RUN apt-get update && apt-get install -y --force-yes curl libunwind8 gettext && \
- curl -sSL -o dotnet.tar.gz https://go.microsoft.com/fwlink/?LinkID=847105 && \
- mkdir -p /opt/dotnet && tar zxf dotnet.tar.gz -C /opt/dotnet && \
- ln -s /opt/dotnet/dotnet /usr/local/bin
-
-# Install dependencies. We start with the basic ones require to build protoc
-# and the C++ build
-RUN apt-get clean && apt-get update && apt-get install -y --force-yes \
- autoconf \
- autotools-dev \
- build-essential \
- bzip2 \
- ccache \
- curl \
- gcc \
- git \
- libc6 \
- libc6-dbg \
- libc6-dev \
- libgtest-dev \
- libtool \
- make \
- parallel \
- time \
- wget \
- # -- For csharp --
- mono-devel \
- referenceassemblies-pcl \
- nunit \
- # -- For all Java builds -- \
- maven \
- # -- For java_jdk6 -- \
- # oops! not in jessie. too old? openjdk-6-jdk \
- # -- For java_jdk7 -- \
- openjdk-7-jdk \
- # -- For java_oracle7 -- \
- oracle-java7-installer \
- # -- For python / python_cpp -- \
- python-setuptools \
- python-pip \
- python-dev \
- python2.6-dev \
- python3.3-dev \
- python3.4-dev \
- # -- For Ruby --
- ruby \
- # -- For C++ benchmarks --
- cmake \
- # -- For PHP --
- php5.6 \
- php5.6-dev \
- php5.6-xml \
- php7.0 \
- php7.0-dev \
- php7.0-xml \
- phpunit \
- valgrind \
- libxml2-dev \
- && apt-get clean
-
-##################
-# C# dependencies
-
-RUN wget www.nuget.org/NuGet.exe -O /usr/local/bin/nuget.exe
-
-##################
-# Python dependencies
-
-# These packages exist in apt-get, but their versions are too old, so we have
-# to get updates from pip.
-
-RUN pip install pip --upgrade
-RUN pip install virtualenv tox yattag
-
-##################
-# Ruby dependencies
-
-# Install rvm
-RUN gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
-RUN \curl -sSL https://get.rvm.io | bash -s stable
-
-# Install Ruby 2.1, Ruby 2.2 and JRuby 1.7
-RUN /bin/bash -l -c "rvm install ruby-2.1"
-RUN /bin/bash -l -c "rvm install ruby-2.2"
-RUN /bin/bash -l -c "rvm install jruby-1.7"
-RUN /bin/bash -l -c "echo 'gem: --no-ri --no-rdoc' > ~/.gemrc"
-RUN /bin/bash -l -c "echo 'export PATH=/usr/local/rvm/bin:$PATH' >> ~/.bashrc"
-RUN /bin/bash -l -c "gem install bundler --no-ri --no-rdoc"
-
-##################
-# Java dependencies
-
-# This step requires compiling protoc. :(
-
-ENV MAVEN_REPO /var/maven_local_repository
-ENV MVN mvn --batch-mode
-
-RUN cd /tmp && \
- git clone https://github.com/google/protobuf.git && \
- cd protobuf && \
- git reset --hard 129a6e2aca95dcfb6c3e717d7b9cca1f104fde39 && \
- ./autogen.sh && \
- ./configure && \
- make -j4 && \
- cd java && \
- $MVN install dependency:go-offline -Dmaven.repo.local=$MAVEN_REPO && \
- cd ../javanano && \
- $MVN install dependency:go-offline -Dmaven.repo.local=$MAVEN_REPO
-
-##################
-# PHP dependencies.
-RUN wget http://am1.php.net/get/php-5.5.38.tar.bz2/from/this/mirror
-RUN mv mirror php-5.5.38.tar.bz2
-RUN tar -xvf php-5.5.38.tar.bz2
-RUN cd php-5.5.38 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-5.5-zts && \
- make && make install && cd ..
-RUN cd php-5.5.38 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-5.5 && \
- make && make install && cd ..
-
-RUN wget http://am1.php.net/get/php-5.6.30.tar.bz2/from/this/mirror
-RUN mv mirror php-5.6.30.tar.bz2
-RUN tar -xvf php-5.6.30.tar.bz2
-RUN cd php-5.6.30 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-5.6-zts && \
- make && make install && cd ..
-RUN cd php-5.6.30 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-5.6 && \
- make && make install && cd ..
-
-RUN wget http://am1.php.net/get/php-7.0.18.tar.bz2/from/this/mirror
-RUN mv mirror php-7.0.18.tar.bz2
-RUN tar -xvf php-7.0.18.tar.bz2
-RUN cd php-7.0.18 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-7.0-zts && \
- make && make install && cd ..
-RUN cd php-7.0.18 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-7.0 && \
- make && make install && cd ..
-
-RUN wget http://am1.php.net/get/php-7.1.4.tar.bz2/from/this/mirror
-RUN mv mirror php-7.1.4.tar.bz2
-RUN tar -xvf php-7.1.4.tar.bz2
-RUN cd php-7.1.4 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-7.1-zts && \
- make && make install && cd ..
-RUN cd php-7.1.4 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-7.1 && \
- make && make install && cd ..
-
-RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
-RUN php composer-setup.php
-RUN mv composer.phar /usr/bin/composer
-RUN php -r "unlink('composer-setup.php');"
-RUN composer config -g -- disable-tls true
-RUN composer config -g -- secure-http false
-RUN cd /tmp && \
- rm -rf protobuf && \
- git clone https://github.com/google/protobuf.git && \
- cd protobuf && \
- git reset --hard 49b44bff2b6257a119f9c6a342d6151c736586b8 && \
- cd php && \
- ln -sfn /usr/local/php-5.5/bin/php /usr/bin/php && \
- ln -sfn /usr/local/php-5.5/bin/php-config /usr/bin/php-config && \
- ln -sfn /usr/local/php-5.5/bin/phpize /usr/bin/phpize && \
- composer install && \
- mv vendor /usr/local/vendor-5.5 && \
- ln -sfn /usr/local/php-5.6/bin/php /usr/bin/php && \
- ln -sfn /usr/local/php-5.6/bin/php-config /usr/bin/php-config && \
- ln -sfn /usr/local/php-5.6/bin/phpize /usr/bin/phpize && \
- composer install && \
- mv vendor /usr/local/vendor-5.6 && \
- ln -sfn /usr/local/php-7.0/bin/php /usr/bin/php && \
- ln -sfn /usr/local/php-7.0/bin/php-config /usr/bin/php-config && \
- ln -sfn /usr/local/php-7.0/bin/phpize /usr/bin/phpize && \
- composer install && \
- mv vendor /usr/local/vendor-7.0 && \
- ln -sfn /usr/local/php-7.1/bin/php /usr/bin/php && \
- ln -sfn /usr/local/php-7.1/bin/php-config /usr/bin/php-config && \
- ln -sfn /usr/local/php-7.1/bin/phpize /usr/bin/phpize && \
- composer install && \
- mv vendor /usr/local/vendor-7.1
-
-##################
-# Go dependencies.
-RUN apt-get install -y \
- # -- For go -- \
- golang
-
-##################
-# Javascript dependencies.
-RUN apt-get install -y \
- # -- For javascript -- \
- npm
-
-##################
-# Python 3.5 3.6 dependencies.
-RUN apt-get clean && apt-get update && apt-get install -y --force-yes \
- python3.5-dev \
- python3.6-dev \
- && apt-get clean
-
-# On Debian/Ubuntu, nodejs binary is named 'nodejs' because the name 'node'
-# is taken by another legacy binary. We don't have that legacy binary and
-# npm expects the binary to be named 'node', so we just create a symbol
-# link here.
-RUN ln -s `which nodejs` /usr/bin/node
-
-##################
-# Prepare ccache
-
-RUN ln -s /usr/bin/ccache /usr/local/bin/gcc
-RUN ln -s /usr/bin/ccache /usr/local/bin/g++
-RUN ln -s /usr/bin/ccache /usr/local/bin/cc
-RUN ln -s /usr/bin/ccache /usr/local/bin/c++
-RUN ln -s /usr/bin/ccache /usr/local/bin/clang
-RUN ln -s /usr/bin/ccache /usr/local/bin/clang++
-
-# Define the default command.
-CMD ["bash"]
diff --git a/jenkins/docker32/Dockerfile b/jenkins/docker32/Dockerfile
deleted file mode 100644
index 1278889f..00000000
--- a/jenkins/docker32/Dockerfile
+++ /dev/null
@@ -1,143 +0,0 @@
-# This Dockerfile specifies the recipe for creating an image for the tests
-# to run in.
-#
-# We install as many test dependencies here as we can, because these setup
-# steps can be cached. They do *not* run every time we run the build.
-# The Docker image is only rebuilt when the Dockerfile (ie. this file)
-# changes.
-
-# Base Dockerfile for gRPC dev images
-FROM 32bit/debian:latest
-
-# Apt source for php
-RUN echo "deb http://ppa.launchpad.net/ondrej/php/ubuntu trusty main" | tee /etc/apt/sources.list.d/various-php.list && \
- apt-key adv --keyserver keyserver.ubuntu.com --recv-keys F4FCBB07
-
-# Install dependencies. We start with the basic ones require to build protoc
-# and the C++ build
-RUN apt-get clean && apt-get update && apt-get install -y --force-yes \
- autoconf \
- autotools-dev \
- build-essential \
- bzip2 \
- ccache \
- curl \
- gcc \
- git \
- libc6 \
- libc6-dbg \
- libc6-dev \
- libgtest-dev \
- libtool \
- make \
- parallel \
- time \
- wget \
- unzip \
- # -- For python --
- python-setuptools \
- python-pip \
- python-dev \
- # -- For C++ benchmarks --
- cmake \
- # -- For PHP --
- php5.5 \
- php5.5-dev \
- php5.5-xml \
- php5.6 \
- php5.6-dev \
- php5.6-xml \
- php7.0 \
- php7.0-dev \
- php7.0-xml \
- phpunit \
- valgrind \
- libxml2-dev \
- && apt-get clean
-
-##################
-# PHP dependencies.
-RUN wget http://am1.php.net/get/php-5.5.38.tar.bz2/from/this/mirror
-RUN mv mirror php-5.5.38.tar.bz2
-RUN tar -xvf php-5.5.38.tar.bz2
-RUN cd php-5.5.38 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-5.5-zts && \
- make && make install && make clean && cd ..
-RUN cd php-5.5.38 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-5.5 && \
- make && make install && make clean && cd ..
-
-RUN wget http://am1.php.net/get/php-5.6.30.tar.bz2/from/this/mirror
-RUN mv mirror php-5.6.30.tar.bz2
-RUN tar -xvf php-5.6.30.tar.bz2
-RUN cd php-5.6.30 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-5.6-zts && \
- make && make install && cd ..
-RUN cd php-5.6.30 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-5.6 && \
- make && make install && cd ..
-
-RUN wget http://am1.php.net/get/php-7.0.18.tar.bz2/from/this/mirror
-RUN mv mirror php-7.0.18.tar.bz2
-RUN tar -xvf php-7.0.18.tar.bz2
-RUN cd php-7.0.18 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-7.0-zts && \
- make && make install && cd ..
-RUN cd php-7.0.18 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-7.0 && \
- make && make install && cd ..
-
-RUN wget http://am1.php.net/get/php-7.1.4.tar.bz2/from/this/mirror
-RUN mv mirror php-7.1.4.tar.bz2
-RUN tar -xvf php-7.1.4.tar.bz2
-RUN cd php-7.1.4 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-7.1-zts && \
- make && make install && cd ..
-RUN cd php-7.1.4 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-7.1 && \
- make && make install && cd ..
-
-RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
-RUN php composer-setup.php
-RUN mv composer.phar /usr/bin/composer
-RUN php -r "unlink('composer-setup.php');"
-RUN composer config -g -- disable-tls true
-RUN composer config -g -- secure-http false
-RUN cd /tmp && \
- git clone https://github.com/google/protobuf.git && \
- cd protobuf/php && \
- git reset --hard 49b44bff2b6257a119f9c6a342d6151c736586b8 && \
- ln -sfn /usr/local/php-5.5/bin/php /usr/bin/php && \
- ln -sfn /usr/local/php-5.5/bin/php-config /usr/bin/php-config && \
- ln -sfn /usr/local/php-5.5/bin/phpize /usr/bin/phpize && \
- composer install && \
- mv vendor /usr/local/vendor-5.5 && \
- ln -sfn /usr/local/php-5.6/bin/php /usr/bin/php && \
- ln -sfn /usr/local/php-5.6/bin/php-config /usr/bin/php-config && \
- ln -sfn /usr/local/php-5.6/bin/phpize /usr/bin/phpize && \
- composer install && \
- mv vendor /usr/local/vendor-5.6 && \
- ln -sfn /usr/local/php-7.0/bin/php /usr/bin/php && \
- ln -sfn /usr/local/php-7.0/bin/php-config /usr/bin/php-config && \
- ln -sfn /usr/local/php-7.0/bin/phpize /usr/bin/phpize && \
- composer install && \
- mv vendor /usr/local/vendor-7.0 && \
- ln -sfn /usr/local/php-7.1/bin/php /usr/bin/php && \
- ln -sfn /usr/local/php-7.1/bin/php-config /usr/bin/php-config && \
- ln -sfn /usr/local/php-7.1/bin/phpize /usr/bin/phpize && \
- composer install && \
- mv vendor /usr/local/vendor-7.1
-
-##################
-# Python dependencies
-
-# These packages exist in apt-get, but their versions are too old, so we have
-# to get updates from pip.
-
-RUN pip install pip --upgrade
-RUN pip install virtualenv tox yattag
-
-##################
-# Prepare ccache
-
-RUN ln -s /usr/bin/ccache /usr/local/bin/gcc
-RUN ln -s /usr/bin/ccache /usr/local/bin/g++
-RUN ln -s /usr/bin/ccache /usr/local/bin/cc
-RUN ln -s /usr/bin/ccache /usr/local/bin/c++
-RUN ln -s /usr/bin/ccache /usr/local/bin/clang
-RUN ln -s /usr/bin/ccache /usr/local/bin/clang++
-
-# Define the default command.
-CMD ["bash"]
diff --git a/jenkins/make_test_output.py b/jenkins/make_test_output.py
deleted file mode 100644
index 98536853..00000000
--- a/jenkins/make_test_output.py
+++ /dev/null
@@ -1,94 +0,0 @@
-"""Gathers output from test runs and create an XML file in JUnit format.
-
-The output files from the individual tests have been written in a directory
-structure like:
-
- $DIR/joblog (output from "parallel --joblog joblog")
- $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
- etc.
-
-This script bundles them into a single output XML file so Jenkins can show
-detailed test results. It runs as the last step before the Jenkins build
-finishes.
-"""
-
-import os
-import sys
-from yattag import Doc
-from collections import defaultdict
-
-
-def readtests(basedir):
- tests = defaultdict(dict)
-
- # Sample input (note: separators are tabs).
- #
- # Seq Host Starttime Runtime Send Receive Exitval Signal Command
- # 1 : 1456263838.313 0.005 0 0 0 0 echo A
- with open(basedir + "/joblog") as jobs:
- firstline = next(jobs)
- for line in jobs:
- values = line.split("\t")
-
- name = values[8].split()[-1]
- test = tests[name]
- test["name"] = name
- test["time"] = values[3]
-
- exitval = values[6]
- if int(exitval):
- # We don't have a more specific message. User should look at stderr.
- test["failure"] = "TEST FAILURE"
- else:
- test["failure"] = False
-
- for testname in os.listdir(basedir + "/logs/1"):
- test = tests[testname]
-
- with open(basedir + "/logs/1/" + testname + "/stdout") as f:
- test["stdout"] = f.read()
-
- with open(basedir + "/logs/1/" + testname + "/stderr") as f:
- test["stderr"] = f.read()
-
- # The cpp test is special since it doesn't run under parallel so doesn't show
- # up in the job log.
- tests["cpp"]["name"] = "cpp"
-
- with open(basedir + '/logs/1/cpp/build_time', 'r') as f:
- tests["cpp"]["time"] = f.read().strip()
- tests["cpp"]["failure"] = False
-
- ret = tests.values()
- ret.sort(key=lambda x: x["name"])
-
- return ret
-
-
-def genxml(tests):
- doc, tag, text = Doc().tagtext()
-
- with tag("testsuites"):
- with tag("testsuite", name="Protobuf Tests"):
- for test in tests:
- with tag("testcase", name=test["name"], classname=test["name"],
- time=test["time"]):
- with tag("system-out"):
- text(test["stdout"])
- with tag("system-err"):
- text(test["stderr"])
- if test["failure"]:
- with tag("failure"):
- text(test["failure"])
-
- return doc.getvalue()
-
-
-sys.stderr.write("make_test_output.py: writing XML from directory: " +
- sys.argv[1] + "\n")
-print(genxml(readtests(sys.argv[1])))
diff --git a/jenkins/pull_request_in_docker.sh b/jenkins/pull_request_in_docker.sh
deleted file mode 100755
index 10daf0a5..00000000
--- a/jenkins/pull_request_in_docker.sh
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/bin/bash
-#
-# This is the script that runs inside Docker, once the image has been built,
-# to execute all tests for the "pull request" project.
-
-WORKSPACE_BASE=`pwd`
-MY_DIR="$(dirname "$0")"
-TEST_SCRIPT=$MY_DIR/../tests.sh
-BUILD_DIR=/tmp/protobuf
-
-set -e # exit immediately on error
-set -x # display all commands
-
-# The protobuf repository is mounted into our Docker image, but read-only.
-# We clone into a directory inside Docker (this is faster than cp).
-rm -rf $BUILD_DIR
-mkdir -p $BUILD_DIR
-cd $BUILD_DIR
-git clone /var/local/jenkins/protobuf
-cd protobuf
-
-# 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 \
- || true # Process test results even if tests fail.
-
-cat $OUTPUT_DIR/joblog
-
-# The directory that is copied from Docker back into the Jenkins workspace.
-COPY_FROM_DOCKER=/var/local/git/protobuf/testoutput
-mkdir -p $COPY_FROM_DOCKER
-TESTOUTPUT_XML_FILE=$COPY_FROM_DOCKER/testresults.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
diff --git a/js/README.md b/js/README.md
index ef0d4b19..d8edca37 100644
--- a/js/README.md
+++ b/js/README.md
@@ -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 75a8a52c..21c5889c 100644
--- a/js/binary/constants.js
+++ b/js/binary/constants.js
@@ -60,14 +60,25 @@ goog.forwardDeclare('jsproto.BinaryExtension');
/**
- * Base interface class for all const messages. Does __not__ define any
- * methods, as doing so on a widely-used interface defeats dead-code
- * elimination.
+ * Base interface class for all const messages.
* @interface
*/
jspb.ConstBinaryMessage = function() {};
+/**
+ * Generate a debug string for this proto that is in proto2 text format.
+ * @return {string} The debug string.
+ */
+jspb.ConstBinaryMessage.prototype.toDebugString;
+/**
+ * Helper to generate a debug string for this proto at some indent level. The
+ * first line is not indented.
+ * @param {number} indentLevel The number of spaces by which to indent lines.
+ * @return {string} The debug string.
+ * @protected
+ */
+jspb.ConstBinaryMessage.prototype.toDebugStringInternal;
/**
* Base interface class for all messages. Does __not__ define any methods, as
@@ -97,6 +108,7 @@ jspb.ScalarFieldType;
* A repeated field in jspb is an array of scalars, blobs, or messages.
* @typedef {!Array<jspb.ScalarFieldType>|
!Array<!Uint8Array>|
+ !Array<!jspb.ConstBinaryMessage>|
!Array<!jspb.BinaryMessage>}
*/
jspb.RepeatedFieldType;
@@ -108,6 +120,7 @@ jspb.RepeatedFieldType;
* @typedef {jspb.ScalarFieldType|
jspb.RepeatedFieldType|
!Uint8Array|
+ !jspb.ConstBinaryMessage|
!jspb.BinaryMessage|
!jsproto.BinaryExtension}
*/
diff --git a/js/binary/decoder.js b/js/binary/decoder.js
index d0c0bc17..e33bf1be 100644
--- a/js/binary/decoder.js
+++ b/js/binary/decoder.js
@@ -986,7 +986,7 @@ jspb.BinaryDecoder.prototype.readString = function(length) {
codeUnits.push(high, low);
}
- // Avoid exceeding the maximum stack size when calling {@code apply}.
+ // Avoid exceeding the maximum stack size when calling `apply`.
if (codeUnits.length >= 8192) {
result += String.fromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
diff --git a/js/binary/utils.js b/js/binary/utils.js
index 87570ff8..55a9ccd4 100644
--- a/js/binary/utils.js
+++ b/js/binary/utils.js
@@ -971,6 +971,10 @@ jspb.utils.byteSourceToUint8Array = function(data) {
return /** @type {!Uint8Array} */(new Uint8Array(data));
}
+ if (data.constructor === Buffer) {
+ return /** @type {!Uint8Array} */(new Uint8Array(data));
+ }
+
if (data.constructor === Array) {
data = /** @type {!Array<number>} */(data);
return /** @type {!Uint8Array} */(new Uint8Array(data));
diff --git a/js/binary/writer.js b/js/binary/writer.js
index 8a018058..287d29c3 100644
--- a/js/binary/writer.js
+++ b/js/binary/writer.js
@@ -236,10 +236,12 @@ jspb.BinaryWriter.prototype.getResultBuffer = function() {
/**
* Converts the encoded data into a base64-encoded string.
+ * @param {boolean=} opt_webSafe True indicates we should use a websafe
+ * alphabet, which does not require escaping for use in URLs.
* @return {string}
*/
-jspb.BinaryWriter.prototype.getResultBase64String = function() {
- return goog.crypt.base64.encodeByteArray(this.getResultBuffer());
+jspb.BinaryWriter.prototype.getResultBase64String = function(opt_webSafe) {
+ return goog.crypt.base64.encodeByteArray(this.getResultBuffer(), opt_webSafe);
};
diff --git a/js/binary/writer_test.js b/js/binary/writer_test.js
index 118eecfc..8a9a1bb0 100644
--- a/js/binary/writer_test.js
+++ b/js/binary/writer_test.js
@@ -118,4 +118,16 @@ describe('binaryWriterTest', function() {
var buffer = writer.getResultBuffer();
assertEquals(expected, goog.crypt.byteArrayToHex(buffer));
});
+
+
+ /**
+ * Tests websafe encodings for base64 strings.
+ */
+ it('testWebSafeOption', function() {
+ var writer = new jspb.BinaryWriter();
+ writer.writeBytes(1, new Uint8Array([127]));
+ assertEquals('CgF/', writer.getResultBase64String());
+ assertEquals('CgF/', writer.getResultBase64String(false));
+ assertEquals('CgF_', writer.getResultBase64String(true));
+ });
});
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nano.proto b/js/commonjs/strict_test.js
index 406ab774..46458c10 100644
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nano.proto
+++ b/js/commonjs/strict_test.js
@@ -1,5 +1,5 @@
// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
+// Copyright 2016 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
@@ -28,36 +28,40 @@
// (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: maxtroy@google.com (Max Cai)
+// Test suite is written using Jasmine -- see http://jasmine.github.io/
-package protobuf_unittest_import;
-import "google/protobuf/nano/unittest_import_nano.proto";
-option java_package = "com.google.protobuf";
-option java_multiple_files = true;
+var googleProtobuf = require('google-protobuf');
+var asserts = require('closure_asserts_commonjs');
+var global = Function('return this')();
-enum FileScopeEnum {
- ONE = 1;
- TWO = 2;
-}
+// Bring asserts into the global namespace.
+googleProtobuf.object.extend(global, asserts);
-message FileScopeEnumRefNano {
- optional FileScopeEnum enum_field = 1;
-}
+var test9_pb = require('./test9_pb');
+var test10_pb = require('./test10_pb');
-message MessageScopeEnumRefNano {
- enum MessageScopeEnum {
- ONE = 1;
- TWO = 2;
- }
- optional MessageScopeEnum enum_field = 1;
-}
+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());
+ });
-message MultipleImportingNonMultipleNano1 {
- optional ImportMessageNano field = 1;
-}
+ it('testGlobalScopePollution', function() {
+ assertObjectEquals(global.jspb.exttest, undefined);
+ });
-message MultipleImportingNonMultipleNano2 {
- optional MultipleImportingNonMultipleNano1 nano1 = 1;
-}
+ 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/debug.js b/js/debug.js
index 4ae3c2a2..ba51bbe0 100644
--- a/js/debug.js
+++ b/js/debug.js
@@ -42,7 +42,7 @@ goog.require('jspb.Message');
/**
* Turns a proto into a human readable object that can i.e. be written to the
- * console: {@code console.log(jspb.debug.dump(myProto))}.
+ * console: `console.log(jspb.debug.dump(myProto))`.
* This function makes a best effort and may not work in all cases. It will not
* work in obfuscated and or optimized code.
* Use this in environments where {@see jspb.Message.prototype.toObject} is
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 d423499f..2fb14837 100644
--- a/js/map.js
+++ b/js/map.js
@@ -48,9 +48,9 @@ goog.forwardDeclare('jspb.BinaryWriter');
*
* @template K, V
*
- * @param {!Array<!Array<!Object>>} arr
+ * @param {!Array<!Array<?>>} arr
*
- * @param {?function(new:V)|function(new:V,?)=} opt_valueCtor
+ * @param {?function(new:V, ?=)=} opt_valueCtor
* The constructor for type V, if type V is a message type.
*
* @constructor
@@ -118,7 +118,7 @@ jspb.Map.prototype.toArray = function() {
strKeys.sort();
for (var i = 0; i < strKeys.length; i++) {
var entry = this.map_[strKeys[i]];
- var valueWrapper = /** @type {!Object} */ (entry.valueWrapper);
+ var valueWrapper = /** @type {?jspb.Message} */ (entry.valueWrapper);
if (valueWrapper) {
valueWrapper.toArray();
}
@@ -165,7 +165,7 @@ jspb.Map.prototype.toObject = function(includeInstance, valueToObject) {
*
* @template K, V
* @param {!Array<!Array<!Object>>} entries
- * @param {!function(new:V)|function(new:V,?)} valueCtor
+ * @param {!function(new:V,?=)} valueCtor
* The constructor for type V.
* @param {!function(!Object):V} valueFromObject
* The fromObject function for type V.
@@ -432,7 +432,8 @@ jspb.Map.prototype.serializeBinary = function(
valueWriterFn.call(writer, 2, this.wrapEntry_(entry),
opt_valueWriterCallback);
} else {
- valueWriterFn.call(writer, 2, entry.value);
+ /** @type {function(this:jspb.BinaryWriter,number,?)} */ (valueWriterFn)
+ .call(writer, 2, entry.value);
}
writer.endSubMessage();
}
@@ -442,7 +443,8 @@ jspb.Map.prototype.serializeBinary = function(
/**
* Read one key/value message from the given BinaryReader. Compatible as the
* `reader` callback parameter to jspb.BinaryReader.readMessage, to be called
- * when a key/value pair submessage is encountered.
+ * when a key/value pair submessage is encountered. If the Key is undefined,
+ * we should default it to 0.
* @template K, V
* @param {!jspb.Map} map
* @param {!jspb.BinaryReader} reader
@@ -456,12 +458,17 @@ jspb.Map.prototype.serializeBinary = function(
* readMessage, in which case the second callback arg form is used.
*
* @param {?function(V,!jspb.BinaryReader)=} opt_valueReaderCallback
- * The BinaryReader parsing callback for type V, if V is a message type.
+ * The BinaryReader parsing callback for type V, if V is a message type
+ *
+ * @param {K=} opt_defaultKey
+ * The default value for the type of map keys. Accepting map
+ * entries with unset keys is required for maps to be backwards compatible
+ * with the repeated message representation described here: goo.gl/zuoLAC
*
*/
jspb.Map.deserializeBinary = function(map, reader, keyReaderFn, valueReaderFn,
- opt_valueReaderCallback) {
- var key = undefined;
+ opt_valueReaderCallback, opt_defaultKey) {
+ var key = opt_defaultKey;
var value = undefined;
while (reader.nextField()) {
@@ -469,16 +476,20 @@ jspb.Map.deserializeBinary = function(map, reader, keyReaderFn, valueReaderFn,
break;
}
var field = reader.getFieldNumber();
+
if (field == 1) {
// Key.
key = keyReaderFn.call(reader);
} else if (field == 2) {
// Value.
if (map.valueCtor_) {
+ goog.asserts.assert(opt_valueReaderCallback);
value = new map.valueCtor_();
valueReaderFn.call(reader, value, opt_valueReaderCallback);
} else {
- value = valueReaderFn.call(reader);
+ value =
+ (/** @type {function(this:jspb.BinaryReader):?} */ (valueReaderFn))
+ .call(reader);
}
}
}
diff --git a/js/maps_test.js b/js/maps_test.js
index e8dd2f21..e496f446 100755
--- a/js/maps_test.js
+++ b/js/maps_test.js
@@ -35,6 +35,11 @@ goog.require('goog.userAgent');
goog.require('proto.jspb.test.MapValueEnum');
goog.require('proto.jspb.test.MapValueMessage');
goog.require('proto.jspb.test.TestMapFields');
+goog.require('proto.jspb.test.TestMapFieldsOptionalKeys');
+goog.require('proto.jspb.test.MapEntryOptionalKeysStringKey');
+goog.require('proto.jspb.test.MapEntryOptionalKeysInt32Key');
+goog.require('proto.jspb.test.MapEntryOptionalKeysInt64Key');
+goog.require('proto.jspb.test.MapEntryOptionalKeysBoolKey');
// CommonJS-LoadFromFile: test_pb proto.jspb.test
goog.require('proto.jspb.test.MapValueMessageNoBinary');
@@ -76,7 +81,7 @@ function toArray(iter) {
* Helper: generate test methods for this TestMapFields class.
* @param {?} msgInfo
* @param {?} submessageCtor
- * @param {!string} suffix
+ * @param {string} suffix
*/
function makeTests(msgInfo, submessageCtor, suffix) {
/**
@@ -260,6 +265,39 @@ function makeTests(msgInfo, submessageCtor, suffix) {
var decoded = msgInfo.deserializeBinary(serialized);
checkMapFields(decoded);
});
+ /**
+ * Tests deserialization of undefined map keys go to default values in binary format.
+ */
+ it('testMapDeserializationForUndefinedKeys', function() {
+ var testMessageOptionalKeys = new proto.jspb.test.TestMapFieldsOptionalKeys();
+ var mapEntryStringKey = new proto.jspb.test.MapEntryOptionalKeysStringKey();
+ mapEntryStringKey.setValue("a");
+ testMessageOptionalKeys.setMapStringString(mapEntryStringKey);
+ var mapEntryInt32Key = new proto.jspb.test.MapEntryOptionalKeysInt32Key();
+ mapEntryInt32Key.setValue("b");
+ testMessageOptionalKeys.setMapInt32String(mapEntryInt32Key);
+ var mapEntryInt64Key = new proto.jspb.test.MapEntryOptionalKeysInt64Key();
+ mapEntryInt64Key.setValue("c");
+ testMessageOptionalKeys.setMapInt64String(mapEntryInt64Key);
+ var mapEntryBoolKey = new proto.jspb.test.MapEntryOptionalKeysBoolKey();
+ mapEntryBoolKey.setValue("d");
+ testMessageOptionalKeys.setMapBoolString(mapEntryBoolKey);
+ var deserializedMessage = msgInfo.deserializeBinary(
+ testMessageOptionalKeys.serializeBinary()
+ );
+ checkMapEquals(deserializedMessage.getMapStringStringMap(), [
+ ['', 'a']
+ ]);
+ checkMapEquals(deserializedMessage.getMapInt32StringMap(), [
+ [0, 'b']
+ ]);
+ checkMapEquals(deserializedMessage.getMapInt64StringMap(), [
+ [0, 'c']
+ ]);
+ checkMapEquals(deserializedMessage.getMapBoolStringMap(), [
+ [false, 'd']
+ ]);
+ });
}
diff --git a/js/message.js b/js/message.js
index 8f68cbb4..86d18295 100644
--- a/js/message.js
+++ b/js/message.js
@@ -216,17 +216,6 @@ goog.define('jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS', true);
/**
- * @define {boolean} Turning on this flag does NOT change the behavior of JSPB
- * and only affects private internal state. It may, however, break some
- * tests that use naive deeply-equals algorithms, because using a proto
- * mutates its internal state.
- * Projects are advised to turn this flag always on.
- */
-goog.define('jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS', true);
-// TODO(b/19419436): Delete this flag.
-
-
-/**
* Does this JavaScript environment support Uint8Aray typed arrays?
* @type {boolean}
* @private
@@ -369,7 +358,7 @@ jspb.Message.getFieldNumber_ = function(msg, index) {
*/
jspb.Message.initialize = function(
msg, data, messageId, suggestedPivot, repeatedFields, opt_oneofFields) {
- msg.wrappers_ = jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS ? null : {};
+ msg.wrappers_ = null;
if (!data) {
data = messageId ? [messageId] : [];
}
@@ -394,17 +383,12 @@ jspb.Message.initialize = function(
var fieldNumber = repeatedFields[i];
if (fieldNumber < msg.pivot_) {
var index = jspb.Message.getIndex_(msg, fieldNumber);
- msg.array[index] = msg.array[index] ||
- (jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS ?
- jspb.Message.EMPTY_LIST_SENTINEL_ :
- []);
+ msg.array[index] =
+ msg.array[index] || jspb.Message.EMPTY_LIST_SENTINEL_;
} else {
jspb.Message.maybeInitEmptyExtensionObject_(msg);
- msg.extensionObject_[fieldNumber] =
- msg.extensionObject_[fieldNumber] ||
- (jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS ?
- jspb.Message.EMPTY_LIST_SENTINEL_ :
- []);
+ msg.extensionObject_[fieldNumber] = msg.extensionObject_[fieldNumber] ||
+ jspb.Message.EMPTY_LIST_SENTINEL_;
}
}
}
@@ -517,8 +501,7 @@ jspb.Message.toObjectList = function(field, toObjectFn, opt_includeInstance) {
// And not using it here to avoid a function call.
var result = [];
for (var i = 0; i < field.length; i++) {
- result[i] = toObjectFn.call(field[i], opt_includeInstance,
- /** @type {!jspb.Message} */ (field[i]));
+ result[i] = toObjectFn.call(field[i], opt_includeInstance, field[i]);
}
return result;
};
@@ -551,10 +534,11 @@ jspb.Message.toObjectExtension = function(proto, obj, extensions,
} else {
if (fieldInfo.isRepeated) {
obj[name] = jspb.Message.toObjectList(
- /** @type {!Array<jspb.Message>} */ (value),
+ /** @type {!Array<!jspb.Message>} */ (value),
fieldInfo.toObjectFn, opt_includeInstance);
} else {
- obj[name] = fieldInfo.toObjectFn(opt_includeInstance, value);
+ obj[name] = fieldInfo.toObjectFn(
+ opt_includeInstance, /** @type {!jspb.Message} */ (value));
}
}
}
@@ -939,6 +923,17 @@ 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.
@@ -1419,7 +1414,7 @@ jspb.Message.prototype.setExtension = function(fieldInfo, value) {
if (fieldInfo.isMessageType()) {
self.wrappers_[fieldNumber] = value;
self.extensionObject_[fieldNumber] = goog.array.map(
- /** @type {Array<jspb.Message>} */ (value), function(msg) {
+ /** @type {!Array<!jspb.Message>} */ (value), function(msg) {
return msg.toArray();
});
} else {
@@ -1428,7 +1423,8 @@ jspb.Message.prototype.setExtension = function(fieldInfo, value) {
} else {
if (fieldInfo.isMessageType()) {
self.wrappers_[fieldNumber] = value;
- self.extensionObject_[fieldNumber] = value ? value.toArray() : value;
+ self.extensionObject_[fieldNumber] =
+ value ? /** @type {!jspb.Message} */ (value).toArray() : value;
} else {
self.extensionObject_[fieldNumber] = value;
}
@@ -1530,9 +1526,15 @@ jspb.Message.compareFields = function(field1, field2) {
// If the fields are trivially equal, they're equal.
if (field1 == field2) return true;
- // If the fields aren't trivially equal and one of them isn't an object,
- // they can't possibly be equal.
if (!goog.isObject(field1) || !goog.isObject(field2)) {
+ // NaN != NaN so we cover this case.
+ if ((goog.isNumber(field1) && isNaN(field1)) ||
+ (goog.isNumber(field2) && isNaN(field2))) {
+ // One of the fields might be a string 'NaN'.
+ return String(field1) == String(field2);
+ }
+ // If the fields aren't trivially equal and one of them isn't an object,
+ // they can't possibly be equal.
return false;
}
@@ -1555,24 +1557,26 @@ jspb.Message.compareFields = function(field1, field2) {
// If they're both Arrays, compare them element by element except for the
// optional extension objects at the end, which we compare separately.
if (field1.constructor === Array) {
+ var typedField1 = /** @type {!Array<?>} */ (field1);
+ var typedField2 = /** @type {!Array<?>} */ (field2);
var extension1 = undefined;
var extension2 = undefined;
- var length = Math.max(field1.length, field2.length);
+ var length = Math.max(typedField1.length, typedField2.length);
for (var i = 0; i < length; i++) {
- var val1 = field1[i];
- var val2 = field2[i];
+ var val1 = typedField1[i];
+ var val2 = typedField2[i];
if (val1 && (val1.constructor == Object)) {
goog.asserts.assert(extension1 === undefined);
- goog.asserts.assert(i === field1.length - 1);
+ goog.asserts.assert(i === typedField1.length - 1);
extension1 = val1;
val1 = undefined;
}
if (val2 && (val2.constructor == Object)) {
goog.asserts.assert(extension2 === undefined);
- goog.asserts.assert(i === field2.length - 1);
+ goog.asserts.assert(i === typedField2.length - 1);
extension2 = val2;
val2 = undefined;
}
@@ -1695,8 +1699,13 @@ jspb.Message.clone_ = function(obj) {
var clonedArray = new Array(obj.length);
// Use array iteration where possible because it is faster than for-in.
for (var i = 0; i < obj.length; i++) {
- if ((o = obj[i]) != null) {
- clonedArray[i] = typeof o == 'object' ? jspb.Message.clone_(o) : o;
+ o = obj[i];
+ if (o != null) {
+ // NOTE:redundant null check existing for NTI compatibility.
+ // see b/70515949
+ clonedArray[i] = (typeof o == 'object') ?
+ jspb.Message.clone_(goog.asserts.assert(o)) :
+ o;
}
}
return clonedArray;
@@ -1706,8 +1715,13 @@ jspb.Message.clone_ = function(obj) {
}
var clone = {};
for (var key in obj) {
- if ((o = obj[key]) != null) {
- clone[key] = typeof o == 'object' ? jspb.Message.clone_(o) : o;
+ o = obj[key];
+ if (o != null) {
+ // NOTE:redundant null check existing for NTI compatibility.
+ // see b/70515949
+ clone[key] = (typeof o == 'object') ?
+ jspb.Message.clone_(goog.asserts.assert(o)) :
+ o;
}
}
return clone;
@@ -1723,6 +1737,9 @@ jspb.Message.registerMessageType = function(id, constructor) {
jspb.Message.registry_[id] = constructor;
// This is needed so we can later access messageId directly on the contructor,
// otherwise it is not available due to 'property collapsing' by the compiler.
+ /**
+ * @suppress {strictMissingProperties} messageId is not defined on Function
+ */
constructor.messageId = id;
};
diff --git a/js/message_test.js b/js/message_test.js
index 0acebb75..1be41093 100644
--- a/js/message_test.js
+++ b/js/message_test.js
@@ -418,6 +418,18 @@ describe('Message test suite', function() {
['hi',,, {100: [{200: 'a'}]}], ['hi', {100: [{200: 'a'}]}]));
});
+ it('testEqualsNonFinite', function() {
+ assertTrue(jspb.Message.compareFields(NaN, NaN));
+ assertTrue(jspb.Message.compareFields(NaN, 'NaN'));
+ assertTrue(jspb.Message.compareFields('NaN', NaN));
+ assertTrue(jspb.Message.compareFields(Infinity, Infinity));
+ assertTrue(jspb.Message.compareFields(Infinity, 'Infinity'));
+ assertTrue(jspb.Message.compareFields('-Infinity', -Infinity));
+ assertTrue(jspb.Message.compareFields([NaN], ['NaN']));
+ assertFalse(jspb.Message.compareFields(undefined, NaN));
+ assertFalse(jspb.Message.compareFields(NaN, undefined));
+ });
+
it('testToMap', function() {
var p1 = new proto.jspb.test.Simple1(['k', ['v']]);
var p2 = new proto.jspb.test.Simple1(['k1', ['v1', 'v2']]);
diff --git a/js/package.json b/js/package.json
index 3c1c2a42..325f2dcc 100644
--- a/js/package.json
+++ b/js/package.json
@@ -1,6 +1,6 @@
{
"name": "google-protobuf",
- "version": "3.5.1",
+ "version": "3.6.0",
"description": "Protocol Buffers for JavaScript",
"main": "google-protobuf.js",
"files": [
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_single_nano.proto b/js/test10.proto
index 7de30c87..9fa5256c 100644
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_single_nano.proto
+++ b/js/test10.proto
@@ -28,11 +28,12 @@
// (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: maxtroy@google.com (Max Cai)
+syntax = "proto3";
-package protobuf_unittest_import;
+package jspb.exttest.strict.ten;
-option java_package = "com.google.protobuf";
+import "test9.proto";
-message SingleMessageNano {
+message Simple10 {
+ jspb.exttest.strict.nine.Simple9 a = 1;
}
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nameclash_nano.proto b/js/test9.proto
index b31c4399..9f680852 100644
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nameclash_nano.proto
+++ b/js/test9.proto
@@ -28,14 +28,12 @@
// (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: maxtroy@google.com (Max Cai)
+syntax = "proto2";
-package protobuf_unittest_import;
+package jspb.exttest.strict.nine;
-option java_package = "com.google.protobuf";
-option java_outer_classname = "MultipleNameClashNano";
-option java_multiple_files = true;
-
-message MultipleNameClashNano {
- optional int32 field = 1;
+message Simple9 {
+ required string a_string = 1;
+ repeated string a_repeated_string = 2;
+ optional bool a_boolean = 3;
}
diff --git a/js/testbinary.proto b/js/testbinary.proto
index 116f17fb..ed5bdfc6 100644
--- a/js/testbinary.proto
+++ b/js/testbinary.proto
@@ -201,6 +201,38 @@ message TestMapFields {
map<string, TestMapFields> map_string_testmapfields = 12;
}
+// These proto are 'mock map' entries to test the above map deserializing with
+// undefined keys. Make sure TestMapFieldsOptionalKeys is written to be
+// deserialized by TestMapFields
+message MapEntryOptionalKeysStringKey {
+ optional string key = 1;
+ optional string value = 2;
+}
+
+message MapEntryOptionalKeysInt32Key {
+ optional int32 key = 1;
+ optional string value = 2;
+}
+
+message MapEntryOptionalKeysInt64Key {
+ optional int64 key = 1;
+ optional string value = 2;
+}
+
+message MapEntryOptionalKeysBoolKey {
+ optional bool key = 1;
+ optional string value = 2;
+}
+
+message TestMapFieldsOptionalKeys {
+ optional MapEntryOptionalKeysStringKey map_string_string = 1;
+ optional MapEntryOptionalKeysInt32Key map_int32_string= 8;
+ optional MapEntryOptionalKeysInt64Key map_int64_string = 9;
+ optional MapEntryOptionalKeysBoolKey map_bool_string = 10;
+}
+
+// End mock-map entries
+
enum MapValueEnum {
MAP_VALUE_FOO = 0;
MAP_VALUE_BAR = 1;
diff --git a/kokoro/linux/bazel/build.sh b/kokoro/linux/bazel/build.sh
new file mode 100755
index 00000000..d8aea724
--- /dev/null
+++ b/kokoro/linux/bazel/build.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+git submodule update --init --recursive
+bazel test :protobuf_test
diff --git a/kokoro/macos/jruby/continuous.cfg b/kokoro/linux/bazel/continuous.cfg
index f1310fd3..13cfef15 100644
--- a/kokoro/macos/jruby/continuous.cfg
+++ b/kokoro/linux/bazel/continuous.cfg
@@ -1,5 +1,5 @@
# Config file for running tests in Kokoro
# Location of the build script in repository
-build_file: "protobuf/kokoro/macos/jruby/build.sh"
-timeout_mins: 1440
+build_file: "protobuf/kokoro/linux/bazel/build.sh"
+timeout_mins: 15
diff --git a/kokoro/macos/jruby/presubmit.cfg b/kokoro/linux/bazel/presubmit.cfg
index f1310fd3..13cfef15 100644
--- a/kokoro/macos/jruby/presubmit.cfg
+++ b/kokoro/linux/bazel/presubmit.cfg
@@ -1,5 +1,5 @@
# Config file for running tests in Kokoro
# Location of the build script in repository
-build_file: "protobuf/kokoro/macos/jruby/build.sh"
-timeout_mins: 1440
+build_file: "protobuf/kokoro/linux/bazel/build.sh"
+timeout_mins: 15
diff --git a/kokoro/linux/benchmark/build.sh b/kokoro/linux/benchmark/build.sh
new file mode 100755
index 00000000..af5b299e
--- /dev/null
+++ b/kokoro/linux/benchmark/build.sh
@@ -0,0 +1,92 @@
+#!/bin/bash
+#
+# Change to repo root
+cd $(dirname $0)/../../..
+
+export OUTPUT_DIR=testoutput
+oldpwd=`pwd`
+
+# tcmalloc
+if [ ! -f gperftools/.libs/libtcmalloc.so ]; then
+ git clone https://github.com/gperftools/gperftools.git
+ cd gperftools
+ ./autogen.sh
+ ./configure
+ make -j8
+ cd ..
+fi
+
+# download datasets for benchmark
+cd benchmarks
+./download_data.sh
+datasets=`find . -type f -name "dataset.*.pb"`
+cd $oldpwd
+
+# build Python protobuf
+./autogen.sh
+./configure CXXFLAGS="-fPIC -O2"
+make -j8
+cd python
+python setup.py build --cpp_implementation
+pip install . --user
+
+
+# build and run Python benchmark
+cd ../benchmarks
+make python-pure-python-benchmark
+make python-cpp-reflection-benchmark
+make -j8 python-cpp-generated-code-benchmark
+echo "[" > tmp/python_result.json
+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" 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" 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
+
+# build CPP protobuf
+./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
+echo "benchmarking cpp..."
+env LD_PRELOAD="$oldpwd/gperftools/.libs/libtcmalloc.so" ./cpp-benchmark --benchmark_min_time=5.0 --benchmark_out_format=json --benchmark_out="tmp/cpp_result.json" $datasets
+cd $oldpwd
+
+# build go protobuf
+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"
+export PATH="$GOPATH/bin:$PATH"
+go get github.com/golang/protobuf/protoc-gen-go
+
+# build go benchmark
+cd benchmarks
+make go-benchmark
+echo "benchmarking go..."
+./go-benchmark $datasets > tmp/go_result.txt
+
+# build java benchmark
+make java-benchmark
+echo "benchmarking java..."
+./java-benchmark -Cresults.file.options.file="tmp/java_result.json" $datasets
+
+# upload result to bq
+make python_add_init
+env LD_LIBRARY_PATH="$oldpwd/src/.libs" python util/run_and_upload.py -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/javanano_jdk7/continuous.cfg b/kokoro/linux/benchmark/continuous.cfg
index 72936484..a3558c65 100644..100755
--- a/kokoro/linux/javanano_jdk7/continuous.cfg
+++ b/kokoro/linux/benchmark/continuous.cfg
@@ -1,8 +1,8 @@
# Config file for running tests in Kokoro
# Location of the build script in repository
-build_file: "protobuf/kokoro/linux/javanano_jdk7/build.sh"
-timeout_mins: 120
+build_file: "protobuf/kokoro/linux/benchmark/build.sh"
+timeout_mins: 240
action {
define_artifacts {
diff --git a/kokoro/linux/javanano_jdk7/build.sh b/kokoro/linux/javanano_jdk7/build.sh
deleted file mode 100755
index 2fc06475..00000000
--- a/kokoro/linux/javanano_jdk7/build.sh
+++ /dev/null
@@ -1,17 +0,0 @@
-#!/bin/bash
-#
-# This is the top-level script we give to Kokoro as the entry point for
-# running the "pull request" project:
-#
-# This script selects a specific Dockerfile (for building a Docker image) and
-# a script to run inside that image. Then we delegate to the general
-# build_and_run_docker.sh script.
-
-# Change to repo root
-cd $(dirname $0)/../../..
-
-export DOCKERFILE_DIR=kokoro/linux/64-bit
-export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
-export OUTPUT_DIR=testoutput
-export TEST_SET="javanano_jdk7"
-./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/javanano_jdk7/presubmit.cfg b/kokoro/linux/javanano_jdk7/presubmit.cfg
deleted file mode 100644
index 72936484..00000000
--- a/kokoro/linux/javanano_jdk7/presubmit.cfg
+++ /dev/null
@@ -1,11 +0,0 @@
-# Config file for running tests in Kokoro
-
-# Location of the build script in repository
-build_file: "protobuf/kokoro/linux/javanano_jdk7/build.sh"
-timeout_mins: 120
-
-action {
- define_artifacts {
- regex: "**/sponge_log.xml"
- }
-}
diff --git a/kokoro/linux/javanano_oracle7/build.sh b/kokoro/linux/javanano_oracle7/build.sh
deleted file mode 100755
index 651d17e8..00000000
--- a/kokoro/linux/javanano_oracle7/build.sh
+++ /dev/null
@@ -1,17 +0,0 @@
-#!/bin/bash
-#
-# This is the top-level script we give to Kokoro as the entry point for
-# running the "pull request" project:
-#
-# This script selects a specific Dockerfile (for building a Docker image) and
-# a script to run inside that image. Then we delegate to the general
-# build_and_run_docker.sh script.
-
-# Change to repo root
-cd $(dirname $0)/../../..
-
-export DOCKERFILE_DIR=kokoro/linux/64-bit
-export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
-export OUTPUT_DIR=testoutput
-export TEST_SET="javanano_oracle7"
-./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/javanano_oracle7/continuous.cfg b/kokoro/linux/javanano_oracle7/continuous.cfg
deleted file mode 100644
index 9cac8972..00000000
--- a/kokoro/linux/javanano_oracle7/continuous.cfg
+++ /dev/null
@@ -1,11 +0,0 @@
-# Config file for running tests in Kokoro
-
-# Location of the build script in repository
-build_file: "protobuf/kokoro/linux/javanano_oracle7/build.sh"
-timeout_mins: 120
-
-action {
- define_artifacts {
- regex: "**/sponge_log.xml"
- }
-}
diff --git a/kokoro/linux/javanano_oracle7/presubmit.cfg b/kokoro/linux/javanano_oracle7/presubmit.cfg
deleted file mode 100644
index 9cac8972..00000000
--- a/kokoro/linux/javanano_oracle7/presubmit.cfg
+++ /dev/null
@@ -1,11 +0,0 @@
-# Config file for running tests in Kokoro
-
-# Location of the build script in repository
-build_file: "protobuf/kokoro/linux/javanano_oracle7/build.sh"
-timeout_mins: 120
-
-action {
- define_artifacts {
- regex: "**/sponge_log.xml"
- }
-}
diff --git a/kokoro/linux/pull_request_in_docker.sh b/kokoro/linux/pull_request_in_docker.sh
index 23e63961..df3636cc 100755
--- a/kokoro/linux/pull_request_in_docker.sh
+++ b/kokoro/linux/pull_request_in_docker.sh
@@ -19,6 +19,9 @@ cd $BUILD_DIR
git clone /var/local/kokoro/protobuf
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
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/release/linux/build_artifacts.sh b/kokoro/release/linux/build_artifacts.sh
new file mode 100755
index 00000000..ae7dc813
--- /dev/null
+++ b/kokoro/release/linux/build_artifacts.sh
@@ -0,0 +1,14 @@
+#!/bin/bash
+
+set -ex
+
+# change to repo root
+cd $(dirname $0)/../../..
+
+source kokoro/release/linux/prepare_build.sh
+
+# ruby environment
+source kokoro/release/linux/ruby/ruby_build_environment.sh
+
+# build artifacts
+bash kokoro/release/linux/ruby/ruby_build.sh
diff --git a/kokoro/release/linux/prepare_build.sh b/kokoro/release/linux/prepare_build.sh
new file mode 100755
index 00000000..d3ff8764
--- /dev/null
+++ b/kokoro/release/linux/prepare_build.sh
@@ -0,0 +1,16 @@
+#!/bin/bash
+
+# Move docker's storage location to scratch disk so we don't run out of space.
+echo 'DOCKER_OPTS="${DOCKER_OPTS} --graph=/tmpfs/docker"' | sudo tee --append /etc/default/docker
+# Use container registry mirror for pulling docker images (should make downloads faster)
+# See https://cloud.google.com/container-registry/docs/using-dockerhub-mirroring
+echo 'DOCKER_OPTS="${DOCKER_OPTS} --registry-mirror=https://mirror.gcr.io"' | sudo tee --append /etc/default/docker
+sudo service docker restart
+
+# Download Docker images from DockerHub
+export DOCKERHUB_ORGANIZATION=grpctesting
+
+# All artifacts come here
+mkdir artifacts
+export ARTIFACT_DIR=$(pwd)/artifacts
+
diff --git a/kokoro/release/linux/release.cfg b/kokoro/release/linux/release.cfg
new file mode 100644
index 00000000..5dae7019
--- /dev/null
+++ b/kokoro/release/linux/release.cfg
@@ -0,0 +1,8 @@
+# Configuration for Linux release builds
+build_file: "protobuf/kokoro/release/linux/build_artifacts.sh"
+
+action {
+ define_artifacts {
+ regex: "github/protobuf/artifacts/**"
+ }
+}
diff --git a/kokoro/release/linux/ruby/ruby_build.sh b/kokoro/release/linux/ruby/ruby_build.sh
new file mode 100755
index 00000000..cf6b433d
--- /dev/null
+++ b/kokoro/release/linux/ruby/ruby_build.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+
+# Build protoc
+if test ! -e src/protoc; then
+ ./autogen.sh
+ ./configure
+ make -j4
+fi
+
+umask 0022
+pushd ruby
+bundle install && bundle exec rake gem:native
+ls pkg
+mv pkg/* $ARTIFACT_DIR
+popd
diff --git a/kokoro/release/linux/ruby/ruby_build_environment.sh b/kokoro/release/linux/ruby/ruby_build_environment.sh
new file mode 100755
index 00000000..ea04f905
--- /dev/null
+++ b/kokoro/release/linux/ruby/ruby_build_environment.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+
+set +ex
+[[ -s /etc/profile.d/rvm.sh ]] && . /etc/profile.d/rvm.sh
+set -e # rvm commands are very verbose
+rvm --default use ruby-2.4.1
+gem install bundler --update
+set -ex
diff --git a/kokoro/release/macos/build_artifacts.sh b/kokoro/release/macos/build_artifacts.sh
new file mode 100755
index 00000000..23135ca3
--- /dev/null
+++ b/kokoro/release/macos/build_artifacts.sh
@@ -0,0 +1,19 @@
+#!/bin/bash
+
+set -ex
+
+# change to repo root
+cd $(dirname $0)/../../..
+
+# all artifacts come here
+mkdir artifacts
+export ARTIFACT_DIR=$(pwd)/artifacts
+
+# ruby environment
+bash kokoro/release/macos/ruby/ruby_build_environment.sh
+
+gem install rubygems-update
+update_rubygems
+
+# build artifacts
+bash kokoro/release/macos/ruby/ruby_build.sh
diff --git a/kokoro/release/macos/release.cfg b/kokoro/release/macos/release.cfg
new file mode 100644
index 00000000..35d36dee
--- /dev/null
+++ b/kokoro/release/macos/release.cfg
@@ -0,0 +1,8 @@
+# Configuration for Mac OSX release builds
+build_file: "protobuf/kokoro/release/macos/build_artifacts.sh"
+
+action {
+ define_artifacts {
+ regex: "github/protobuf/artifacts/**"
+ }
+}
diff --git a/kokoro/release/macos/ruby/ruby_build.sh b/kokoro/release/macos/ruby/ruby_build.sh
new file mode 100755
index 00000000..cf6b433d
--- /dev/null
+++ b/kokoro/release/macos/ruby/ruby_build.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+
+# Build protoc
+if test ! -e src/protoc; then
+ ./autogen.sh
+ ./configure
+ make -j4
+fi
+
+umask 0022
+pushd ruby
+bundle install && bundle exec rake gem:native
+ls pkg
+mv pkg/* $ARTIFACT_DIR
+popd
diff --git a/kokoro/release/macos/ruby/ruby_build_environment.sh b/kokoro/release/macos/ruby/ruby_build_environment.sh
new file mode 100755
index 00000000..e9c619cd
--- /dev/null
+++ b/kokoro/release/macos/ruby/ruby_build_environment.sh
@@ -0,0 +1,57 @@
+#!/bin/bash
+
+set -ex
+
+set +ex # rvm script is very verbose and exits with errorcode
+source $HOME/.rvm/scripts/rvm
+set -e # rvm commands are very verbose
+time rvm install 2.5.0
+rvm use 2.5.0 --default
+gem install rake-compiler --no-ri --no-doc
+gem install bundler --no-ri --no-doc
+rvm osx-ssl-certs status all
+rvm osx-ssl-certs update all
+set -ex
+
+rm -rf ~/.rake-compiler
+
+CROSS_RUBY=$(mktemp tmpfile.XXXXXXXX)
+
+curl https://raw.githubusercontent.com/rake-compiler/rake-compiler/v1.0.3/tasks/bin/cross-ruby.rake > "$CROSS_RUBY"
+
+# See https://github.com/grpc/grpc/issues/12161 for verconf.h patch details
+patch "$CROSS_RUBY" << EOF
+--- cross-ruby.rake 2018-04-10 11:32:16.000000000 -0700
++++ patched 2018-04-10 11:40:25.000000000 -0700
+@@ -133,8 +133,10 @@
+ "--host=#{MINGW_HOST}",
+ "--target=#{MINGW_TARGET}",
+ "--build=#{RUBY_BUILD}",
+- '--enable-shared',
++ '--enable-static',
++ '--disable-shared',
+ '--disable-install-doc',
++ '--without-gmp',
+ '--with-ext='
+ ]
+
+@@ -151,6 +153,7 @@
+ # make
+ file "#{USER_HOME}/builds/#{MINGW_HOST}/#{RUBY_CC_VERSION}/ruby.exe" => ["#{USER_HOME}/builds/#{MINGW_HOST}/#{RUBY_CC_VERSION}/Makefile"] do |t|
+ chdir File.dirname(t.prerequisites.first) do
++ sh "test -s verconf.h || rm -f verconf.h" # if verconf.h has size 0, make sure it gets re-built by make
+ sh MAKE
+ end
+ end
+EOF
+
+MAKE="make -j8"
+
+for v in 2.5.0 2.4.0 2.3.0 2.2.2 2.1.6 2.0.0-p645 ; do
+ ccache -c
+ rake -f "$CROSS_RUBY" cross-ruby VERSION="$v" HOST=x86_64-darwin11 MAKE="$MAKE"
+done
+
+sed 's/x86_64-darwin-11/universal-darwin/' ~/.rake-compiler/config.yml > "$CROSS_RUBY"
+mv "$CROSS_RUBY" ~/.rake-compiler/config.yml
+
diff --git a/kokoro/release/protoc/macos/build.sh b/kokoro/release/protoc/macos/build.sh
new file mode 100644
index 00000000..db9d3140
--- /dev/null
+++ b/kokoro/release/protoc/macos/build.sh
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+set -x
+CXXFLAGS_COMMON="-DNDEBUG -mmacosx-version-min=10.9"
+
+cd github/protobuf
+./autogen.sh
+
+mkdir build32 && cd build32
+export CXXFLAGS="$CXXFLAGS_COMMON -m32"
+../configure --disable-shared
+make -j4
+file src/protoc
+otool -L src/protoc | grep dylib
+cd ..
+
+mkdir build64 && cd build64
+export CXXFLAGS="$CXXFLAGS_COMMON -m64"
+../configure --disable-shared
+make -j4
+file src/protoc
+otool -L src/protoc | grep dylib
+cd ..
diff --git a/kokoro/release/protoc/macos/release.cfg b/kokoro/release/protoc/macos/release.cfg
new file mode 100644
index 00000000..da903d03
--- /dev/null
+++ b/kokoro/release/protoc/macos/release.cfg
@@ -0,0 +1,8 @@
+# Configuration for Mac OSX protoc release builds
+build_file: "protobuf/kokoro/release/protoc/macos/build.sh"
+
+action {
+ define_artifacts {
+ regex: "**/protoc"
+ }
+}
diff --git a/kokoro/release/protoc/windows/build.bat b/kokoro/release/protoc/windows/build.bat
new file mode 100644
index 00000000..ae0fa94a
--- /dev/null
+++ b/kokoro/release/protoc/windows/build.bat
@@ -0,0 +1,27 @@
+set PATH=C:\Program Files (x86)\MSBuild\14.0\bin\;%PATH%
+set generator32=Visual Studio 14
+set generator64=Visual Studio 14 Win64
+set vcplatform32=win32
+set vcplatform64=x64
+set configuration=Release
+
+echo Building protoc
+cd github\protobuf
+
+mkdir build32
+cd build32
+cmake -G "%generator32%" -Dprotobuf_BUILD_TESTS=OFF -Dprotobuf_BUILD_SHARED_LIBS=OFF -Dprotobuf_UNICODE=ON ../cmake
+msbuild protobuf.sln /p:Platform=%vcplatform32% || goto error
+cd ..
+
+mkdir build64
+cd build64
+cmake -G "%generator64%" -Dprotobuf_BUILD_TESTS=OFF -Dprotobuf_BUILD_SHARED_LIBS=OFF -Dprotobuf_UNICODE=ON ../cmake
+msbuild protobuf.sln /p:Platform=%vcplatform64% || goto error
+cd ..
+
+goto :EOF
+
+:error
+echo Failed!
+exit /b %ERRORLEVEL%
diff --git a/kokoro/release/protoc/windows/release.cfg b/kokoro/release/protoc/windows/release.cfg
new file mode 100644
index 00000000..0d0da8f1
--- /dev/null
+++ b/kokoro/release/protoc/windows/release.cfg
@@ -0,0 +1,8 @@
+# Configuration for Windows protoc release builds
+build_file: "protobuf/kokoro/release/protoc/windows/build.bat"
+
+action {
+ define_artifacts {
+ regex: "**/protoc.exe"
+ }
+}
diff --git a/m4/acx_pthread.m4 b/m4/acx_pthread.m4
deleted file mode 100644
index 89d42c74..00000000
--- a/m4/acx_pthread.m4
+++ /dev/null
@@ -1,397 +0,0 @@
-# This was retrieved from
-# http://svn.0pointer.de/viewvc/trunk/common/acx_pthread.m4?revision=1277&root=avahi
-# See also (perhaps for new versions?)
-# http://svn.0pointer.de/viewvc/trunk/common/acx_pthread.m4?root=avahi
-#
-# We've rewritten the inconsistency check code (from avahi), to work
-# more broadly. In particular, it no longer assumes ld accepts -zdefs.
-# This caused a restructing of the code, but the functionality has only
-# changed a little.
-
-dnl @synopsis ACX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
-dnl
-dnl @summary figure out how to build C programs using POSIX threads
-dnl
-dnl This macro figures out how to build C programs using POSIX threads.
-dnl It sets the PTHREAD_LIBS output variable to the threads library and
-dnl linker flags, and the PTHREAD_CFLAGS output variable to any special
-dnl C compiler flags that are needed. (The user can also force certain
-dnl compiler flags/libs to be tested by setting these environment
-dnl variables.)
-dnl
-dnl Also sets PTHREAD_CC to any special C compiler that is needed for
-dnl multi-threaded programs (defaults to the value of CC otherwise).
-dnl (This is necessary on AIX to use the special cc_r compiler alias.)
-dnl
-dnl NOTE: You are assumed to not only compile your program with these
-dnl flags, but also link it with them as well. e.g. you should link
-dnl with $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS
-dnl $LIBS
-dnl
-dnl If you are only building threads programs, you may wish to use
-dnl these variables in your default LIBS, CFLAGS, and CC:
-dnl
-dnl LIBS="$PTHREAD_LIBS $LIBS"
-dnl CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-dnl CC="$PTHREAD_CC"
-dnl
-dnl In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute
-dnl constant has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to
-dnl that name (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
-dnl
-dnl ACTION-IF-FOUND is a list of shell commands to run if a threads
-dnl library is found, and ACTION-IF-NOT-FOUND is a list of commands to
-dnl run it if it is not found. If ACTION-IF-FOUND is not specified, the
-dnl default action will define HAVE_PTHREAD.
-dnl
-dnl Please let the authors know if this macro fails on any platform, or
-dnl if you have any other suggestions or comments. This macro was based
-dnl on work by SGJ on autoconf scripts for FFTW (www.fftw.org) (with
-dnl help from M. Frigo), as well as ac_pthread and hb_pthread macros
-dnl posted by Alejandro Forero Cuervo to the autoconf macro repository.
-dnl We are also grateful for the helpful feedback of numerous users.
-dnl
-dnl @category InstalledPackages
-dnl @author Steven G. Johnson <stevenj@alum.mit.edu>
-dnl @version 2006-05-29
-dnl @license GPLWithACException
-dnl
-dnl Checks for GCC shared/pthread inconsistency based on work by
-dnl Marcin Owsiany <marcin@owsiany.pl>
-
-
-AC_DEFUN([ACX_PTHREAD], [
-AC_REQUIRE([AC_CANONICAL_HOST])
-AC_LANG_SAVE
-AC_LANG_C
-acx_pthread_ok=no
-
-# We used to check for pthread.h first, but this fails if pthread.h
-# requires special compiler flags (e.g. on True64 or Sequent).
-# It gets checked for in the link test anyway.
-
-# First of all, check if the user has set any of the PTHREAD_LIBS,
-# etcetera environment variables, and if threads linking works using
-# them:
-if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then
- save_CFLAGS="$CFLAGS"
- CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
- save_LIBS="$LIBS"
- LIBS="$PTHREAD_LIBS $LIBS"
- AC_MSG_CHECKING([for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS])
- AC_TRY_LINK_FUNC(pthread_join, acx_pthread_ok=yes)
- AC_MSG_RESULT($acx_pthread_ok)
- if test x"$acx_pthread_ok" = xno; then
- PTHREAD_LIBS=""
- PTHREAD_CFLAGS=""
- fi
- LIBS="$save_LIBS"
- CFLAGS="$save_CFLAGS"
-fi
-
-# We must check for the threads library under a number of different
-# names; the ordering is very important because some systems
-# (e.g. DEC) have both -lpthread and -lpthreads, where one of the
-# libraries is broken (non-POSIX).
-
-# Create a list of thread flags to try. Items starting with a "-" are
-# C compiler flags, and other items are library names, except for "none"
-# which indicates that we try without any flags at all, and "pthread-config"
-# which is a program returning the flags for the Pth emulation library.
-
-acx_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"
-
-# The ordering *is* (sometimes) important. Some notes on the
-# individual items follow:
-
-# pthreads: AIX (must check this before -lpthread)
-# none: in case threads are in libc; should be tried before -Kthread and
-# other compiler flags to prevent continual compiler warnings
-# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
-# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
-# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
-# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads)
-# -pthreads: Solaris/gcc
-# -mthreads: Mingw32/gcc, Lynx/gcc
-# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
-# doesn't hurt to check since this sometimes defines pthreads too;
-# also defines -D_REENTRANT)
-# ... -mt is also the pthreads flag for HP/aCC
-# pthread: Linux, etcetera
-# --thread-safe: KAI C++
-# pthread-config: use pthread-config program (for GNU Pth library)
-
-case "${host_cpu}-${host_os}" in
- *solaris*)
-
- # On Solaris (at least, for some versions), libc contains stubbed
- # (non-functional) versions of the pthreads routines, so link-based
- # tests will erroneously succeed. (We need to link with -pthreads/-mt/
- # -lpthread.) (The stubs are missing pthread_cleanup_push, or rather
- # a function called by this macro, so we could check for that, but
- # who knows whether they'll stub that too in a future libc.) So,
- # we'll just look for -pthreads and -lpthread first:
-
- acx_pthread_flags="-pthreads pthread -mt -pthread $acx_pthread_flags"
- ;;
-esac
-
-if test x"$acx_pthread_ok" = xno; then
-for flag in $acx_pthread_flags; do
-
- case $flag in
- none)
- AC_MSG_CHECKING([whether pthreads work without any flags])
- ;;
-
- -*)
- AC_MSG_CHECKING([whether pthreads work with $flag])
- PTHREAD_CFLAGS="$flag"
- ;;
-
- pthread-config)
- AC_CHECK_PROG(acx_pthread_config, pthread-config, yes, no)
- if test x"$acx_pthread_config" = xno; then continue; fi
- PTHREAD_CFLAGS="`pthread-config --cflags`"
- PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
- ;;
-
- *)
- AC_MSG_CHECKING([for the pthreads library -l$flag])
- PTHREAD_LIBS="-l$flag"
- ;;
- esac
-
- save_LIBS="$LIBS"
- save_CFLAGS="$CFLAGS"
- LIBS="$PTHREAD_LIBS $LIBS"
- CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-
- # Check for various functions. We must include pthread.h,
- # since some functions may be macros. (On the Sequent, we
- # need a special flag -Kthread to make this header compile.)
- # We check for pthread_join because it is in -lpthread on IRIX
- # while pthread_create is in libc. We check for pthread_attr_init
- # due to DEC craziness with -lpthreads. We check for
- # pthread_cleanup_push because it is one of the few pthread
- # functions on Solaris that doesn't have a non-functional libc stub.
- # We try pthread_create on general principles.
- AC_TRY_LINK([#include <pthread.h>],
- [pthread_t th; pthread_join(th, 0);
- pthread_attr_init(0); pthread_cleanup_push(0, 0);
- pthread_create(0,0,0,0); pthread_cleanup_pop(0); ],
- [acx_pthread_ok=yes])
-
- LIBS="$save_LIBS"
- CFLAGS="$save_CFLAGS"
-
- AC_MSG_RESULT($acx_pthread_ok)
- if test "x$acx_pthread_ok" = xyes; then
- break;
- fi
-
- PTHREAD_LIBS=""
- PTHREAD_CFLAGS=""
-done
-fi
-
-# Various other checks:
-if test "x$acx_pthread_ok" = xyes; then
- save_LIBS="$LIBS"
- LIBS="$PTHREAD_LIBS $LIBS"
- save_CFLAGS="$CFLAGS"
- CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-
- # Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
- AC_MSG_CHECKING([for joinable pthread attribute])
- attr_name=unknown
- for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
- AC_TRY_LINK([#include <pthread.h>], [int attr=$attr; return attr;],
- [attr_name=$attr; break])
- done
- AC_MSG_RESULT($attr_name)
- if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then
- AC_DEFINE_UNQUOTED(PTHREAD_CREATE_JOINABLE, $attr_name,
- [Define to necessary symbol if this constant
- uses a non-standard name on your system.])
- fi
-
- AC_MSG_CHECKING([if more special flags are required for pthreads])
- flag=no
- case "${host_cpu}-${host_os}" in
- *-aix* | *-freebsd* | *-darwin*) flag="-D_THREAD_SAFE";;
- *solaris* | *-osf* | *-hpux*) flag="-D_REENTRANT";;
- esac
- AC_MSG_RESULT(${flag})
- if test "x$flag" != xno; then
- PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS"
- fi
-
- LIBS="$save_LIBS"
- CFLAGS="$save_CFLAGS"
- # More AIX lossage: must compile with xlc_r or cc_r
- if test x"$GCC" != xyes; then
- AC_CHECK_PROGS(PTHREAD_CC, xlc_r cc_r, ${CC})
- else
- PTHREAD_CC=$CC
- fi
-
- # The next part tries to detect GCC inconsistency with -shared on some
- # architectures and systems. The problem is that in certain
- # configurations, when -shared is specified, GCC "forgets" to
- # internally use various flags which are still necessary.
-
- #
- # Prepare the flags
- #
- save_CFLAGS="$CFLAGS"
- save_LIBS="$LIBS"
- save_CC="$CC"
-
- # Try with the flags determined by the earlier checks.
- #
- # -Wl,-z,defs forces link-time symbol resolution, so that the
- # linking checks with -shared actually have any value
- #
- # FIXME: -fPIC is required for -shared on many architectures,
- # so we specify it here, but the right way would probably be to
- # properly detect whether it is actually required.
- CFLAGS="-shared -fPIC -Wl,-z,defs $CFLAGS $PTHREAD_CFLAGS"
- LIBS="$PTHREAD_LIBS $LIBS"
- CC="$PTHREAD_CC"
-
- # In order not to create several levels of indentation, we test
- # the value of "$done" until we find the cure or run out of ideas.
- done="no"
-
- # First, make sure the CFLAGS we added are actually accepted by our
- # compiler. If not (and OS X's ld, for instance, does not accept -z),
- # then we can't do this test.
- if test x"$done" = xno; then
- AC_MSG_CHECKING([whether to check for GCC pthread/shared inconsistencies])
- AC_TRY_LINK(,, , [done=yes])
-
- if test "x$done" = xyes ; then
- AC_MSG_RESULT([no])
- else
- AC_MSG_RESULT([yes])
- fi
- fi
-
- if test x"$done" = xno; then
- AC_MSG_CHECKING([whether -pthread is sufficient with -shared])
- AC_TRY_LINK([#include <pthread.h>],
- [pthread_t th; pthread_join(th, 0);
- pthread_attr_init(0); pthread_cleanup_push(0, 0);
- pthread_create(0,0,0,0); pthread_cleanup_pop(0); ],
- [done=yes])
-
- if test "x$done" = xyes; then
- AC_MSG_RESULT([yes])
- else
- AC_MSG_RESULT([no])
- fi
- fi
-
- #
- # Linux gcc on some architectures such as mips/mipsel forgets
- # about -lpthread
- #
- if test x"$done" = xno; then
- AC_MSG_CHECKING([whether -lpthread fixes that])
- LIBS="-lpthread $PTHREAD_LIBS $save_LIBS"
- AC_TRY_LINK([#include <pthread.h>],
- [pthread_t th; pthread_join(th, 0);
- pthread_attr_init(0); pthread_cleanup_push(0, 0);
- pthread_create(0,0,0,0); pthread_cleanup_pop(0); ],
- [done=yes])
-
- if test "x$done" = xyes; then
- AC_MSG_RESULT([yes])
- PTHREAD_LIBS="-lpthread $PTHREAD_LIBS"
- else
- AC_MSG_RESULT([no])
- fi
- fi
- #
- # FreeBSD 4.10 gcc forgets to use -lc_r instead of -lc
- #
- if test x"$done" = xno; then
- AC_MSG_CHECKING([whether -lc_r fixes that])
- LIBS="-lc_r $PTHREAD_LIBS $save_LIBS"
- AC_TRY_LINK([#include <pthread.h>],
- [pthread_t th; pthread_join(th, 0);
- pthread_attr_init(0); pthread_cleanup_push(0, 0);
- pthread_create(0,0,0,0); pthread_cleanup_pop(0); ],
- [done=yes])
-
- if test "x$done" = xyes; then
- AC_MSG_RESULT([yes])
- PTHREAD_LIBS="-lc_r $PTHREAD_LIBS"
- else
- AC_MSG_RESULT([no])
- fi
- fi
- if test x"$done" = xno; then
- # OK, we have run out of ideas
- AC_MSG_WARN([Impossible to determine how to use pthreads with shared libraries])
-
- # so it's not safe to assume that we may use pthreads
- acx_pthread_ok=no
- fi
-
- AC_MSG_CHECKING([whether what we have so far is sufficient with -nostdlib])
- CFLAGS="-nostdlib $CFLAGS"
- # we need c with nostdlib
- LIBS="$LIBS -lc"
- AC_TRY_LINK([#include <pthread.h>],
- [pthread_t th; pthread_join(th, 0);
- pthread_attr_init(0); pthread_cleanup_push(0, 0);
- pthread_create(0,0,0,0); pthread_cleanup_pop(0); ],
- [done=yes],[done=no])
-
- if test "x$done" = xyes; then
- AC_MSG_RESULT([yes])
- else
- AC_MSG_RESULT([no])
- fi
-
- if test x"$done" = xno; then
- AC_MSG_CHECKING([whether -lpthread saves the day])
- LIBS="-lpthread $LIBS"
- AC_TRY_LINK([#include <pthread.h>],
- [pthread_t th; pthread_join(th, 0);
- pthread_attr_init(0); pthread_cleanup_push(0, 0);
- pthread_create(0,0,0,0); pthread_cleanup_pop(0); ],
- [done=yes],[done=no])
-
- if test "x$done" = xyes; then
- AC_MSG_RESULT([yes])
- PTHREAD_LIBS="$PTHREAD_LIBS -lpthread"
- else
- AC_MSG_RESULT([no])
- AC_MSG_WARN([Impossible to determine how to use pthreads with shared libraries and -nostdlib])
- fi
- fi
-
- CFLAGS="$save_CFLAGS"
- LIBS="$save_LIBS"
- CC="$save_CC"
-else
- PTHREAD_CC="$CC"
-fi
-
-AC_SUBST(PTHREAD_LIBS)
-AC_SUBST(PTHREAD_CFLAGS)
-AC_SUBST(PTHREAD_CC)
-
-# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
-if test x"$acx_pthread_ok" = xyes; then
- ifelse([$1],,AC_DEFINE(HAVE_PTHREAD,1,[Define if you have POSIX threads libraries and header files.]),[$1])
- :
-else
- acx_pthread_ok=no
- $2
-fi
-AC_LANG_RESTORE
-])dnl ACX_PTHREAD
diff --git a/m4/ax_pthread.m4 b/m4/ax_pthread.m4
new file mode 100644
index 00000000..d218d1af
--- /dev/null
+++ b/m4/ax_pthread.m4
@@ -0,0 +1,485 @@
+# ===========================================================================
+# http://www.gnu.org/software/autoconf-archive/ax_pthread.html
+# ===========================================================================
+#
+# SYNOPSIS
+#
+# AX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
+#
+# DESCRIPTION
+#
+# This macro figures out how to build C programs using POSIX threads. It
+# sets the PTHREAD_LIBS output variable to the threads library and linker
+# flags, and the PTHREAD_CFLAGS output variable to any special C compiler
+# flags that are needed. (The user can also force certain compiler
+# flags/libs to be tested by setting these environment variables.)
+#
+# Also sets PTHREAD_CC to any special C compiler that is needed for
+# multi-threaded programs (defaults to the value of CC otherwise). (This
+# is necessary on AIX to use the special cc_r compiler alias.)
+#
+# NOTE: You are assumed to not only compile your program with these flags,
+# but also to link with them as well. For example, you might link with
+# $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS
+#
+# If you are only building threaded programs, you may wish to use these
+# variables in your default LIBS, CFLAGS, and CC:
+#
+# LIBS="$PTHREAD_LIBS $LIBS"
+# CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+# CC="$PTHREAD_CC"
+#
+# In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute constant
+# has a nonstandard name, this macro defines PTHREAD_CREATE_JOINABLE to
+# that name (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
+#
+# Also HAVE_PTHREAD_PRIO_INHERIT is defined if pthread is found and the
+# PTHREAD_PRIO_INHERIT symbol is defined when compiling with
+# PTHREAD_CFLAGS.
+#
+# ACTION-IF-FOUND is a list of shell commands to run if a threads library
+# is found, and ACTION-IF-NOT-FOUND is a list of commands to run it if it
+# is not found. If ACTION-IF-FOUND is not specified, the default action
+# will define HAVE_PTHREAD.
+#
+# Please let the authors know if this macro fails on any platform, or if
+# you have any other suggestions or comments. This macro was based on work
+# by SGJ on autoconf scripts for FFTW (http://www.fftw.org/) (with help
+# from M. Frigo), as well as ac_pthread and hb_pthread macros posted by
+# Alejandro Forero Cuervo to the autoconf macro repository. We are also
+# grateful for the helpful feedback of numerous users.
+#
+# Updated for Autoconf 2.68 by Daniel Richard G.
+#
+# LICENSE
+#
+# Copyright (c) 2008 Steven G. Johnson <stevenj@alum.mit.edu>
+# Copyright (c) 2011 Daniel Richard G. <skunk@iSKUNK.ORG>
+#
+# This program is free software: you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by the
+# Free Software Foundation, either version 3 of the License, or (at your
+# option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
+# Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+# As a special exception, the respective Autoconf Macro's copyright owner
+# gives unlimited permission to copy, distribute and modify the configure
+# scripts that are the output of Autoconf when processing the Macro. You
+# need not follow the terms of the GNU General Public License when using
+# or distributing such scripts, even though portions of the text of the
+# Macro appear in them. The GNU General Public License (GPL) does govern
+# all other use of the material that constitutes the Autoconf Macro.
+#
+# This special exception to the GPL applies to versions of the Autoconf
+# Macro released by the Autoconf Archive. When you make and distribute a
+# modified version of the Autoconf Macro, you may extend this special
+# exception to the GPL to apply to your modified version as well.
+
+#serial 22
+
+AU_ALIAS([ACX_PTHREAD], [AX_PTHREAD])
+AC_DEFUN([AX_PTHREAD], [
+AC_REQUIRE([AC_CANONICAL_HOST])
+AC_REQUIRE([AC_PROG_CC])
+AC_REQUIRE([AC_PROG_SED])
+AC_LANG_PUSH([C])
+ax_pthread_ok=no
+
+# We used to check for pthread.h first, but this fails if pthread.h
+# requires special compiler flags (e.g. on Tru64 or Sequent).
+# It gets checked for in the link test anyway.
+
+# First of all, check if the user has set any of the PTHREAD_LIBS,
+# etcetera environment variables, and if threads linking works using
+# them:
+if test "x$PTHREAD_CFLAGS$PTHREAD_LIBS" != "x"; then
+ ax_pthread_save_CC="$CC"
+ ax_pthread_save_CFLAGS="$CFLAGS"
+ ax_pthread_save_LIBS="$LIBS"
+ AS_IF([test "x$PTHREAD_CC" != "x"], [CC="$PTHREAD_CC"])
+ CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+ LIBS="$PTHREAD_LIBS $LIBS"
+ AC_MSG_CHECKING([for pthread_join using $CC $PTHREAD_CFLAGS $PTHREAD_LIBS])
+ AC_LINK_IFELSE([AC_LANG_CALL([], [pthread_join])], [ax_pthread_ok=yes])
+ AC_MSG_RESULT([$ax_pthread_ok])
+ if test "x$ax_pthread_ok" = "xno"; then
+ PTHREAD_LIBS=""
+ PTHREAD_CFLAGS=""
+ fi
+ CC="$ax_pthread_save_CC"
+ CFLAGS="$ax_pthread_save_CFLAGS"
+ LIBS="$ax_pthread_save_LIBS"
+fi
+
+# We must check for the threads library under a number of different
+# names; the ordering is very important because some systems
+# (e.g. DEC) have both -lpthread and -lpthreads, where one of the
+# libraries is broken (non-POSIX).
+
+# Create a list of thread flags to try. Items starting with a "-" are
+# C compiler flags, and other items are library names, except for "none"
+# which indicates that we try without any flags at all, and "pthread-config"
+# which is a program returning the flags for the Pth emulation library.
+
+ax_pthread_flags="pthreads none -Kthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"
+
+# The ordering *is* (sometimes) important. Some notes on the
+# individual items follow:
+
+# pthreads: AIX (must check this before -lpthread)
+# none: in case threads are in libc; should be tried before -Kthread and
+# other compiler flags to prevent continual compiler warnings
+# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
+# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads), Tru64
+# (Note: HP C rejects this with "bad form for `-t' option")
+# -pthreads: Solaris/gcc (Note: HP C also rejects)
+# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
+# doesn't hurt to check since this sometimes defines pthreads and
+# -D_REENTRANT too), HP C (must be checked before -lpthread, which
+# is present but should not be used directly; and before -mthreads,
+# because the compiler interprets this as "-mt" + "-hreads")
+# -mthreads: Mingw32/gcc, Lynx/gcc
+# pthread: Linux, etcetera
+# --thread-safe: KAI C++
+# pthread-config: use pthread-config program (for GNU Pth library)
+
+case $host_os in
+
+ freebsd*)
+
+ # -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
+ # lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
+
+ ax_pthread_flags="-kthread lthread $ax_pthread_flags"
+ ;;
+
+ hpux*)
+
+ # From the cc(1) man page: "[-mt] Sets various -D flags to enable
+ # multi-threading and also sets -lpthread."
+
+ ax_pthread_flags="-mt -pthread pthread $ax_pthread_flags"
+ ;;
+
+ openedition*)
+
+ # IBM z/OS requires a feature-test macro to be defined in order to
+ # enable POSIX threads at all, so give the user a hint if this is
+ # not set. (We don't define these ourselves, as they can affect
+ # other portions of the system API in unpredictable ways.)
+
+ AC_EGREP_CPP([AX_PTHREAD_ZOS_MISSING],
+ [
+# if !defined(_OPEN_THREADS) && !defined(_UNIX03_THREADS)
+ AX_PTHREAD_ZOS_MISSING
+# endif
+ ],
+ [AC_MSG_WARN([IBM z/OS requires -D_OPEN_THREADS or -D_UNIX03_THREADS to enable pthreads support.])])
+ ;;
+
+ solaris*)
+
+ # On Solaris (at least, for some versions), libc contains stubbed
+ # (non-functional) versions of the pthreads routines, so link-based
+ # tests will erroneously succeed. (N.B.: The stubs are missing
+ # pthread_cleanup_push, or rather a function called by this macro,
+ # so we could check for that, but who knows whether they'll stub
+ # that too in a future libc.) So we'll check first for the
+ # standard Solaris way of linking pthreads (-mt -lpthread).
+
+ ax_pthread_flags="-mt,pthread pthread $ax_pthread_flags"
+ ;;
+esac
+
+# GCC generally uses -pthread, or -pthreads on some platforms (e.g. SPARC)
+
+AS_IF([test "x$GCC" = "xyes"],
+ [ax_pthread_flags="-pthread -pthreads $ax_pthread_flags"])
+
+# The presence of a feature test macro requesting re-entrant function
+# definitions is, on some systems, a strong hint that pthreads support is
+# correctly enabled
+
+case $host_os in
+ darwin* | hpux* | linux* | osf* | solaris*)
+ ax_pthread_check_macro="_REENTRANT"
+ ;;
+
+ aix* | freebsd*)
+ ax_pthread_check_macro="_THREAD_SAFE"
+ ;;
+
+ *)
+ ax_pthread_check_macro="--"
+ ;;
+esac
+AS_IF([test "x$ax_pthread_check_macro" = "x--"],
+ [ax_pthread_check_cond=0],
+ [ax_pthread_check_cond="!defined($ax_pthread_check_macro)"])
+
+# Are we compiling with Clang?
+
+AC_CACHE_CHECK([whether $CC is Clang],
+ [ax_cv_PTHREAD_CLANG],
+ [ax_cv_PTHREAD_CLANG=no
+ # Note that Autoconf sets GCC=yes for Clang as well as GCC
+ if test "x$GCC" = "xyes"; then
+ AC_EGREP_CPP([AX_PTHREAD_CC_IS_CLANG],
+ [/* Note: Clang 2.7 lacks __clang_[a-z]+__ */
+# if defined(__clang__) && defined(__llvm__)
+ AX_PTHREAD_CC_IS_CLANG
+# endif
+ ],
+ [ax_cv_PTHREAD_CLANG=yes])
+ fi
+ ])
+ax_pthread_clang="$ax_cv_PTHREAD_CLANG"
+
+ax_pthread_clang_warning=no
+
+# Clang needs special handling, because older versions handle the -pthread
+# option in a rather... idiosyncratic way
+
+if test "x$ax_pthread_clang" = "xyes"; then
+
+ # Clang takes -pthread; it has never supported any other flag
+
+ # (Note 1: This will need to be revisited if a system that Clang
+ # supports has POSIX threads in a separate library. This tends not
+ # to be the way of modern systems, but it's conceivable.)
+
+ # (Note 2: On some systems, notably Darwin, -pthread is not needed
+ # to get POSIX threads support; the API is always present and
+ # active. We could reasonably leave PTHREAD_CFLAGS empty. But
+ # -pthread does define _REENTRANT, and while the Darwin headers
+ # ignore this macro, third-party headers might not.)
+
+ PTHREAD_CFLAGS="-pthread"
+ PTHREAD_LIBS=
+
+ ax_pthread_ok=yes
+
+ # However, older versions of Clang make a point of warning the user
+ # that, in an invocation where only linking and no compilation is
+ # taking place, the -pthread option has no effect ("argument unused
+ # during compilation"). They expect -pthread to be passed in only
+ # when source code is being compiled.
+ #
+ # Problem is, this is at odds with the way Automake and most other
+ # C build frameworks function, which is that the same flags used in
+ # compilation (CFLAGS) are also used in linking. Many systems
+ # supported by AX_PTHREAD require exactly this for POSIX threads
+ # support, and in fact it is often not straightforward to specify a
+ # flag that is used only in the compilation phase and not in
+ # linking. Such a scenario is extremely rare in practice.
+ #
+ # Even though use of the -pthread flag in linking would only print
+ # a warning, this can be a nuisance for well-run software projects
+ # that build with -Werror. So if the active version of Clang has
+ # this misfeature, we search for an option to squash it.
+
+ AC_CACHE_CHECK([whether Clang needs flag to prevent "argument unused" warning when linking with -pthread],
+ [ax_cv_PTHREAD_CLANG_NO_WARN_FLAG],
+ [ax_cv_PTHREAD_CLANG_NO_WARN_FLAG=unknown
+ # Create an alternate version of $ac_link that compiles and
+ # links in two steps (.c -> .o, .o -> exe) instead of one
+ # (.c -> exe), because the warning occurs only in the second
+ # step
+ ax_pthread_save_ac_link="$ac_link"
+ ax_pthread_sed='s/conftest\.\$ac_ext/conftest.$ac_objext/g'
+ ax_pthread_link_step=`$as_echo "$ac_link" | sed "$ax_pthread_sed"`
+ ax_pthread_2step_ac_link="($ac_compile) && (echo ==== >&5) && ($ax_pthread_link_step)"
+ ax_pthread_save_CFLAGS="$CFLAGS"
+ for ax_pthread_try in '' -Qunused-arguments -Wno-unused-command-line-argument unknown; do
+ AS_IF([test "x$ax_pthread_try" = "xunknown"], [break])
+ CFLAGS="-Werror -Wunknown-warning-option $ax_pthread_try -pthread $ax_pthread_save_CFLAGS"
+ ac_link="$ax_pthread_save_ac_link"
+ AC_LINK_IFELSE([AC_LANG_SOURCE([[int main(void){return 0;}]])],
+ [ac_link="$ax_pthread_2step_ac_link"
+ AC_LINK_IFELSE([AC_LANG_SOURCE([[int main(void){return 0;}]])],
+ [break])
+ ])
+ done
+ ac_link="$ax_pthread_save_ac_link"
+ CFLAGS="$ax_pthread_save_CFLAGS"
+ AS_IF([test "x$ax_pthread_try" = "x"], [ax_pthread_try=no])
+ ax_cv_PTHREAD_CLANG_NO_WARN_FLAG="$ax_pthread_try"
+ ])
+
+ case "$ax_cv_PTHREAD_CLANG_NO_WARN_FLAG" in
+ no | unknown) ;;
+ *) PTHREAD_CFLAGS="$ax_cv_PTHREAD_CLANG_NO_WARN_FLAG $PTHREAD_CFLAGS" ;;
+ esac
+
+fi # $ax_pthread_clang = yes
+
+if test "x$ax_pthread_ok" = "xno"; then
+for ax_pthread_try_flag in $ax_pthread_flags; do
+
+ case $ax_pthread_try_flag in
+ none)
+ AC_MSG_CHECKING([whether pthreads work without any flags])
+ ;;
+
+ -mt,pthread)
+ AC_MSG_CHECKING([whether pthreads work with -mt -lpthread])
+ PTHREAD_CFLAGS="-mt"
+ PTHREAD_LIBS="-lpthread"
+ ;;
+
+ -*)
+ AC_MSG_CHECKING([whether pthreads work with $ax_pthread_try_flag])
+ PTHREAD_CFLAGS="$ax_pthread_try_flag"
+ ;;
+
+ pthread-config)
+ AC_CHECK_PROG([ax_pthread_config], [pthread-config], [yes], [no])
+ AS_IF([test "x$ax_pthread_config" = "xno"], [continue])
+ PTHREAD_CFLAGS="`pthread-config --cflags`"
+ PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
+ ;;
+
+ *)
+ AC_MSG_CHECKING([for the pthreads library -l$ax_pthread_try_flag])
+ PTHREAD_LIBS="-l$ax_pthread_try_flag"
+ ;;
+ esac
+
+ ax_pthread_save_CFLAGS="$CFLAGS"
+ ax_pthread_save_LIBS="$LIBS"
+ CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+ LIBS="$PTHREAD_LIBS $LIBS"
+
+ # Check for various functions. We must include pthread.h,
+ # since some functions may be macros. (On the Sequent, we
+ # need a special flag -Kthread to make this header compile.)
+ # We check for pthread_join because it is in -lpthread on IRIX
+ # while pthread_create is in libc. We check for pthread_attr_init
+ # due to DEC craziness with -lpthreads. We check for
+ # pthread_cleanup_push because it is one of the few pthread
+ # functions on Solaris that doesn't have a non-functional libc stub.
+ # We try pthread_create on general principles.
+
+ AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <pthread.h>
+# if $ax_pthread_check_cond
+# error "$ax_pthread_check_macro must be defined"
+# endif
+ static void routine(void *a) { a = 0; }
+ static void *start_routine(void *a) { return a; }],
+ [pthread_t th; pthread_attr_t attr;
+ pthread_create(&th, 0, start_routine, 0);
+ pthread_join(th, 0);
+ pthread_attr_init(&attr);
+ pthread_cleanup_push(routine, 0);
+ pthread_cleanup_pop(0) /* ; */])],
+ [ax_pthread_ok=yes],
+ [])
+
+ CFLAGS="$ax_pthread_save_CFLAGS"
+ LIBS="$ax_pthread_save_LIBS"
+
+ AC_MSG_RESULT([$ax_pthread_ok])
+ AS_IF([test "x$ax_pthread_ok" = "xyes"], [break])
+
+ PTHREAD_LIBS=""
+ PTHREAD_CFLAGS=""
+done
+fi
+
+# Various other checks:
+if test "x$ax_pthread_ok" = "xyes"; then
+ ax_pthread_save_CFLAGS="$CFLAGS"
+ ax_pthread_save_LIBS="$LIBS"
+ CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+ LIBS="$PTHREAD_LIBS $LIBS"
+
+ # Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
+ AC_CACHE_CHECK([for joinable pthread attribute],
+ [ax_cv_PTHREAD_JOINABLE_ATTR],
+ [ax_cv_PTHREAD_JOINABLE_ATTR=unknown
+ for ax_pthread_attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
+ AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <pthread.h>],
+ [int attr = $ax_pthread_attr; return attr /* ; */])],
+ [ax_cv_PTHREAD_JOINABLE_ATTR=$ax_pthread_attr; break],
+ [])
+ done
+ ])
+ AS_IF([test "x$ax_cv_PTHREAD_JOINABLE_ATTR" != "xunknown" && \
+ test "x$ax_cv_PTHREAD_JOINABLE_ATTR" != "xPTHREAD_CREATE_JOINABLE" && \
+ test "x$ax_pthread_joinable_attr_defined" != "xyes"],
+ [AC_DEFINE_UNQUOTED([PTHREAD_CREATE_JOINABLE],
+ [$ax_cv_PTHREAD_JOINABLE_ATTR],
+ [Define to necessary symbol if this constant
+ uses a non-standard name on your system.])
+ ax_pthread_joinable_attr_defined=yes
+ ])
+
+ AC_CACHE_CHECK([whether more special flags are required for pthreads],
+ [ax_cv_PTHREAD_SPECIAL_FLAGS],
+ [ax_cv_PTHREAD_SPECIAL_FLAGS=no
+ case $host_os in
+ solaris*)
+ ax_cv_PTHREAD_SPECIAL_FLAGS="-D_POSIX_PTHREAD_SEMANTICS"
+ ;;
+ esac
+ ])
+ AS_IF([test "x$ax_cv_PTHREAD_SPECIAL_FLAGS" != "xno" && \
+ test "x$ax_pthread_special_flags_added" != "xyes"],
+ [PTHREAD_CFLAGS="$ax_cv_PTHREAD_SPECIAL_FLAGS $PTHREAD_CFLAGS"
+ ax_pthread_special_flags_added=yes])
+
+ AC_CACHE_CHECK([for PTHREAD_PRIO_INHERIT],
+ [ax_cv_PTHREAD_PRIO_INHERIT],
+ [AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <pthread.h>]],
+ [[int i = PTHREAD_PRIO_INHERIT;]])],
+ [ax_cv_PTHREAD_PRIO_INHERIT=yes],
+ [ax_cv_PTHREAD_PRIO_INHERIT=no])
+ ])
+ AS_IF([test "x$ax_cv_PTHREAD_PRIO_INHERIT" = "xyes" && \
+ test "x$ax_pthread_prio_inherit_defined" != "xyes"],
+ [AC_DEFINE([HAVE_PTHREAD_PRIO_INHERIT], [1], [Have PTHREAD_PRIO_INHERIT.])
+ ax_pthread_prio_inherit_defined=yes
+ ])
+
+ CFLAGS="$ax_pthread_save_CFLAGS"
+ LIBS="$ax_pthread_save_LIBS"
+
+ # More AIX lossage: compile with *_r variant
+ if test "x$GCC" != "xyes"; then
+ case $host_os in
+ aix*)
+ AS_CASE(["x/$CC"],
+ [x*/c89|x*/c89_128|x*/c99|x*/c99_128|x*/cc|x*/cc128|x*/xlc|x*/xlc_v6|x*/xlc128|x*/xlc128_v6],
+ [#handle absolute path differently from PATH based program lookup
+ AS_CASE(["x$CC"],
+ [x/*],
+ [AS_IF([AS_EXECUTABLE_P([${CC}_r])],[PTHREAD_CC="${CC}_r"])],
+ [AC_CHECK_PROGS([PTHREAD_CC],[${CC}_r],[$CC])])])
+ ;;
+ esac
+ fi
+fi
+
+test -n "$PTHREAD_CC" || PTHREAD_CC="$CC"
+
+AC_SUBST([PTHREAD_LIBS])
+AC_SUBST([PTHREAD_CFLAGS])
+AC_SUBST([PTHREAD_CC])
+
+# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
+if test "x$ax_pthread_ok" = "xyes"; then
+ ifelse([$1],,[AC_DEFINE([HAVE_PTHREAD],[1],[Define if you have POSIX threads libraries and header files.])],[$1])
+ :
+else
+ ax_pthread_ok=no
+ $2
+fi
+AC_LANG_POP
+])dnl AX_PTHREAD
diff --git a/more_tests/Makefile b/more_tests/Makefile
deleted file mode 100755
index 286cf0f1..00000000
--- a/more_tests/Makefile
+++ /dev/null
@@ -1,41 +0,0 @@
-# Additional tests to run before releasing a package.
-#
-# Run like:
-# make PACKAGE=/path/to/protobuf-VERSION.tar.gz
-#
-# Some of these tests require tools or make assumptions that may not be
-# available on end-user machines, so these cannot be part of "make check". For
-# example, we test that the headers compile with strict warning settings, but
-# since different compilers produce wildly different warnings we cannot assume
-# that this test will pass everywhere. If we ran it as part of "make check",
-# it could unnecessarily block users from running the real tests just because
-# their compiler produces some extra warnings that probably aren't a big deal.
-# So we run it separately.
-
-all: header_warning_test
-
-clean:
- rm -rf src target header_warning_test.cc header_warning_test.o header_warning_test
-
-# Unpack the package into src, then install it into target.
-PACKAGE=protobuf.tar.gz
-
-src: $(PACKAGE)
- tar zxvf $(PACKAGE)
- mv `basename $(PACKAGE) .tar.gz` src
-
-target: src
- (cd src && ./configure --prefix=$$PWD/../target --disable-shared)
- (cd src && make -j4 check)
- (cd src && make install)
-
-# Verify that headers produce no warnings even under strict settings.
-header_warning_test.cc: target
- ( (cd target/include && find google/protobuf -name '*.h') | \
- awk '{print "#include \""$$1"\""} ' > header_warning_test.cc )
-
-header_warning_test: header_warning_test.cc
- # TODO(kenton): Consider adding -pedantic and -Weffc++. Currently these
- # produce tons of extra warnings so we'll need to do some work first.
- g++ -Itarget/include -Wall -Werror -Wsign-compare -O2 -c header_warning_test.cc
- touch header_warning_test
diff --git a/objectivec/DevTools/full_mac_build.sh b/objectivec/DevTools/full_mac_build.sh
index b34e28fc..c673fcba 100755
--- a/objectivec/DevTools/full_mac_build.sh
+++ b/objectivec/DevTools/full_mac_build.sh
@@ -244,8 +244,7 @@ if [[ "${DO_XCODE_IOS_TESTS}" == "yes" ]] ; then
exit 10
;;
7.* )
- echo "ERROR: The unittests include Swift code that is now Swift 3.0." 1>&2
- echo "ERROR: Xcode 8.0 or higher is required to build the test suite, but the library works with Xcode 7.x." 1>&2
+ echo "ERROR: Xcode 7.x no longer supported for building, please use 8.0 or higher." 1>&2
exit 11
;;
8.0* )
@@ -269,8 +268,20 @@ if [[ "${DO_XCODE_IOS_TESTS}" == "yes" ]] ; then
-disable-concurrent-testing
)
;;
+ 9.3* )
+ XCODEBUILD_TEST_BASE_IOS+=(
+ # Xcode 9.3 chokes targeting iOS 8.x - http://www.openradar.me/39335367
+ -destination "platform=iOS Simulator,name=iPhone 4s,OS=9.0" # 32bit
+ -destination "platform=iOS Simulator,name=iPhone 7,OS=latest" # 64bit
+ # 9.3 also seems to often fail running destinations in parallel
+ -disable-concurrent-testing
+ )
+ ;;
* )
- echo "Time to update the simulator targets for Xcode ${XCODE_VERSION}"
+ echo ""
+ echo "ATTENTION: Time to update the simulator targets for Xcode ${XCODE_VERSION}"
+ echo ""
+ echo "Build aborted!"
exit 2
;;
esac
diff --git a/objectivec/GPBArray.m b/objectivec/GPBArray.m
index f401631d..122e0304 100644
--- a/objectivec/GPBArray.m
+++ b/objectivec/GPBArray.m
@@ -2537,12 +2537,12 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
return [_array countByEnumeratingWithState:state objects:buffer count:len];
}
-- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block {
+- (void)enumerateObjectsUsingBlock:(void (NS_NOESCAPE ^)(id obj, NSUInteger idx, BOOL *stop))block {
[_array enumerateObjectsUsingBlock:block];
}
- (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts
- usingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block {
+ usingBlock:(void (NS_NOESCAPE ^)(id obj, NSUInteger idx, BOOL *stop))block {
[_array enumerateObjectsWithOptions:opts usingBlock:block];
}
diff --git a/objectivec/GPBCodedInputStream.m b/objectivec/GPBCodedInputStream.m
index a8262e5d..dd05ddb4 100644
--- a/objectivec/GPBCodedInputStream.m
+++ b/objectivec/GPBCodedInputStream.m
@@ -63,9 +63,9 @@ static void RaiseException(NSInteger code, NSString *reason) {
NSDictionary *exceptionInfo =
@{ GPBCodedInputStreamUnderlyingErrorKey: error };
- [[[NSException alloc] initWithName:GPBCodedInputStreamException
- reason:reason
- userInfo:exceptionInfo] raise];
+ [[NSException exceptionWithName:GPBCodedInputStreamException
+ reason:reason
+ userInfo:exceptionInfo] raise];
}
static void CheckRecursionLimit(GPBCodedInputStreamState *state) {
diff --git a/objectivec/GPBCodedOutputStream.m b/objectivec/GPBCodedOutputStream.m
index f832e8a6..b846c2fc 100644
--- a/objectivec/GPBCodedOutputStream.m
+++ b/objectivec/GPBCodedOutputStream.m
@@ -942,7 +942,10 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state,
state_.position = length;
} else {
// Write is very big. Let's do it all at once.
- [state_.output write:((uint8_t *)value) + offset maxLength:length];
+ NSInteger written = [state_.output write:((uint8_t *)value) + offset maxLength:length];
+ if (written != (NSInteger)length) {
+ [NSException raise:GPBCodedOutputStreamException_WriteFailed format:@""];
+ }
}
}
}
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 615d2234..ad46ef4f 100644
--- a/objectivec/GPBDescriptor.m
+++ b/objectivec/GPBDescriptor.m
@@ -411,7 +411,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
}
- (NSString *)name {
- return @(name_);
+ return (NSString * _Nonnull)@(name_);
}
- (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber {
@@ -582,7 +582,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
}
- (NSString *)name {
- return @(description_->name);
+ return (NSString * _Nonnull)@(description_->name);
}
- (BOOL)isRequired {
@@ -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.
@@ -998,7 +1015,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
}
- (NSString *)singletonName {
- return @(description_->singletonName);
+ return (NSString * _Nonnull)@(description_->singletonName);
}
- (const char *)singletonNameC {
diff --git a/objectivec/GPBDictionary.m b/objectivec/GPBDictionary.m
index aa21670a..cedf5e54 100644
--- a/objectivec/GPBDictionary.m
+++ b/objectivec/GPBDictionary.m
@@ -12102,14 +12102,14 @@ void GPBDictionaryReadEntry(id mapDictionary,
}
}
-- (void)enumerateKeysAndObjectsUsingBlock:(void (^)(id key,
+- (void)enumerateKeysAndObjectsUsingBlock:(void (NS_NOESCAPE ^)(id key,
id obj,
BOOL *stop))block {
[_dictionary enumerateKeysAndObjectsUsingBlock:block];
}
- (void)enumerateKeysAndObjectsWithOptions:(NSEnumerationOptions)opts
- usingBlock:(void (^)(id key,
+ usingBlock:(void (NS_NOESCAPE ^)(id key,
id obj,
BOOL *stop))block {
[_dictionary enumerateKeysAndObjectsWithOptions:opts usingBlock:block];
diff --git a/objectivec/GPBProtocolBuffers_RuntimeSupport.h b/objectivec/GPBProtocolBuffers_RuntimeSupport.h
index fea75b93..04dde620 100644
--- a/objectivec/GPBProtocolBuffers_RuntimeSupport.h
+++ b/objectivec/GPBProtocolBuffers_RuntimeSupport.h
@@ -31,7 +31,7 @@
// This header is meant to only be used by the generated source, it should not
// be included in code using protocol buffers.
-#import "GPBProtocolBuffers.h"
+#import "GPBBootstrap.h"
#import "GPBDescriptor_PackagePrivate.h"
#import "GPBExtensionInternals.h"
diff --git a/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj b/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj
index 266b05a1..a41be9f2 100644
--- a/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj
+++ b/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj
@@ -37,6 +37,31 @@
8BF8193514A0DDA600A2C982 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; };
F401DC2D1A8D444600FCC765 /* GPBArray.m in Sources */ = {isa = PBXBuildFile; fileRef = F401DC2B1A8D444600FCC765 /* GPBArray.m */; };
F401DC331A8E5C0200FCC765 /* GPBArrayTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F401DC321A8E5C0200FCC765 /* GPBArrayTests.m */; };
+ F40EE4AB206BF8B90071091A /* GPBCompileTest01.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE488206BF8B00071091A /* GPBCompileTest01.m */; };
+ F40EE4AC206BF8B90071091A /* GPBCompileTest02.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE481206BF8AE0071091A /* GPBCompileTest02.m */; };
+ F40EE4AD206BF8B90071091A /* GPBCompileTest03.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE491206BF8B10071091A /* GPBCompileTest03.m */; };
+ F40EE4AE206BF8B90071091A /* GPBCompileTest04.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE47E206BF8AE0071091A /* GPBCompileTest04.m */; };
+ F40EE4AF206BF8B90071091A /* GPBCompileTest05.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE47F206BF8AE0071091A /* GPBCompileTest05.m */; };
+ F40EE4B0206BF8B90071091A /* GPBCompileTest06.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE492206BF8B10071091A /* GPBCompileTest06.m */; };
+ F40EE4B1206BF8B90071091A /* GPBCompileTest07.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE480206BF8AE0071091A /* GPBCompileTest07.m */; };
+ F40EE4B2206BF8B90071091A /* GPBCompileTest08.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE47D206BF8AD0071091A /* GPBCompileTest08.m */; };
+ F40EE4B3206BF8B90071091A /* GPBCompileTest09.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE484206BF8AF0071091A /* GPBCompileTest09.m */; };
+ F40EE4B4206BF8B90071091A /* GPBCompileTest10.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE48C206BF8B00071091A /* GPBCompileTest10.m */; };
+ F40EE4B5206BF8B90071091A /* GPBCompileTest11.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE493206BF8B20071091A /* GPBCompileTest11.m */; };
+ F40EE4B6206BF8B90071091A /* GPBCompileTest12.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE490206BF8B10071091A /* GPBCompileTest12.m */; };
+ F40EE4B7206BF8B90071091A /* GPBCompileTest13.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE483206BF8AF0071091A /* GPBCompileTest13.m */; };
+ F40EE4B8206BF8B90071091A /* GPBCompileTest14.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE48F206BF8B10071091A /* GPBCompileTest14.m */; };
+ F40EE4B9206BF8B90071091A /* GPBCompileTest15.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE489206BF8B00071091A /* GPBCompileTest15.m */; };
+ F40EE4BA206BF8B90071091A /* GPBCompileTest16.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE48B206BF8B00071091A /* GPBCompileTest16.m */; };
+ F40EE4BB206BF8B90071091A /* GPBCompileTest17.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE48D206BF8B00071091A /* GPBCompileTest17.m */; };
+ F40EE4BC206BF8B90071091A /* GPBCompileTest18.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE48E206BF8B10071091A /* GPBCompileTest18.m */; };
+ F40EE4BD206BF8B90071091A /* GPBCompileTest19.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE482206BF8AF0071091A /* GPBCompileTest19.m */; };
+ F40EE4BE206BF8B90071091A /* GPBCompileTest20.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE485206BF8AF0071091A /* GPBCompileTest20.m */; };
+ F40EE4BF206BF8B90071091A /* GPBCompileTest21.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE486206BF8AF0071091A /* GPBCompileTest21.m */; };
+ F40EE4C0206BF8B90071091A /* GPBCompileTest22.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE48A206BF8B00071091A /* GPBCompileTest22.m */; };
+ F40EE4C1206BF8B90071091A /* GPBCompileTest23.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE487206BF8B00071091A /* GPBCompileTest23.m */; };
+ F40EE50B206C06640071091A /* GPBCompileTest24.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE508206C06440071091A /* GPBCompileTest24.m */; };
+ F40EE50C206C06640071091A /* GPBCompileTest25.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE507206C06440071091A /* GPBCompileTest25.m */; };
F41C175D1833D3310064ED4D /* GPBPerfTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F41C175C1833D3310064ED4D /* GPBPerfTests.m */; };
F4353D1D1AB8822D005A6198 /* GPBDescriptorTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F4353D1C1AB8822D005A6198 /* GPBDescriptorTests.m */; };
F4353D231ABB1537005A6198 /* GPBDictionary.m in Sources */ = {isa = PBXBuildFile; fileRef = F4353D211ABB1537005A6198 /* GPBDictionary.m */; };
@@ -158,6 +183,31 @@
F401DC2A1A8D444600FCC765 /* GPBArray.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBArray.h; sourceTree = "<group>"; };
F401DC2B1A8D444600FCC765 /* GPBArray.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBArray.m; sourceTree = "<group>"; };
F401DC321A8E5C0200FCC765 /* GPBArrayTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBArrayTests.m; sourceTree = "<group>"; };
+ F40EE47D206BF8AD0071091A /* GPBCompileTest08.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest08.m; sourceTree = "<group>"; };
+ F40EE47E206BF8AE0071091A /* GPBCompileTest04.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest04.m; sourceTree = "<group>"; };
+ F40EE47F206BF8AE0071091A /* GPBCompileTest05.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest05.m; sourceTree = "<group>"; };
+ F40EE480206BF8AE0071091A /* GPBCompileTest07.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest07.m; sourceTree = "<group>"; };
+ F40EE481206BF8AE0071091A /* GPBCompileTest02.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest02.m; sourceTree = "<group>"; };
+ F40EE482206BF8AF0071091A /* GPBCompileTest19.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest19.m; sourceTree = "<group>"; };
+ F40EE483206BF8AF0071091A /* GPBCompileTest13.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest13.m; sourceTree = "<group>"; };
+ F40EE484206BF8AF0071091A /* GPBCompileTest09.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest09.m; sourceTree = "<group>"; };
+ F40EE485206BF8AF0071091A /* GPBCompileTest20.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest20.m; sourceTree = "<group>"; };
+ F40EE486206BF8AF0071091A /* GPBCompileTest21.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest21.m; sourceTree = "<group>"; };
+ F40EE487206BF8B00071091A /* GPBCompileTest23.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest23.m; sourceTree = "<group>"; };
+ F40EE488206BF8B00071091A /* GPBCompileTest01.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest01.m; sourceTree = "<group>"; };
+ F40EE489206BF8B00071091A /* GPBCompileTest15.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest15.m; sourceTree = "<group>"; };
+ F40EE48A206BF8B00071091A /* GPBCompileTest22.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest22.m; sourceTree = "<group>"; };
+ F40EE48B206BF8B00071091A /* GPBCompileTest16.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest16.m; sourceTree = "<group>"; };
+ F40EE48C206BF8B00071091A /* GPBCompileTest10.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest10.m; sourceTree = "<group>"; };
+ F40EE48D206BF8B00071091A /* GPBCompileTest17.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest17.m; sourceTree = "<group>"; };
+ F40EE48E206BF8B10071091A /* GPBCompileTest18.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest18.m; sourceTree = "<group>"; };
+ F40EE48F206BF8B10071091A /* GPBCompileTest14.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest14.m; sourceTree = "<group>"; };
+ F40EE490206BF8B10071091A /* GPBCompileTest12.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest12.m; sourceTree = "<group>"; };
+ F40EE491206BF8B10071091A /* GPBCompileTest03.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest03.m; sourceTree = "<group>"; };
+ F40EE492206BF8B10071091A /* GPBCompileTest06.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest06.m; sourceTree = "<group>"; };
+ F40EE493206BF8B20071091A /* GPBCompileTest11.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest11.m; sourceTree = "<group>"; };
+ F40EE507206C06440071091A /* GPBCompileTest25.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest25.m; sourceTree = "<group>"; };
+ F40EE508206C06440071091A /* GPBCompileTest24.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest24.m; sourceTree = "<group>"; };
F41C175C1833D3310064ED4D /* GPBPerfTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBPerfTests.m; sourceTree = "<group>"; };
F4353D1C1AB8822D005A6198 /* GPBDescriptorTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBDescriptorTests.m; sourceTree = "<group>"; };
F4353D201ABB1537005A6198 /* GPBDictionary.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBDictionary.h; sourceTree = "<group>"; };
@@ -395,6 +445,31 @@
F401DC321A8E5C0200FCC765 /* GPBArrayTests.m */,
7461B69B0F94FDF800A0C422 /* GPBCodedInputStreamTests.m */,
7461B69D0F94FDF800A0C422 /* GPBCodedOuputStreamTests.m */,
+ F40EE488206BF8B00071091A /* GPBCompileTest01.m */,
+ F40EE481206BF8AE0071091A /* GPBCompileTest02.m */,
+ F40EE491206BF8B10071091A /* GPBCompileTest03.m */,
+ F40EE47E206BF8AE0071091A /* GPBCompileTest04.m */,
+ F40EE47F206BF8AE0071091A /* GPBCompileTest05.m */,
+ F40EE492206BF8B10071091A /* GPBCompileTest06.m */,
+ F40EE480206BF8AE0071091A /* GPBCompileTest07.m */,
+ F40EE47D206BF8AD0071091A /* GPBCompileTest08.m */,
+ F40EE484206BF8AF0071091A /* GPBCompileTest09.m */,
+ F40EE48C206BF8B00071091A /* GPBCompileTest10.m */,
+ F40EE493206BF8B20071091A /* GPBCompileTest11.m */,
+ F40EE490206BF8B10071091A /* GPBCompileTest12.m */,
+ F40EE483206BF8AF0071091A /* GPBCompileTest13.m */,
+ F40EE48F206BF8B10071091A /* GPBCompileTest14.m */,
+ F40EE489206BF8B00071091A /* GPBCompileTest15.m */,
+ F40EE48B206BF8B00071091A /* GPBCompileTest16.m */,
+ F40EE48D206BF8B00071091A /* GPBCompileTest17.m */,
+ F40EE48E206BF8B10071091A /* GPBCompileTest18.m */,
+ F40EE482206BF8AF0071091A /* GPBCompileTest19.m */,
+ F40EE485206BF8AF0071091A /* GPBCompileTest20.m */,
+ F40EE486206BF8AF0071091A /* GPBCompileTest21.m */,
+ F40EE48A206BF8B00071091A /* GPBCompileTest22.m */,
+ F40EE487206BF8B00071091A /* GPBCompileTest23.m */,
+ F40EE508206C06440071091A /* GPBCompileTest24.m */,
+ F40EE507206C06440071091A /* GPBCompileTest25.m */,
5102DABB1891A052002037B6 /* GPBConcurrencyTests.m */,
F4353D1C1AB8822D005A6198 /* GPBDescriptorTests.m */,
F4C4B9E21E1D974F00D3B61D /* GPBDictionaryTests.m */,
@@ -562,7 +637,7 @@
attributes = {
LastSwiftUpdateCheck = 0710;
LastTestingUpgradeCheck = 0600;
- LastUpgradeCheck = 0900;
+ LastUpgradeCheck = 0930;
TargetAttributes = {
8BBEA4A5147C727100C4ADB7 = {
LastSwiftMigration = 0800;
@@ -661,28 +736,53 @@
buildActionMask = 2147483647;
files = (
8BBEA4A9147C727D00C4ADB7 /* GPBCodedInputStreamTests.m in Sources */,
+ F40EE50B206C06640071091A /* GPBCompileTest24.m in Sources */,
+ F40EE4BE206BF8B90071091A /* GPBCompileTest20.m in Sources */,
F401DC331A8E5C0200FCC765 /* GPBArrayTests.m in Sources */,
+ F40EE4B4206BF8B90071091A /* GPBCompileTest10.m in Sources */,
F4353D361AC06F10005A6198 /* GPBDictionaryTests+Int64.m in Sources */,
+ F40EE4C0206BF8B90071091A /* GPBCompileTest22.m in Sources */,
+ F40EE4B2206BF8B90071091A /* GPBCompileTest08.m in Sources */,
+ F40EE4BB206BF8B90071091A /* GPBCompileTest17.m in Sources */,
F4353D391AC06F10005A6198 /* GPBDictionaryTests+UInt64.m in Sources */,
8BBEA4AA147C727D00C4ADB7 /* GPBCodedOuputStreamTests.m in Sources */,
+ F40EE4C1206BF8B90071091A /* GPBCompileTest23.m in Sources */,
8BBEA4AC147C727D00C4ADB7 /* GPBMessageTests.m in Sources */,
F4B51B1E1BBC610700744318 /* GPBObjectiveCPlusPlusTest.mm in Sources */,
+ F40EE4BD206BF8B90071091A /* GPBCompileTest19.m in Sources */,
+ F40EE4B0206BF8B90071091A /* GPBCompileTest06.m in Sources */,
+ F40EE4B6206BF8B90071091A /* GPBCompileTest12.m in Sources */,
F4487C7F1AAF62CD00531423 /* GPBMessageTests+Serialization.m in Sources */,
+ F40EE4AD206BF8B90071091A /* GPBCompileTest03.m in Sources */,
+ F40EE4BC206BF8B90071091A /* GPBCompileTest18.m in Sources */,
+ F40EE4B7206BF8B90071091A /* GPBCompileTest13.m in Sources */,
+ F40EE4B9206BF8B90071091A /* GPBCompileTest15.m in Sources */,
+ F40EE4B1206BF8B90071091A /* GPBCompileTest07.m in Sources */,
8B4248DC1A92933A00BC1EC6 /* GPBWellKnownTypesTest.m in Sources */,
+ F40EE4BF206BF8B90071091A /* GPBCompileTest21.m in Sources */,
+ F40EE4B5206BF8B90071091A /* GPBCompileTest11.m in Sources */,
F4F8D8831D789FD9002CE128 /* GPBUnittestProtos2.m in Sources */,
F4353D1D1AB8822D005A6198 /* GPBDescriptorTests.m in Sources */,
8B4248BB1A8C256A00BC1EC6 /* GPBSwiftTests.swift in Sources */,
+ F40EE50C206C06640071091A /* GPBCompileTest25.m in Sources */,
F4584D821ECCB52A00803AB6 /* GPBExtensionRegistryTest.m in Sources */,
5102DABC1891A073002037B6 /* GPBConcurrencyTests.m in Sources */,
F4487C751AADF7F500531423 /* GPBMessageTests+Runtime.m in Sources */,
+ F40EE4AC206BF8B90071091A /* GPBCompileTest02.m in Sources */,
F4353D351AC06F10005A6198 /* GPBDictionaryTests+Int32.m in Sources */,
+ F40EE4AF206BF8B90071091A /* GPBCompileTest05.m in Sources */,
+ F40EE4B8206BF8B90071091A /* GPBCompileTest14.m in Sources */,
8BBEA4B0147C727D00C4ADB7 /* GPBTestUtilities.m in Sources */,
+ F40EE4AE206BF8B90071091A /* GPBCompileTest04.m in Sources */,
+ F40EE4BA206BF8B90071091A /* GPBCompileTest16.m in Sources */,
F41C175D1833D3310064ED4D /* GPBPerfTests.m in Sources */,
F4353D341AC06F10005A6198 /* GPBDictionaryTests+Bool.m in Sources */,
F4487C831AAF6AB300531423 /* GPBMessageTests+Merge.m in Sources */,
+ F40EE4AB206BF8B90071091A /* GPBCompileTest01.m in Sources */,
8BBEA4B6147C727D00C4ADB7 /* GPBUnknownFieldSetTest.m in Sources */,
F4353D371AC06F10005A6198 /* GPBDictionaryTests+String.m in Sources */,
F4353D381AC06F10005A6198 /* GPBDictionaryTests+UInt32.m in Sources */,
+ F40EE4B3206BF8B90071091A /* GPBCompileTest09.m in Sources */,
8BBEA4B7147C727D00C4ADB7 /* GPBUtilitiesTests.m in Sources */,
F4C4B9E41E1D976300D3B61D /* GPBDictionaryTests.m in Sources */,
8BBEA4B8147C727D00C4ADB7 /* GPBWireFormatTests.m in Sources */,
@@ -718,6 +818,7 @@
7461B52F0F94FAFA00A0C422 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ CLANG_ENABLE_OBJC_WEAK = YES;
COMBINE_HIDPI_IMAGES = YES;
HEADER_SEARCH_PATHS = "$(SRCROOT)";
PRODUCT_NAME = ProtocolBuffers;
@@ -727,6 +828,7 @@
7461B5300F94FAFA00A0C422 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ CLANG_ENABLE_OBJC_WEAK = YES;
COMBINE_HIDPI_IMAGES = YES;
HEADER_SEARCH_PATHS = "$(SRCROOT)";
PRODUCT_NAME = ProtocolBuffers;
@@ -737,6 +839,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_WEAK = YES;
COMBINE_HIDPI_IMAGES = YES;
HEADER_SEARCH_PATHS = (
"${PROJECT_DERIVED_FILE_DIR}/protos",
@@ -763,6 +866,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_WEAK = YES;
COMBINE_HIDPI_IMAGES = YES;
HEADER_SEARCH_PATHS = (
"${PROJECT_DERIVED_FILE_DIR}/protos",
@@ -925,6 +1029,7 @@
F4487C4F1A9F8E0200531423 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ CLANG_ENABLE_OBJC_WEAK = YES;
COMBINE_HIDPI_IMAGES = YES;
HEADER_SEARCH_PATHS = "$(SRCROOT)";
PRODUCT_NAME = TestSingleSourceBuild;
@@ -934,6 +1039,7 @@
F4487C501A9F8E0200531423 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ CLANG_ENABLE_OBJC_WEAK = YES;
COMBINE_HIDPI_IMAGES = YES;
HEADER_SEARCH_PATHS = "$(SRCROOT)";
PRODUCT_NAME = TestSingleSourceBuild;
@@ -943,12 +1049,14 @@
F45BBC151B0CE3C6002D064D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ CLANG_ENABLE_OBJC_WEAK = YES;
};
name = Debug;
};
F45BBC161B0CE3C6002D064D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ CLANG_ENABLE_OBJC_WEAK = YES;
};
name = Release;
};
diff --git a/objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
new file mode 100644
index 00000000..18d98100
--- /dev/null
+++ b/objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>IDEDidComputeMac32BitWarning</key>
+ <true/>
+</dict>
+</plist>
diff --git a/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme b/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme
index d3c29389..6653a1b0 100644
--- a/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme
+++ b/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "0900"
+ LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -26,7 +26,6 @@
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
- language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
@@ -301,7 +300,6 @@
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
- language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
diff --git a/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme b/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme
index e7fb8215..328771b8 100644
--- a/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme
+++ b/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "0900"
+ LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -54,9 +54,8 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
- language = ""
- shouldUseLaunchSchemeArgsEnv = "YES"
- codeCoverageEnabled = "YES">
+ codeCoverageEnabled = "YES"
+ shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
@@ -90,7 +89,6 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
- language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
diff --git a/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj b/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj
index 9333ea7d..470652d0 100644
--- a/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj
+++ b/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj
@@ -25,13 +25,6 @@
8B79657B14992E3F002FFBFC /* GPBRootObject.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B79657914992E3E002FFBFC /* GPBRootObject.m */; };
8B8B615D17DF7056002EE618 /* GPBARCUnittestProtos.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B8B615C17DF7056002EE618 /* GPBARCUnittestProtos.m */; settings = {COMPILER_FLAGS = "-fobjc-arc"; }; };
8B96157414C8C38C00A2AC0B /* GPBDescriptor.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B96157314C8C38C00A2AC0B /* GPBDescriptor.m */; };
- 8B9742331A89D19F00DCE92C /* LaunchScreen.xib in Resources */ = {isa = PBXBuildFile; fileRef = 8B9742321A89D19F00DCE92C /* LaunchScreen.xib */; };
- 8B9742431A8AAA7800DCE92C /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8B9742421A8AAA7800DCE92C /* CoreGraphics.framework */; };
- 8B9A5EA61831993600A9D33B /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; };
- 8B9A5EA81831993600A9D33B /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8B9A5E9F1831913D00A9D33B /* UIKit.framework */; };
- 8B9A5EAE1831993600A9D33B /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 8B9A5EAC1831993600A9D33B /* InfoPlist.strings */; };
- 8B9A5EB41831993600A9D33B /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B9A5EB31831993600A9D33B /* AppDelegate.m */; };
- 8B9A5EB61831993600A9D33B /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 8B9A5EB51831993600A9D33B /* Images.xcassets */; };
8B9A5EEC18330A0F00A9D33B /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8B9A5E9F1831913D00A9D33B /* UIKit.framework */; };
8BBEA4A9147C727D00C4ADB7 /* GPBCodedInputStreamTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 7461B69B0F94FDF800A0C422 /* GPBCodedInputStreamTests.m */; };
8BBEA4AA147C727D00C4ADB7 /* GPBCodedOuputStreamTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 7461B69D0F94FDF800A0C422 /* GPBCodedOuputStreamTests.m */; };
@@ -44,6 +37,31 @@
8BD3981F14BE59D70081D629 /* GPBUnittestProtos.m in Sources */ = {isa = PBXBuildFile; fileRef = 8BD3981E14BE59D70081D629 /* GPBUnittestProtos.m */; };
8BF8193514A0DDA600A2C982 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; };
F401DC351A8E5C6F00FCC765 /* GPBArrayTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F401DC341A8E5C6F00FCC765 /* GPBArrayTests.m */; };
+ F40EE4F0206BF91E0071091A /* GPBCompileTest01.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4CD206BF9170071091A /* GPBCompileTest01.m */; };
+ F40EE4F1206BF91E0071091A /* GPBCompileTest02.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C6206BF9170071091A /* GPBCompileTest02.m */; };
+ F40EE4F2206BF91E0071091A /* GPBCompileTest03.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D6206BF9190071091A /* GPBCompileTest03.m */; };
+ F40EE4F3206BF91E0071091A /* GPBCompileTest04.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C3206BF9160071091A /* GPBCompileTest04.m */; };
+ F40EE4F4206BF91E0071091A /* GPBCompileTest05.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C4206BF9160071091A /* GPBCompileTest05.m */; };
+ F40EE4F5206BF91E0071091A /* GPBCompileTest06.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D7206BF9190071091A /* GPBCompileTest06.m */; };
+ F40EE4F6206BF91E0071091A /* GPBCompileTest07.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C5206BF9170071091A /* GPBCompileTest07.m */; };
+ F40EE4F7206BF91E0071091A /* GPBCompileTest08.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C2206BF9160071091A /* GPBCompileTest08.m */; };
+ F40EE4F8206BF91E0071091A /* GPBCompileTest09.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C9206BF9170071091A /* GPBCompileTest09.m */; };
+ F40EE4F9206BF91E0071091A /* GPBCompileTest10.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D1206BF9180071091A /* GPBCompileTest10.m */; };
+ F40EE4FA206BF91E0071091A /* GPBCompileTest11.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D8206BF9190071091A /* GPBCompileTest11.m */; };
+ F40EE4FB206BF91E0071091A /* GPBCompileTest12.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D5206BF9180071091A /* GPBCompileTest12.m */; };
+ F40EE4FC206BF91E0071091A /* GPBCompileTest13.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C8206BF9170071091A /* GPBCompileTest13.m */; };
+ F40EE4FD206BF91E0071091A /* GPBCompileTest14.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D4206BF9180071091A /* GPBCompileTest14.m */; };
+ F40EE4FE206BF91E0071091A /* GPBCompileTest15.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4CE206BF9170071091A /* GPBCompileTest15.m */; };
+ F40EE4FF206BF91E0071091A /* GPBCompileTest16.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D0206BF9180071091A /* GPBCompileTest16.m */; };
+ F40EE500206BF91E0071091A /* GPBCompileTest17.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D2206BF9180071091A /* GPBCompileTest17.m */; };
+ F40EE501206BF91E0071091A /* GPBCompileTest18.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D3206BF9180071091A /* GPBCompileTest18.m */; };
+ F40EE502206BF91E0071091A /* GPBCompileTest19.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C7206BF9170071091A /* GPBCompileTest19.m */; };
+ F40EE503206BF91E0071091A /* GPBCompileTest20.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4CA206BF9170071091A /* GPBCompileTest20.m */; };
+ F40EE504206BF91E0071091A /* GPBCompileTest21.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4CB206BF9170071091A /* GPBCompileTest21.m */; };
+ F40EE505206BF91E0071091A /* GPBCompileTest22.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4CF206BF9170071091A /* GPBCompileTest22.m */; };
+ F40EE506206BF91E0071091A /* GPBCompileTest23.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4CC206BF9170071091A /* GPBCompileTest23.m */; };
+ F40EE511206C068D0071091A /* GPBCompileTest24.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE50E206C06880071091A /* GPBCompileTest24.m */; };
+ F40EE512206C068D0071091A /* GPBCompileTest25.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE50D206C06880071091A /* GPBCompileTest25.m */; };
F41C175D1833D3310064ED4D /* GPBPerfTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F41C175C1833D3310064ED4D /* GPBPerfTests.m */; };
F4353D1F1AB88243005A6198 /* GPBDescriptorTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F4353D1E1AB88243005A6198 /* GPBDescriptorTests.m */; };
F4353D271ABB156F005A6198 /* GPBDictionary.m in Sources */ = {isa = PBXBuildFile; fileRef = F4353D251ABB156F005A6198 /* GPBDictionary.m */; };
@@ -79,13 +97,6 @@
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
- 8B9A5ED01831994600A9D33B /* PBXContainerItemProxy */ = {
- isa = PBXContainerItemProxy;
- containerPortal = 29B97313FDCFA39411CA2CEA /* Project object */;
- proxyType = 1;
- remoteGlobalIDString = 8B9A5EA41831993600A9D33B;
- remoteInfo = iOSTestHarness;
- };
8BBEA4BC147C729A00C4ADB7 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 29B97313FDCFA39411CA2CEA /* Project object */;
@@ -163,14 +174,8 @@
8B8B615C17DF7056002EE618 /* GPBARCUnittestProtos.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBARCUnittestProtos.m; sourceTree = "<group>"; };
8B96157214C8B06000A2AC0B /* GPBDescriptor.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBDescriptor.h; sourceTree = "<group>"; };
8B96157314C8C38C00A2AC0B /* GPBDescriptor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBDescriptor.m; sourceTree = "<group>"; };
- 8B9742321A89D19F00DCE92C /* LaunchScreen.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = LaunchScreen.xib; sourceTree = "<group>"; };
8B9742421A8AAA7800DCE92C /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; };
8B9A5E9F1831913D00A9D33B /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
- 8B9A5EA51831993600A9D33B /* iOSTestHarness.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = iOSTestHarness.app; sourceTree = BUILT_PRODUCTS_DIR; };
- 8B9A5EAB1831993600A9D33B /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
- 8B9A5EAD1831993600A9D33B /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = "<group>"; };
- 8B9A5EB31831993600A9D33B /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; };
- 8B9A5EB51831993600A9D33B /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = "<group>"; };
8BBD9DB016DD1DC8008E1EC1 /* unittest_lite.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = unittest_lite.proto; path = ../../src/google/protobuf/unittest_lite.proto; sourceTree = "<group>"; };
8BBEA4A6147C727100C4ADB7 /* UnitTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = UnitTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
8BCF338814ED799900BC5317 /* GPBProtocolBuffers.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GPBProtocolBuffers.m; sourceTree = "<group>"; };
@@ -178,6 +183,31 @@
8BD3981E14BE59D70081D629 /* GPBUnittestProtos.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBUnittestProtos.m; sourceTree = "<group>"; };
8BEB5AE01498033E0078BF9D /* GPBRuntimeTypes.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBRuntimeTypes.h; sourceTree = "<group>"; };
F401DC341A8E5C6F00FCC765 /* GPBArrayTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBArrayTests.m; sourceTree = "<group>"; };
+ F40EE4C2206BF9160071091A /* GPBCompileTest08.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest08.m; sourceTree = "<group>"; };
+ F40EE4C3206BF9160071091A /* GPBCompileTest04.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest04.m; sourceTree = "<group>"; };
+ F40EE4C4206BF9160071091A /* GPBCompileTest05.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest05.m; sourceTree = "<group>"; };
+ F40EE4C5206BF9170071091A /* GPBCompileTest07.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest07.m; sourceTree = "<group>"; };
+ F40EE4C6206BF9170071091A /* GPBCompileTest02.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest02.m; sourceTree = "<group>"; };
+ F40EE4C7206BF9170071091A /* GPBCompileTest19.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest19.m; sourceTree = "<group>"; };
+ F40EE4C8206BF9170071091A /* GPBCompileTest13.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest13.m; sourceTree = "<group>"; };
+ F40EE4C9206BF9170071091A /* GPBCompileTest09.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest09.m; sourceTree = "<group>"; };
+ F40EE4CA206BF9170071091A /* GPBCompileTest20.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest20.m; sourceTree = "<group>"; };
+ F40EE4CB206BF9170071091A /* GPBCompileTest21.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest21.m; sourceTree = "<group>"; };
+ F40EE4CC206BF9170071091A /* GPBCompileTest23.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest23.m; sourceTree = "<group>"; };
+ F40EE4CD206BF9170071091A /* GPBCompileTest01.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest01.m; sourceTree = "<group>"; };
+ F40EE4CE206BF9170071091A /* GPBCompileTest15.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest15.m; sourceTree = "<group>"; };
+ F40EE4CF206BF9170071091A /* GPBCompileTest22.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest22.m; sourceTree = "<group>"; };
+ F40EE4D0206BF9180071091A /* GPBCompileTest16.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest16.m; sourceTree = "<group>"; };
+ F40EE4D1206BF9180071091A /* GPBCompileTest10.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest10.m; sourceTree = "<group>"; };
+ F40EE4D2206BF9180071091A /* GPBCompileTest17.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest17.m; sourceTree = "<group>"; };
+ F40EE4D3206BF9180071091A /* GPBCompileTest18.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest18.m; sourceTree = "<group>"; };
+ F40EE4D4206BF9180071091A /* GPBCompileTest14.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest14.m; sourceTree = "<group>"; };
+ F40EE4D5206BF9180071091A /* GPBCompileTest12.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest12.m; sourceTree = "<group>"; };
+ F40EE4D6206BF9190071091A /* GPBCompileTest03.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest03.m; sourceTree = "<group>"; };
+ F40EE4D7206BF9190071091A /* GPBCompileTest06.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest06.m; sourceTree = "<group>"; };
+ F40EE4D8206BF9190071091A /* GPBCompileTest11.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest11.m; sourceTree = "<group>"; };
+ F40EE50D206C06880071091A /* GPBCompileTest25.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest25.m; sourceTree = "<group>"; };
+ F40EE50E206C06880071091A /* GPBCompileTest24.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest24.m; sourceTree = "<group>"; };
F41C175C1833D3310064ED4D /* GPBPerfTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBPerfTests.m; sourceTree = "<group>"; };
F4353D1E1AB88243005A6198 /* GPBDescriptorTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBDescriptorTests.m; sourceTree = "<group>"; };
F4353D241ABB156F005A6198 /* GPBDictionary.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBDictionary.h; sourceTree = "<group>"; };
@@ -251,16 +281,6 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
- 8B9A5EA21831993600A9D33B /* Frameworks */ = {
- isa = PBXFrameworksBuildPhase;
- buildActionMask = 2147483647;
- files = (
- 8B9742431A8AAA7800DCE92C /* CoreGraphics.framework in Frameworks */,
- 8B9A5EA81831993600A9D33B /* UIKit.framework in Frameworks */,
- 8B9A5EA61831993600A9D33B /* Foundation.framework in Frameworks */,
- );
- runOnlyForDeploymentPostprocessing = 0;
- };
8BBEA4A3147C727100C4ADB7 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
@@ -303,7 +323,6 @@
children = (
7461B52E0F94FAF800A0C422 /* libProtocolBuffers.a */,
8BBEA4A6147C727100C4ADB7 /* UnitTests.xctest */,
- 8B9A5EA51831993600A9D33B /* iOSTestHarness.app */,
F4487C6E1A9F8F8100531423 /* libTestSingleSourceBuild.a */,
);
name = Products;
@@ -425,7 +444,6 @@
7461B6940F94FDDD00A0C422 /* Tests */ = {
isa = PBXGroup;
children = (
- 8B9A5EA91831993600A9D33B /* iOSTestHarness */,
8B4248B71A8BDD9600BC1EC6 /* protobuf */,
8B210CCD159383D60032D72D /* golden_message */,
8B210CCF159386920032D72D /* golden_packed_fields_message */,
@@ -433,6 +451,31 @@
F401DC341A8E5C6F00FCC765 /* GPBArrayTests.m */,
7461B69B0F94FDF800A0C422 /* GPBCodedInputStreamTests.m */,
7461B69D0F94FDF800A0C422 /* GPBCodedOuputStreamTests.m */,
+ F40EE4CD206BF9170071091A /* GPBCompileTest01.m */,
+ F40EE4C6206BF9170071091A /* GPBCompileTest02.m */,
+ F40EE4D6206BF9190071091A /* GPBCompileTest03.m */,
+ F40EE4C3206BF9160071091A /* GPBCompileTest04.m */,
+ F40EE4C4206BF9160071091A /* GPBCompileTest05.m */,
+ F40EE4D7206BF9190071091A /* GPBCompileTest06.m */,
+ F40EE4C5206BF9170071091A /* GPBCompileTest07.m */,
+ F40EE4C2206BF9160071091A /* GPBCompileTest08.m */,
+ F40EE4C9206BF9170071091A /* GPBCompileTest09.m */,
+ F40EE4D1206BF9180071091A /* GPBCompileTest10.m */,
+ F40EE4D8206BF9190071091A /* GPBCompileTest11.m */,
+ F40EE4D5206BF9180071091A /* GPBCompileTest12.m */,
+ F40EE4C8206BF9170071091A /* GPBCompileTest13.m */,
+ F40EE4D4206BF9180071091A /* GPBCompileTest14.m */,
+ F40EE4CE206BF9170071091A /* GPBCompileTest15.m */,
+ F40EE4D0206BF9180071091A /* GPBCompileTest16.m */,
+ F40EE4D2206BF9180071091A /* GPBCompileTest17.m */,
+ F40EE4D3206BF9180071091A /* GPBCompileTest18.m */,
+ F40EE4C7206BF9170071091A /* GPBCompileTest19.m */,
+ F40EE4CA206BF9170071091A /* GPBCompileTest20.m */,
+ F40EE4CB206BF9170071091A /* GPBCompileTest21.m */,
+ F40EE4CF206BF9170071091A /* GPBCompileTest22.m */,
+ F40EE4CC206BF9170071091A /* GPBCompileTest23.m */,
+ F40EE50E206C06880071091A /* GPBCompileTest24.m */,
+ F40EE50D206C06880071091A /* GPBCompileTest25.m */,
5102DABB1891A052002037B6 /* GPBConcurrencyTests.m */,
F4353D1E1AB88243005A6198 /* GPBDescriptorTests.m */,
F4C4B9E51E1D97BB00D3B61D /* GPBDictionaryTests.m */,
@@ -482,26 +525,6 @@
path = Tests;
sourceTree = "<group>";
};
- 8B9A5EA91831993600A9D33B /* iOSTestHarness */ = {
- isa = PBXGroup;
- children = (
- 8B9A5EB31831993600A9D33B /* AppDelegate.m */,
- 8B9A5EB51831993600A9D33B /* Images.xcassets */,
- 8B9A5EAA1831993600A9D33B /* Supporting Files */,
- 8B9742321A89D19F00DCE92C /* LaunchScreen.xib */,
- );
- path = iOSTestHarness;
- sourceTree = "<group>";
- };
- 8B9A5EAA1831993600A9D33B /* Supporting Files */ = {
- isa = PBXGroup;
- children = (
- 8B9A5EAB1831993600A9D33B /* Info.plist */,
- 8B9A5EAC1831993600A9D33B /* InfoPlist.strings */,
- );
- name = "Supporting Files";
- sourceTree = "<group>";
- };
8BCF334414ED727300BC5317 /* Support */ = {
isa = PBXGroup;
children = (
@@ -576,23 +599,6 @@
productReference = 7461B52E0F94FAF800A0C422 /* libProtocolBuffers.a */;
productType = "com.apple.product-type.library.static";
};
- 8B9A5EA41831993600A9D33B /* iOSTestHarness */ = {
- isa = PBXNativeTarget;
- buildConfigurationList = 8B9A5ECA1831993600A9D33B /* Build configuration list for PBXNativeTarget "iOSTestHarness" */;
- buildPhases = (
- 8B9A5EA11831993600A9D33B /* Sources */,
- 8B9A5EA21831993600A9D33B /* Frameworks */,
- 8B9A5EA31831993600A9D33B /* Resources */,
- );
- buildRules = (
- );
- dependencies = (
- );
- name = iOSTestHarness;
- productName = iOSTestHarness;
- productReference = 8B9A5EA51831993600A9D33B /* iOSTestHarness.app */;
- productType = "com.apple.product-type.application";
- };
8BBEA4A5147C727100C4ADB7 /* UnitTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 8BBEA4BA147C728600C4ADB7 /* Build configuration list for PBXNativeTarget "UnitTests" */;
@@ -607,7 +613,6 @@
dependencies = (
8BBEA4BD147C729A00C4ADB7 /* PBXTargetDependency */,
F45BBC131B0CDBBA002D064D /* PBXTargetDependency */,
- 8B9A5ED11831994600A9D33B /* PBXTargetDependency */,
);
name = UnitTests;
productName = UnitTests;
@@ -639,7 +644,7 @@
attributes = {
LastSwiftUpdateCheck = 0710;
LastTestingUpgradeCheck = 0600;
- LastUpgradeCheck = 0900;
+ LastUpgradeCheck = 0930;
TargetAttributes = {
8BBEA4A5147C727100C4ADB7 = {
LastSwiftMigration = 0800;
@@ -663,7 +668,6 @@
targets = (
7461B52D0F94FAF800A0C422 /* ProtocolBuffers */,
8BBEA4A5147C727100C4ADB7 /* UnitTests */,
- 8B9A5EA41831993600A9D33B /* iOSTestHarness */,
F4487C551A9F8F8100531423 /* TestSingleSourceBuild */,
F45BBC0E1B0CDB50002D064D /* Compile Unittest Protos */,
);
@@ -671,16 +675,6 @@
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
- 8B9A5EA31831993600A9D33B /* Resources */ = {
- isa = PBXResourcesBuildPhase;
- buildActionMask = 2147483647;
- files = (
- 8B9A5EAE1831993600A9D33B /* InfoPlist.strings in Resources */,
- 8B9A5EB61831993600A9D33B /* Images.xcassets in Resources */,
- 8B9742331A89D19F00DCE92C /* LaunchScreen.xib in Resources */,
- );
- runOnlyForDeploymentPostprocessing = 0;
- };
8BBEA4A1147C727100C4ADB7 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
@@ -744,41 +738,58 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
- 8B9A5EA11831993600A9D33B /* Sources */ = {
- isa = PBXSourcesBuildPhase;
- buildActionMask = 2147483647;
- files = (
- 8B9A5EB41831993600A9D33B /* AppDelegate.m in Sources */,
- );
- runOnlyForDeploymentPostprocessing = 0;
- };
8BBEA4A2147C727100C4ADB7 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
8BBEA4A9147C727D00C4ADB7 /* GPBCodedInputStreamTests.m in Sources */,
+ F40EE511206C068D0071091A /* GPBCompileTest24.m in Sources */,
+ F40EE503206BF91E0071091A /* GPBCompileTest20.m in Sources */,
F401DC351A8E5C6F00FCC765 /* GPBArrayTests.m in Sources */,
+ F40EE4F9206BF91E0071091A /* GPBCompileTest10.m in Sources */,
F4353D441AC06F31005A6198 /* GPBDictionaryTests+Int64.m in Sources */,
+ F40EE505206BF91E0071091A /* GPBCompileTest22.m in Sources */,
+ F40EE4F7206BF91E0071091A /* GPBCompileTest08.m in Sources */,
+ F40EE500206BF91E0071091A /* GPBCompileTest17.m in Sources */,
F4353D471AC06F31005A6198 /* GPBDictionaryTests+UInt64.m in Sources */,
8BBEA4AA147C727D00C4ADB7 /* GPBCodedOuputStreamTests.m in Sources */,
+ F40EE506206BF91E0071091A /* GPBCompileTest23.m in Sources */,
8BBEA4AC147C727D00C4ADB7 /* GPBMessageTests.m in Sources */,
F4487C811AAF62FC00531423 /* GPBMessageTests+Serialization.m in Sources */,
+ F40EE502206BF91E0071091A /* GPBCompileTest19.m in Sources */,
+ F40EE4F5206BF91E0071091A /* GPBCompileTest06.m in Sources */,
+ F40EE4FB206BF91E0071091A /* GPBCompileTest12.m in Sources */,
8B4248E61A929C9900BC1EC6 /* GPBWellKnownTypesTest.m in Sources */,
+ F40EE4F2206BF91E0071091A /* GPBCompileTest03.m in Sources */,
+ F40EE501206BF91E0071091A /* GPBCompileTest18.m in Sources */,
+ F40EE4FC206BF91E0071091A /* GPBCompileTest13.m in Sources */,
+ F40EE4FE206BF91E0071091A /* GPBCompileTest15.m in Sources */,
+ F40EE4F6206BF91E0071091A /* GPBCompileTest07.m in Sources */,
F4353D1F1AB88243005A6198 /* GPBDescriptorTests.m in Sources */,
+ F40EE504206BF91E0071091A /* GPBCompileTest21.m in Sources */,
+ F40EE4FA206BF91E0071091A /* GPBCompileTest11.m in Sources */,
F4F8D8861D78A193002CE128 /* GPBUnittestProtos2.m in Sources */,
F4B51B1C1BBC5C7100744318 /* GPBObjectiveCPlusPlusTest.mm in Sources */,
8B4248B41A8BD96E00BC1EC6 /* GPBSwiftTests.swift in Sources */,
+ F40EE512206C068D0071091A /* GPBCompileTest25.m in Sources */,
F4584D831ECCB53600803AB6 /* GPBExtensionRegistryTest.m in Sources */,
5102DABC1891A073002037B6 /* GPBConcurrencyTests.m in Sources */,
F4487C771AADF84900531423 /* GPBMessageTests+Runtime.m in Sources */,
+ F40EE4F1206BF91E0071091A /* GPBCompileTest02.m in Sources */,
F4353D431AC06F31005A6198 /* GPBDictionaryTests+Int32.m in Sources */,
+ F40EE4F4206BF91E0071091A /* GPBCompileTest05.m in Sources */,
+ F40EE4FD206BF91E0071091A /* GPBCompileTest14.m in Sources */,
8BBEA4B0147C727D00C4ADB7 /* GPBTestUtilities.m in Sources */,
+ F40EE4F3206BF91E0071091A /* GPBCompileTest04.m in Sources */,
+ F40EE4FF206BF91E0071091A /* GPBCompileTest16.m in Sources */,
F41C175D1833D3310064ED4D /* GPBPerfTests.m in Sources */,
F4353D421AC06F31005A6198 /* GPBDictionaryTests+Bool.m in Sources */,
F4487C851AAF6AC500531423 /* GPBMessageTests+Merge.m in Sources */,
+ F40EE4F0206BF91E0071091A /* GPBCompileTest01.m in Sources */,
8BBEA4B6147C727D00C4ADB7 /* GPBUnknownFieldSetTest.m in Sources */,
F4353D451AC06F31005A6198 /* GPBDictionaryTests+String.m in Sources */,
F4353D461AC06F31005A6198 /* GPBDictionaryTests+UInt32.m in Sources */,
+ F40EE4F8206BF91E0071091A /* GPBCompileTest09.m in Sources */,
8BBEA4B7147C727D00C4ADB7 /* GPBUtilitiesTests.m in Sources */,
F4C4B9E71E1D97BF00D3B61D /* GPBDictionaryTests.m in Sources */,
8BBEA4B8147C727D00C4ADB7 /* GPBWireFormatTests.m in Sources */,
@@ -798,11 +809,6 @@
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
- 8B9A5ED11831994600A9D33B /* PBXTargetDependency */ = {
- isa = PBXTargetDependency;
- target = 8B9A5EA41831993600A9D33B /* iOSTestHarness */;
- targetProxy = 8B9A5ED01831994600A9D33B /* PBXContainerItemProxy */;
- };
8BBEA4BD147C729A00C4ADB7 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 7461B52D0F94FAF800A0C422 /* ProtocolBuffers */;
@@ -815,21 +821,11 @@
};
/* End PBXTargetDependency section */
-/* Begin PBXVariantGroup section */
- 8B9A5EAC1831993600A9D33B /* InfoPlist.strings */ = {
- isa = PBXVariantGroup;
- children = (
- 8B9A5EAD1831993600A9D33B /* en */,
- );
- name = InfoPlist.strings;
- sourceTree = "<group>";
- };
-/* End PBXVariantGroup section */
-
/* Begin XCBuildConfiguration section */
7461B52F0F94FAFA00A0C422 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ CLANG_ENABLE_OBJC_WEAK = YES;
HEADER_SEARCH_PATHS = "$(SRCROOT)";
PRODUCT_NAME = ProtocolBuffers;
TARGETED_DEVICE_FAMILY = "1,2";
@@ -839,46 +835,18 @@
7461B5300F94FAFA00A0C422 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ CLANG_ENABLE_OBJC_WEAK = YES;
HEADER_SEARCH_PATHS = "$(SRCROOT)";
PRODUCT_NAME = ProtocolBuffers;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
- 8B9A5ECB1831993600A9D33B /* Debug */ = {
- isa = XCBuildConfiguration;
- buildSettings = {
- ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
- ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
- CLANG_ENABLE_OBJC_ARC = YES;
- INFOPLIST_FILE = "$(SRCROOT)/Tests/iOSTestHarness/Info.plist";
- IPHONEOS_DEPLOYMENT_TARGET = 8.0;
- PRODUCT_BUNDLE_IDENTIFIER = "com.google.${PRODUCT_NAME:rfc1034identifier}";
- PRODUCT_NAME = "$(TARGET_NAME)";
- TARGETED_DEVICE_FAMILY = "1,2";
- WRAPPER_EXTENSION = app;
- };
- name = Debug;
- };
- 8B9A5ECC1831993600A9D33B /* Release */ = {
- isa = XCBuildConfiguration;
- buildSettings = {
- ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
- ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
- CLANG_ENABLE_OBJC_ARC = YES;
- INFOPLIST_FILE = "$(SRCROOT)/Tests/iOSTestHarness/Info.plist";
- IPHONEOS_DEPLOYMENT_TARGET = 8.0;
- PRODUCT_BUNDLE_IDENTIFIER = "com.google.${PRODUCT_NAME:rfc1034identifier}";
- PRODUCT_NAME = "$(TARGET_NAME)";
- TARGETED_DEVICE_FAMILY = "1,2";
- WRAPPER_EXTENSION = app;
- };
- name = Release;
- };
8BBEA4A7147C727100C4ADB7 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_WEAK = YES;
FRAMEWORK_SEARCH_PATHS = (
"\"$(DEVELOPER_LIBRARY_DIR)/Frameworks\"",
"$(inherited)",
@@ -900,7 +868,6 @@
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = "1,2";
- TEST_HOST = "$(BUILT_PRODUCTS_DIR)/iOSTestHarness.app/iOSTestHarness";
WARNING_CFLAGS = (
"$(inherited)",
"-Wno-documentation-unknown-command",
@@ -914,6 +881,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_WEAK = YES;
FRAMEWORK_SEARCH_PATHS = (
"\"$(DEVELOPER_LIBRARY_DIR)/Frameworks\"",
"$(inherited)",
@@ -934,7 +902,6 @@
SWIFT_OBJC_BRIDGING_HEADER = "Tests/UnitTests-Bridging-Header.h";
SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = "1,2";
- TEST_HOST = "$(BUILT_PRODUCTS_DIR)/iOSTestHarness.app/iOSTestHarness";
WARNING_CFLAGS = (
"$(inherited)",
"-Wno-documentation-unknown-command",
@@ -1087,6 +1054,7 @@
F4487C6C1A9F8F8100531423 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ CLANG_ENABLE_OBJC_WEAK = YES;
HEADER_SEARCH_PATHS = "$(SRCROOT)";
PRODUCT_NAME = TestSingleSourceBuild;
TARGETED_DEVICE_FAMILY = "1,2";
@@ -1096,6 +1064,7 @@
F4487C6D1A9F8F8100531423 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ CLANG_ENABLE_OBJC_WEAK = YES;
HEADER_SEARCH_PATHS = "$(SRCROOT)";
PRODUCT_NAME = TestSingleSourceBuild;
TARGETED_DEVICE_FAMILY = "1,2";
@@ -1105,12 +1074,14 @@
F45BBC0F1B0CDB50002D064D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ CLANG_ENABLE_OBJC_WEAK = YES;
};
name = Debug;
};
F45BBC101B0CDB50002D064D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ CLANG_ENABLE_OBJC_WEAK = YES;
};
name = Release;
};
@@ -1126,15 +1097,6 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
- 8B9A5ECA1831993600A9D33B /* Build configuration list for PBXNativeTarget "iOSTestHarness" */ = {
- isa = XCConfigurationList;
- buildConfigurations = (
- 8B9A5ECB1831993600A9D33B /* Debug */,
- 8B9A5ECC1831993600A9D33B /* Release */,
- );
- defaultConfigurationIsVisible = 0;
- defaultConfigurationName = Release;
- };
8BBEA4BA147C728600C4ADB7 /* Build configuration list for PBXNativeTarget "UnitTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
diff --git a/objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
new file mode 100644
index 00000000..18d98100
--- /dev/null
+++ b/objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>IDEDidComputeMac32BitWarning</key>
+ <true/>
+</dict>
+</plist>
diff --git a/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme b/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme
index 03acb083..77483d38 100644
--- a/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme
+++ b/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "0900"
+ LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -26,7 +26,6 @@
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
- language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
@@ -310,7 +309,6 @@
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
- language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
diff --git a/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme b/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme
index 98bcd562..bacbcba3 100644
--- a/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme
+++ b/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "0900"
+ LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -54,9 +54,8 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
- language = ""
- shouldUseLaunchSchemeArgsEnv = "YES"
- codeCoverageEnabled = "YES">
+ codeCoverageEnabled = "YES"
+ shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
@@ -90,23 +89,21 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
- language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
- <BuildableProductRunnable
- runnableDebuggingMode = "0">
+ <MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
- BlueprintIdentifier = "8B9A5EA41831993600A9D33B"
- BuildableName = "iOSTestHarness.app"
- BlueprintName = "iOSTestHarness"
+ BlueprintIdentifier = "7461B52D0F94FAF800A0C422"
+ BuildableName = "libProtocolBuffers.a"
+ BlueprintName = "ProtocolBuffers"
ReferencedContainer = "container:ProtocolBuffers_iOS.xcodeproj">
</BuildableReference>
- </BuildableProductRunnable>
+ </MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
diff --git a/objectivec/README.md b/objectivec/README.md
index 469a61fb..21ac07d8 100644
--- a/objectivec/README.md
+++ b/objectivec/README.md
@@ -13,16 +13,17 @@ Requirements
The Objective C implementation requires:
- Objective C 2.0 Runtime (32bit & 64bit iOS, 64bit OS X).
-- Xcode 7.0 (or later).
+- Xcode 8.0 (or later).
- The library code does *not* use ARC (for performance reasons), but it all can
be called from ARC code.
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/GPBCodedOuputStreamTests.m b/objectivec/Tests/GPBCodedOuputStreamTests.m
index 878e7aa9..109239d5 100644
--- a/objectivec/Tests/GPBCodedOuputStreamTests.m
+++ b/objectivec/Tests/GPBCodedOuputStreamTests.m
@@ -423,4 +423,14 @@
}
}
+- (void)testThatItThrowsWhenWriteRawPtrFails {
+ NSOutputStream *output = [NSOutputStream outputStreamToMemory];
+ GPBCodedOutputStream *codedOutput =
+ [GPBCodedOutputStream streamWithOutputStream:output bufferSize:0]; // Skip buffering.
+ [output close]; // Close the output stream to force failure on write.
+ const char *cString = "raw";
+ XCTAssertThrowsSpecificNamed([codedOutput writeRawPtr:cString offset:0 length:strlen(cString)],
+ NSException, GPBCodedOutputStreamException_WriteFailed);
+}
+
@end
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_stringutf8_nano.proto b/objectivec/Tests/GPBCompileTest01.m
index bbd677cf..c8bc433a 100644
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_stringutf8_nano.proto
+++ b/objectivec/Tests/GPBCompileTest01.m
@@ -28,16 +28,13 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-// Author: wink@google.com (Wink Saville)
-//
-package protobuf_unittest_import;
+// This is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "GPBArray.h"
-option java_package = "com.google.protobuf";
-// Explicit outer classname to suppress legacy info.
-option java_outer_classname = "UnittestStringutf8Nano";
-message StringUtf8 {
- optional string id = 1;
- repeated string rs = 2;
-}
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_1 = 0;
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_nano.proto b/objectivec/Tests/GPBCompileTest02.m
index 3a1e07f6..c44e201a 100644
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_nano.proto
+++ b/objectivec/Tests/GPBCompileTest02.m
@@ -28,21 +28,13 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-// Author: maxtroy@google.com (Max Cai)
-package protobuf_unittest;
+// This is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
-option java_package = "com.google.protobuf";
-option java_outer_classname = "EnumClassNanos";
+#import "GPBCodedInputStream.h"
-enum FileScopeEnum {
- ONE = 1;
-}
-message EnumClassNano {
- enum MessageScopeEnum {
- TWO = 2;
- }
- optional FileScopeEnum one = 1 [ default = ONE ];
- optional MessageScopeEnum two = 2 [ default = TWO ];
-}
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_2 = 0;
diff --git a/objectivec/Tests/GPBCompileTest03.m b/objectivec/Tests/GPBCompileTest03.m
new file mode 100644
index 00000000..41994f94
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest03.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "GPBCodedOutputStream.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_3 = 0;
diff --git a/objectivec/Tests/GPBCompileTest04.m b/objectivec/Tests/GPBCompileTest04.m
new file mode 100644
index 00000000..c31498f1
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest04.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "GPBDescriptor.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_4 = 0;
diff --git a/objectivec/Tests/GPBCompileTest05.m b/objectivec/Tests/GPBCompileTest05.m
new file mode 100644
index 00000000..adb72252
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest05.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "GPBDictionary.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_5 = 0;
diff --git a/objectivec/Tests/GPBCompileTest06.m b/objectivec/Tests/GPBCompileTest06.m
new file mode 100644
index 00000000..b7505b02
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest06.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "GPBExtensionRegistry.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_6 = 0;
diff --git a/objectivec/Tests/GPBCompileTest07.m b/objectivec/Tests/GPBCompileTest07.m
new file mode 100644
index 00000000..939bb709
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest07.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "GPBMessage.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_7 = 0;
diff --git a/objectivec/Tests/GPBCompileTest08.m b/objectivec/Tests/GPBCompileTest08.m
new file mode 100644
index 00000000..a84f38cf
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest08.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "GPBRootObject.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_8 = 0;
diff --git a/objectivec/Tests/GPBCompileTest09.m b/objectivec/Tests/GPBCompileTest09.m
new file mode 100644
index 00000000..f8ccb4a0
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest09.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "GPBUnknownField.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_9 = 0;
diff --git a/objectivec/Tests/GPBCompileTest10.m b/objectivec/Tests/GPBCompileTest10.m
new file mode 100644
index 00000000..d8318678
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest10.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "GPBUnknownFieldSet.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_10 = 0;
diff --git a/objectivec/Tests/GPBCompileTest11.m b/objectivec/Tests/GPBCompileTest11.m
new file mode 100644
index 00000000..9f2c6b11
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest11.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "GPBUtilities.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_11 = 0;
diff --git a/objectivec/Tests/GPBCompileTest12.m b/objectivec/Tests/GPBCompileTest12.m
new file mode 100644
index 00000000..3aa29b31
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest12.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "GPBWellKnownTypes.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_12 = 0;
diff --git a/objectivec/Tests/GPBCompileTest13.m b/objectivec/Tests/GPBCompileTest13.m
new file mode 100644
index 00000000..fef2af5f
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest13.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "GPBWireFormat.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_13 = 0;
diff --git a/objectivec/Tests/GPBCompileTest14.m b/objectivec/Tests/GPBCompileTest14.m
new file mode 100644
index 00000000..ae04349a
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest14.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "google/protobuf/Any.pbobjc.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_14 = 0;
diff --git a/objectivec/Tests/GPBCompileTest15.m b/objectivec/Tests/GPBCompileTest15.m
new file mode 100644
index 00000000..889243aa
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest15.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "google/protobuf/Api.pbobjc.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_15 = 0;
diff --git a/objectivec/Tests/GPBCompileTest16.m b/objectivec/Tests/GPBCompileTest16.m
new file mode 100644
index 00000000..c5aaf14f
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest16.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "google/protobuf/Duration.pbobjc.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_16 = 0;
diff --git a/objectivec/Tests/GPBCompileTest17.m b/objectivec/Tests/GPBCompileTest17.m
new file mode 100644
index 00000000..feb64d66
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest17.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "google/protobuf/Empty.pbobjc.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_17 = 0;
diff --git a/objectivec/Tests/GPBCompileTest18.m b/objectivec/Tests/GPBCompileTest18.m
new file mode 100644
index 00000000..66784c4f
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest18.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "google/protobuf/FieldMask.pbobjc.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_18 = 0;
diff --git a/objectivec/Tests/GPBCompileTest19.m b/objectivec/Tests/GPBCompileTest19.m
new file mode 100644
index 00000000..435dea01
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest19.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "google/protobuf/SourceContext.pbobjc.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_19 = 0;
diff --git a/objectivec/Tests/GPBCompileTest20.m b/objectivec/Tests/GPBCompileTest20.m
new file mode 100644
index 00000000..c2da8066
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest20.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "google/protobuf/Struct.pbobjc.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_20 = 0;
diff --git a/objectivec/Tests/GPBCompileTest21.m b/objectivec/Tests/GPBCompileTest21.m
new file mode 100644
index 00000000..d7110b93
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest21.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "google/protobuf/Timestamp.pbobjc.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_21 = 0;
diff --git a/objectivec/Tests/GPBCompileTest22.m b/objectivec/Tests/GPBCompileTest22.m
new file mode 100644
index 00000000..17380618
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest22.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "google/protobuf/Type.pbobjc.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_22 = 0;
diff --git a/objectivec/Tests/GPBCompileTest23.m b/objectivec/Tests/GPBCompileTest23.m
new file mode 100644
index 00000000..f22f9bdd
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest23.m
@@ -0,0 +1,40 @@
+// 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 is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
+
+#import "google/protobuf/Wrappers.pbobjc.h"
+
+
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_23 = 0;
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_merge_nano.proto b/objectivec/Tests/GPBCompileTest24.m
index ef4e2d2f..c81ea732 100644
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_merge_nano.proto
+++ b/objectivec/Tests/GPBCompileTest24.m
@@ -28,20 +28,15 @@
// (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: maxtroy@google.com (Max Cai)
-package protobuf_unittest;
+// This is a test including a single header to ensure things build. This
+// is NOT a public header of the library, but uses a file that defines
+// proto2 syntax messages that are extendable, so it can need more things
+// that the proto3 syntax WKTs bundled with the library.
-import "google/protobuf/nano/unittest_nano.proto";
+#import "google/protobuf/Descriptor.pbobjc.h"
-option java_package = "com.google.protobuf";
-option java_multiple_files = true;
-// A container message for testing the merging of repeated fields at a
-// nested level. Other tests will be done using the repeated fields in
-// TestAllTypesNano.
-message TestRepeatedMergeNano {
-
- optional TestAllTypesNano contained = 1;
-
-}
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_24 = 0;
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_multiple_nano.proto b/objectivec/Tests/GPBCompileTest25.m
index 958e1f17..7a482b51 100644
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_multiple_nano.proto
+++ b/objectivec/Tests/GPBCompileTest25.m
@@ -28,21 +28,15 @@
// (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: maxtroy@google.com (Max Cai)
-package protobuf_unittest;
+// This is a test including a single header to ensure things build. This
+// is NOT a public header of the library, but uses a file that defines
+// extensions to proto2 syntax messages, so it can need more things
+// that the proto3 syntax WKTs bundled with the library.
-option java_package = "com.google.protobuf";
-option java_multiple_files = true;
+#import "google/protobuf/UnittestCustomOptions.pbobjc.h"
-enum FileScopeEnumMultiple {
- THREE = 3;
-}
-message EnumClassNanoMultiple {
- enum MessageScopeEnumMultiple {
- FOUR = 4;
- }
- optional FileScopeEnumMultiple three = 3 [ default = THREE ];
- optional MessageScopeEnumMultiple four = 4 [ default = FOUR ];
-}
+// Something in the body of this file so the compiler/linker won't complain
+// about an empty .o file.
+__attribute__((visibility("default"))) char dummy_symbol_25 = 0;
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/iOSTestHarness/AppDelegate.m b/objectivec/Tests/iOSTestHarness/AppDelegate.m
deleted file mode 100644
index 8c4a586b..00000000
--- a/objectivec/Tests/iOSTestHarness/AppDelegate.m
+++ /dev/null
@@ -1,35 +0,0 @@
-#import <UIKit/UIKit.h>
-
-@interface AppDelegate : UIResponder <UIApplicationDelegate>
-@property (strong, nonatomic) UIWindow *window;
-@end
-
-@implementation AppDelegate
-
-@synthesize window;
-
-- (BOOL)application:(UIApplication *)application
- didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
- #pragma unused (application, launchOptions)
-
- self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
- self.window.backgroundColor = [UIColor whiteColor];
- [self.window makeKeyAndVisible];
- self.window.rootViewController = [[UIViewController alloc] init];
-
- UILabel *label =
- [[UILabel alloc] initWithFrame:CGRectMake(0, 200, CGRectGetWidth(self.window.frame), 40)];
- label.text = @"Protocol Buffer Test Harness";
- label.textAlignment = NSTextAlignmentCenter;
- [self.window addSubview:label];
-
- return YES;
-}
-
-@end
-
-int main(int argc, char * argv[]) {
- @autoreleasepool {
- return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
- }
-}
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/Contents.json b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/Contents.json
deleted file mode 100644
index 9f4a9e59..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/Contents.json
+++ /dev/null
@@ -1,152 +0,0 @@
-{
- "images" : [
- {
- "size" : "20x20",
- "idiom" : "iphone",
- "filename" : "appicon_40.png",
- "scale" : "2x"
- },
- {
- "size" : "20x20",
- "idiom" : "iphone",
- "filename" : "appicon_60.png",
- "scale" : "3x"
- },
- {
- "size" : "29x29",
- "idiom" : "iphone",
- "filename" : "appicon_29.png",
- "scale" : "1x"
- },
- {
- "size" : "29x29",
- "idiom" : "iphone",
- "filename" : "appicon_58.png",
- "scale" : "2x"
- },
- {
- "size" : "29x29",
- "idiom" : "iphone",
- "filename" : "appicon_87.png",
- "scale" : "3x"
- },
- {
- "size" : "40x40",
- "idiom" : "iphone",
- "filename" : "appicon_80.png",
- "scale" : "2x"
- },
- {
- "size" : "40x40",
- "idiom" : "iphone",
- "filename" : "appicon_120.png",
- "scale" : "3x"
- },
- {
- "idiom" : "iphone",
- "size" : "57x57",
- "scale" : "1x"
- },
- {
- "idiom" : "iphone",
- "size" : "57x57",
- "scale" : "2x"
- },
- {
- "size" : "60x60",
- "idiom" : "iphone",
- "filename" : "appicon_120.png",
- "scale" : "2x"
- },
- {
- "size" : "60x60",
- "idiom" : "iphone",
- "filename" : "appicon_180.png",
- "scale" : "3x"
- },
- {
- "size" : "20x20",
- "idiom" : "ipad",
- "filename" : "appicon_20.png",
- "scale" : "1x"
- },
- {
- "size" : "20x20",
- "idiom" : "ipad",
- "filename" : "appicon_40.png",
- "scale" : "2x"
- },
- {
- "size" : "29x29",
- "idiom" : "ipad",
- "filename" : "appicon_29.png",
- "scale" : "1x"
- },
- {
- "size" : "29x29",
- "idiom" : "ipad",
- "filename" : "appicon_58.png",
- "scale" : "2x"
- },
- {
- "size" : "40x40",
- "idiom" : "ipad",
- "filename" : "appicon_40.png",
- "scale" : "1x"
- },
- {
- "size" : "40x40",
- "idiom" : "ipad",
- "filename" : "appicon_80.png",
- "scale" : "2x"
- },
- {
- "idiom" : "ipad",
- "size" : "50x50",
- "scale" : "1x"
- },
- {
- "idiom" : "ipad",
- "size" : "50x50",
- "scale" : "2x"
- },
- {
- "idiom" : "ipad",
- "size" : "72x72",
- "scale" : "1x"
- },
- {
- "idiom" : "ipad",
- "size" : "72x72",
- "scale" : "2x"
- },
- {
- "size" : "76x76",
- "idiom" : "ipad",
- "filename" : "appicon_76.png",
- "scale" : "1x"
- },
- {
- "size" : "76x76",
- "idiom" : "ipad",
- "filename" : "appicon_152.png",
- "scale" : "2x"
- },
- {
- "size" : "83.5x83.5",
- "idiom" : "ipad",
- "filename" : "appicon_167.png",
- "scale" : "2x"
- },
- {
- "size" : "1024x1024",
- "idiom" : "ios-marketing",
- "filename" : "appicon_1024.png",
- "scale" : "1x"
- }
- ],
- "info" : {
- "version" : 1,
- "author" : "xcode"
- }
-} \ No newline at end of file
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_1024.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_1024.png
deleted file mode 100644
index 6b6a102e..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_1024.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_120.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_120.png
deleted file mode 100644
index 1bac2e58..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_120.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_152.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_152.png
deleted file mode 100644
index 80f13301..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_152.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_167.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_167.png
deleted file mode 100644
index 99f0745e..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_167.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_180.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_180.png
deleted file mode 100644
index ae123712..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_180.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_20.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_20.png
deleted file mode 100644
index 8e530c49..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_20.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_29.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_29.png
deleted file mode 100644
index 1826feb9..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_29.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_40.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_40.png
deleted file mode 100644
index f2e2ded1..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_40.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_58.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_58.png
deleted file mode 100644
index 0ec6d003..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_58.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_60.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_60.png
deleted file mode 100644
index 8664e8b0..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_60.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_76.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_76.png
deleted file mode 100644
index d4bb05b9..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_76.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_80.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_80.png
deleted file mode 100644
index 8fa6a8e7..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_80.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_87.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_87.png
deleted file mode 100644
index b41bc67b..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_87.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/LaunchImage.launchimage/Contents.json b/objectivec/Tests/iOSTestHarness/Images.xcassets/LaunchImage.launchimage/Contents.json
deleted file mode 100644
index a0ad363c..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/LaunchImage.launchimage/Contents.json
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "images" : [
- {
- "orientation" : "portrait",
- "idiom" : "ipad",
- "extent" : "full-screen",
- "minimum-system-version" : "7.0",
- "scale" : "1x"
- },
- {
- "orientation" : "landscape",
- "idiom" : "ipad",
- "extent" : "full-screen",
- "minimum-system-version" : "7.0",
- "scale" : "1x"
- },
- {
- "orientation" : "portrait",
- "idiom" : "ipad",
- "extent" : "full-screen",
- "minimum-system-version" : "7.0",
- "scale" : "2x"
- },
- {
- "orientation" : "landscape",
- "idiom" : "ipad",
- "extent" : "full-screen",
- "minimum-system-version" : "7.0",
- "scale" : "2x"
- }
- ],
- "info" : {
- "version" : 1,
- "author" : "xcode"
- }
-} \ No newline at end of file
diff --git a/objectivec/Tests/iOSTestHarness/Info.plist b/objectivec/Tests/iOSTestHarness/Info.plist
deleted file mode 100644
index 24bd333d..00000000
--- a/objectivec/Tests/iOSTestHarness/Info.plist
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>CFBundleDevelopmentRegion</key>
- <string>en</string>
- <key>CFBundleDisplayName</key>
- <string>${PRODUCT_NAME}</string>
- <key>CFBundleExecutable</key>
- <string>${EXECUTABLE_NAME}</string>
- <key>CFBundleIdentifier</key>
- <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
- <key>CFBundleInfoDictionaryVersion</key>
- <string>6.0</string>
- <key>CFBundleName</key>
- <string>${PRODUCT_NAME}</string>
- <key>CFBundlePackageType</key>
- <string>APPL</string>
- <key>CFBundleShortVersionString</key>
- <string>1.0</string>
- <key>CFBundleSignature</key>
- <string>????</string>
- <key>CFBundleVersion</key>
- <string>1.0</string>
- <key>LSRequiresIPhoneOS</key>
- <true/>
- <key>UILaunchStoryboardName</key>
- <string>LaunchScreen</string>
- <key>UISupportedInterfaceOrientations</key>
- <array>
- <string>UIInterfaceOrientationPortrait</string>
- <string>UIInterfaceOrientationLandscapeLeft</string>
- <string>UIInterfaceOrientationLandscapeRight</string>
- </array>
- <key>UISupportedInterfaceOrientations~ipad</key>
- <array>
- <string>UIInterfaceOrientationPortrait</string>
- <string>UIInterfaceOrientationLandscapeLeft</string>
- <string>UIInterfaceOrientationLandscapeRight</string>
- <string>UIInterfaceOrientationPortraitUpsideDown</string>
- </array>
-</dict>
-</plist>
diff --git a/objectivec/Tests/iOSTestHarness/LaunchScreen.xib b/objectivec/Tests/iOSTestHarness/LaunchScreen.xib
deleted file mode 100644
index 22204bfe..00000000
--- a/objectivec/Tests/iOSTestHarness/LaunchScreen.xib
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="6254" systemVersion="13F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES">
- <dependencies>
- <deployment identifier="iOS"/>
- <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6247"/>
- <capability name="Constraints with non-1.0 multipliers" minToolsVersion="5.1"/>
- </dependencies>
- <objects>
- <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
- <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
- <view contentMode="scaleToFill" id="iN0-l3-epB">
- <rect key="frame" x="0.0" y="0.0" width="630" height="503"/>
- <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
- <subviews>
- <label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Protocol Buffer Test Harness" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="kId-c2-rCX">
- <rect key="frame" x="20" y="147" width="591" height="43"/>
- <fontDescription key="fontDescription" type="boldSystem" pointSize="36"/>
- <color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
- <nil key="highlightedColor"/>
- </label>
- </subviews>
- <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
- <constraints>
- <constraint firstItem="kId-c2-rCX" firstAttribute="centerY" secondItem="iN0-l3-epB" secondAttribute="bottom" multiplier="1/3" constant="1" id="Kid-kn-2rF"/>
- <constraint firstAttribute="centerX" secondItem="kId-c2-rCX" secondAttribute="centerX" id="Koa-jz-hwk"/>
- <constraint firstItem="kId-c2-rCX" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" constant="20" symbolic="YES" id="fvb-Df-36g"/>
- </constraints>
- <nil key="simulatedStatusBarMetrics"/>
- <freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
- <point key="canvasLocation" x="479" y="456.5"/>
- </view>
- </objects>
-</document>
diff --git a/objectivec/Tests/iOSTestHarness/en.lproj/InfoPlist.strings b/objectivec/Tests/iOSTestHarness/en.lproj/InfoPlist.strings
deleted file mode 100644
index 477b28ff..00000000
--- a/objectivec/Tests/iOSTestHarness/en.lproj/InfoPlist.strings
+++ /dev/null
@@ -1,2 +0,0 @@
-/* Localized versions of Info.plist keys */
-
diff --git a/objectivec/google/protobuf/Any.pbobjc.h b/objectivec/google/protobuf/Any.pbobjc.h
index 89c99bdb..ad261898 100644
--- a/objectivec/google/protobuf/Any.pbobjc.h
+++ b/objectivec/google/protobuf/Any.pbobjc.h
@@ -8,9 +8,13 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <Protobuf/GPBProtocolBuffers.h>
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
#else
- #import "GPBProtocolBuffers.h"
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
#endif
#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
diff --git a/objectivec/google/protobuf/Api.pbobjc.h b/objectivec/google/protobuf/Api.pbobjc.h
index 095fc2cd..c93f3f15 100644
--- a/objectivec/google/protobuf/Api.pbobjc.h
+++ b/objectivec/google/protobuf/Api.pbobjc.h
@@ -8,9 +8,13 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <Protobuf/GPBProtocolBuffers.h>
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
#else
- #import "GPBProtocolBuffers.h"
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
#endif
#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
diff --git a/objectivec/google/protobuf/Duration.pbobjc.h b/objectivec/google/protobuf/Duration.pbobjc.h
index d9a388ac..3e367590 100644
--- a/objectivec/google/protobuf/Duration.pbobjc.h
+++ b/objectivec/google/protobuf/Duration.pbobjc.h
@@ -8,9 +8,13 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <Protobuf/GPBProtocolBuffers.h>
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
#else
- #import "GPBProtocolBuffers.h"
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
#endif
#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
diff --git a/objectivec/google/protobuf/Empty.pbobjc.h b/objectivec/google/protobuf/Empty.pbobjc.h
index bd49cfdb..fdc247ae 100644
--- a/objectivec/google/protobuf/Empty.pbobjc.h
+++ b/objectivec/google/protobuf/Empty.pbobjc.h
@@ -8,9 +8,13 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <Protobuf/GPBProtocolBuffers.h>
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
#else
- #import "GPBProtocolBuffers.h"
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
#endif
#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
diff --git a/objectivec/google/protobuf/FieldMask.pbobjc.h b/objectivec/google/protobuf/FieldMask.pbobjc.h
index 75cf856c..73296d57 100644
--- a/objectivec/google/protobuf/FieldMask.pbobjc.h
+++ b/objectivec/google/protobuf/FieldMask.pbobjc.h
@@ -8,9 +8,13 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <Protobuf/GPBProtocolBuffers.h>
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
#else
- #import "GPBProtocolBuffers.h"
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
#endif
#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
@@ -255,8 +259,8 @@ typedef GPB_ENUM(GPBFieldMask_FieldNumber) {
*
* ## Field Mask Verification
*
- * The implementation of the all the API methods, which have any FieldMask type
- * field in the request, should verify the included field paths, and return
+ * The implementation of any API method which has a FieldMask type field in the
+ * request should verify the included field paths, and return an
* `INVALID_ARGUMENT` error if any path is duplicated or unmappable.
**/
@interface GPBFieldMask : GPBMessage
diff --git a/objectivec/google/protobuf/SourceContext.pbobjc.h b/objectivec/google/protobuf/SourceContext.pbobjc.h
index 799d190a..e4923959 100644
--- a/objectivec/google/protobuf/SourceContext.pbobjc.h
+++ b/objectivec/google/protobuf/SourceContext.pbobjc.h
@@ -8,9 +8,13 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <Protobuf/GPBProtocolBuffers.h>
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
#else
- #import "GPBProtocolBuffers.h"
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
#endif
#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
diff --git a/objectivec/google/protobuf/Struct.pbobjc.h b/objectivec/google/protobuf/Struct.pbobjc.h
index 3fc80caa..fb204251 100644
--- a/objectivec/google/protobuf/Struct.pbobjc.h
+++ b/objectivec/google/protobuf/Struct.pbobjc.h
@@ -8,9 +8,13 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <Protobuf/GPBProtocolBuffers.h>
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
#else
- #import "GPBProtocolBuffers.h"
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
#endif
#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
diff --git a/objectivec/google/protobuf/Timestamp.pbobjc.h b/objectivec/google/protobuf/Timestamp.pbobjc.h
index 7e65b15b..2c4b8b20 100644
--- a/objectivec/google/protobuf/Timestamp.pbobjc.h
+++ b/objectivec/google/protobuf/Timestamp.pbobjc.h
@@ -8,9 +8,13 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <Protobuf/GPBProtocolBuffers.h>
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
#else
- #import "GPBProtocolBuffers.h"
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
#endif
#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
diff --git a/objectivec/google/protobuf/Type.pbobjc.h b/objectivec/google/protobuf/Type.pbobjc.h
index 17986970..e14d15df 100644
--- a/objectivec/google/protobuf/Type.pbobjc.h
+++ b/objectivec/google/protobuf/Type.pbobjc.h
@@ -8,9 +8,13 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <Protobuf/GPBProtocolBuffers.h>
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
#else
- #import "GPBProtocolBuffers.h"
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
#endif
#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
diff --git a/objectivec/google/protobuf/Wrappers.pbobjc.h b/objectivec/google/protobuf/Wrappers.pbobjc.h
index 3cb9fe77..0411e1ec 100644
--- a/objectivec/google/protobuf/Wrappers.pbobjc.h
+++ b/objectivec/google/protobuf/Wrappers.pbobjc.h
@@ -8,9 +8,13 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <Protobuf/GPBProtocolBuffers.h>
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
#else
- #import "GPBProtocolBuffers.h"
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
#endif
#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
diff --git a/php/README.md b/php/README.md
index da7884ea..967250a7 100644
--- a/php/README.md
+++ b/php/README.md
@@ -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/ext/google/protobuf/def.c b/php/ext/google/protobuf/def.c
index 8140fe47..fa33830b 100644
--- a/php/ext/google/protobuf/def.c
+++ b/php/ext/google/protobuf/def.c
@@ -718,105 +718,187 @@ PHP_METHOD(InternalDescriptorPool, getGeneratedPool) {
#endif
}
-static void classname_no_prefix(const char *fullname, const char *package_name,
- char *class_name) {
- size_t i = 0, j;
- bool first_char = true, is_reserved = false;
- size_t pkg_name_len = package_name == NULL ? 0 : strlen(package_name);
- size_t message_name_start = package_name == NULL ? 0 : pkg_name_len + 1;
- size_t message_len = (strlen(fullname) - message_name_start);
+static size_t classname_len_max(const char *fullname,
+ const char *package,
+ const char *php_namespace,
+ const char *prefix) {
+ size_t fullname_len = strlen(fullname);
+ size_t package_len = 0;
+ size_t prefix_len = 0;
+ size_t namespace_len = 0;
+ size_t length = fullname_len;
+ int i, segment, classname_start = 0;
+
+ if (package != NULL) {
+ package_len = strlen(package);
+ }
+ if (prefix != NULL) {
+ prefix_len = strlen(prefix);
+ }
+ if (php_namespace != NULL) {
+ namespace_len = strlen(php_namespace);
+ }
- // Submessage is concatenated with its containing messages by '_'.
- for (j = message_name_start; j < message_name_start + message_len; j++) {
- if (fullname[j] == '.') {
- class_name[i++] = '_';
- } else {
- class_name[i++] = fullname[j];
+ // Process package
+ if (package_len > 0) {
+ segment = 1;
+ for (i = 0; i < package_len; i++) {
+ if (package[i] == '.') {
+ segment++;
+ }
}
- }
-}
+ // In case of reserved name in package.
+ length += 3 * segment;
-static const char *classname_prefix(const char *classname,
- const char *prefix_given,
- const char *package_name) {
- size_t i;
- bool is_reserved = false;
+ classname_start = package_len + 1;
+ }
- if (prefix_given != NULL && strcmp(prefix_given, "") != 0) {
- return prefix_given;
+ // Process class name
+ segment = 1;
+ for (i = classname_start; i < fullname_len; i++) {
+ if (fullname[i] == '.') {
+ segment++;
+ }
+ }
+ if (prefix_len == 0) {
+ length += 3 * segment;
+ } else {
+ length += prefix_len * segment;
}
- char* lower = ALLOC_N(char, strlen(classname) + 1);
- i = 0;
- while(classname[i]) {
- lower[i] = (char)tolower(classname[i]);
+ // The additional 2, one is for preceding '.' and the other is for trailing 0.
+ return length + namespace_len + 2;
+}
+
+static bool is_reserved(const char *segment, int length) {
+ bool result;
+ char* lower = ALLOC_N(char, length + 1);
+ memset(lower, 0, length + 1);
+ memcpy(lower, segment, length);
+ int i = 0;
+ while(lower[i]) {
+ lower[i] = (char)tolower(lower[i]);
i++;
}
- lower[i] = 0;
-
- is_reserved = is_reserved_name(lower);
+ lower[length] = 0;
+ result = is_reserved_name(lower);
FREE(lower);
+ return result;
+}
- if (is_reserved) {
- if (package_name != NULL && strcmp("google.protobuf", package_name) == 0) {
- return "GPB";
- } else {
- return "PB";
+static char* fill_prefix(const char *segment, int length,
+ const char *prefix_given,
+ const char *package_name, char *classname) {
+ size_t i;
+
+ if (prefix_given != NULL && strcmp(prefix_given, "") != 0) {
+ size_t prefix_len = strlen(prefix_given);
+ memcpy(classname, prefix_given, strlen(prefix_given));
+ classname += prefix_len;
+ } else {
+ if (is_reserved(segment, length)) {
+ if (package_name != NULL &&
+ strcmp("google.protobuf", package_name) == 0) {
+ memcpy(classname, "GPB", 3);
+ classname += 3;
+ } else {
+ memcpy(classname, "PB", 2);
+ classname += 2;
+ }
}
}
+ return classname;
+}
- return "";
+static char* fill_segment(const char *segment, int length,
+ char *classname, bool use_camel) {
+ memcpy(classname, segment, length);
+ if (use_camel && (segment[0] < 'A' || segment[0] > 'Z')) {
+ classname[0] += 'A' - 'a';
+ }
+ return classname + length;
}
-static void convert_to_class_name_inplace(const char *package,
- const char *namespace_given,
- const char *prefix, char *classname) {
- size_t prefix_len = prefix == NULL ? 0 : strlen(prefix);
- size_t classname_len = strlen(classname);
- int i = 0, j;
- bool first_char = true;
+static char* fill_namespace(const char *package, const char *namespace_given,
+ char *classname) {
+ if (namespace_given != NULL) {
+ size_t namespace_len = strlen(namespace_given);
+ memcpy(classname, namespace_given, namespace_len);
+ classname += namespace_len;
+ *classname = '\\';
+ classname++;
+ } else if (package != NULL) {
+ int i = 0, j, offset = 0;
+ size_t package_len = strlen(package);
+ while (i < package_len) {
+ j = i;
+ while (j < package_len && package[j] != '.') {
+ j++;
+ }
+ classname = fill_prefix(package + i, j - i, "", package, classname);
+ classname = fill_segment(package + i, j - i, classname, true);
+ classname[0] = '\\';
+ classname++;
+ i = j + 1;
+ }
+ }
+ return classname;
+}
- size_t package_len = package == NULL ? 0 : strlen(package);
- size_t namespace_given_len =
- namespace_given == NULL ? 0 : strlen(namespace_given);
- bool use_namespace_given = namespace_given != NULL;
- size_t namespace_len =
- use_namespace_given ? namespace_given_len : package_len;
+static char* fill_classname(const char *fullname,
+ const char *package,
+ const char *namespace_given,
+ const char *prefix, char *classname) {
+ int classname_start = 0;
+ if (package != NULL) {
+ size_t package_len = strlen(package);
+ classname_start = package_len == 0 ? 0 : package_len + 1;
+ }
+ size_t fullname_len = strlen(fullname);
+ classname = fill_prefix(fullname + classname_start,
+ fullname_len - classname_start,
+ prefix, package, classname);
+
+ int i = classname_start, j;
+ while (i < fullname_len) {
+ j = i;
+ while (j < fullname_len && fullname[j] != '.') {
+ j++;
+ }
+ classname = fill_segment(fullname + i, j - i, classname, false);
+ if (j != fullname_len) {
+ *classname = '_';
+ classname++;
+ }
+ i = j + 1;
+ }
+ return classname;
+}
- int offset = namespace_len != 0 ? 2 : 0;
+static char* fill_qualified_classname(const char *fullname,
+ const char *package,
+ const char *namespace_given,
+ const char *prefix, char *classname) {
+ classname = fill_namespace(package, namespace_given, classname);
+ return fill_classname(fullname, package, namespace_given, prefix, classname);
+}
- for (j = 0; j < classname_len; j++) {
- classname[namespace_len + prefix_len + classname_len + offset - 1 - j] =
- classname[classname_len - j - 1];
- }
+static void classname_no_prefix(const char *fullname, const char *package_name,
+ char *class_name) {
+ size_t i = 0, j;
+ bool first_char = true, is_reserved = false;
+ size_t pkg_name_len = package_name == NULL ? 0 : strlen(package_name);
+ size_t message_name_start = package_name == NULL ? 0 : pkg_name_len + 1;
+ size_t message_len = (strlen(fullname) - message_name_start);
- if (namespace_len != 0) {
- classname[i++] = '\\';
- for (j = 0; j < namespace_len; j++) {
- if (use_namespace_given) {
- classname[i++] = namespace_given[j];
- continue;
- }
- // php packages are divided by '\'.
- if (package[j] == '.') {
- classname[i++] = '\\';
- first_char = true;
- } else if (first_char) {
- // PHP package uses camel case.
- if (package[j] < 'A' || package[j] > 'Z') {
- classname[i++] = package[j] + 'A' - 'a';
- } else {
- classname[i++] = package[j];
- }
- first_char = false;
- } else {
- classname[i++] = package[j];
- }
+ // Submessage is concatenated with its containing messages by '_'.
+ for (j = message_name_start; j < message_name_start + message_len; j++) {
+ if (fullname[j] == '.') {
+ class_name[i++] = '_';
+ } else {
+ class_name[i++] = fullname[j];
}
- classname[i++] = '\\';
}
-
- memcpy(classname + i, prefix, prefix_len);
}
void internal_add_generated_file(const char *data, PHP_PROTO_SIZE data_len,
@@ -858,20 +940,14 @@ void internal_add_generated_file(const char *data, PHP_PROTO_SIZE data_len,
* bytes allocated, one for '.', one for trailing 0, and 3 for 'GPB' if \
* given message is google.protobuf.Empty.*/ \
const char *fullname = upb_##def_type_lower##_fullname(def_type_lower); \
+ const char *package = upb_filedef_package(files[0]); \
const char *php_namespace = upb_filedef_phpnamespace(files[0]); \
const char *prefix_given = upb_filedef_phpprefix(files[0]); \
- size_t classname_len = strlen(fullname) + 5; \
- if (prefix_given != NULL) { \
- classname_len += strlen(prefix_given); \
- } \
- if (php_namespace != NULL) { \
- classname_len += strlen(php_namespace); \
- } \
+ size_t classname_len = classname_len_max(fullname, package, \
+ php_namespace, prefix_given); \
char *classname = ecalloc(sizeof(char), classname_len); \
- const char *package = upb_filedef_package(files[0]); \
- classname_no_prefix(fullname, package, classname); \
- const char *prefix = classname_prefix(classname, prefix_given, package); \
- convert_to_class_name_inplace(package, php_namespace, prefix, classname); \
+ fill_qualified_classname(fullname, package, php_namespace, \
+ prefix_given, classname); \
PHP_PROTO_CE_DECLARE pce; \
if (php_proto_zend_lookup_class(classname, strlen(classname), &pce) == \
FAILURE) { \
diff --git a/php/ext/google/protobuf/encode_decode.c b/php/ext/google/protobuf/encode_decode.c
index b98121bb..a8c47f4d 100644
--- a/php/ext/google/protobuf/encode_decode.c
+++ b/php/ext/google/protobuf/encode_decode.c
@@ -484,11 +484,11 @@ static void map_slot_init(void* memory, upb_fieldtype_t type, zval* cache) {
// Store zval** in memory in order to be consistent with the layout of
// singular fields.
zval** holder = ALLOC(zval*);
+ *(zval***)memory = holder;
zval* tmp;
MAKE_STD_ZVAL(tmp);
PHP_PROTO_ZVAL_STRINGL(tmp, "", 0, 1);
*holder = tmp;
- *(zval***)memory = holder;
#else
*(zval**)memory = cache;
PHP_PROTO_ZVAL_STRINGL(*(zval**)memory, "", 0, 1);
@@ -521,7 +521,7 @@ static void map_slot_uninit(void* memory, upb_fieldtype_t type) {
case UPB_TYPE_BYTES: {
#if PHP_MAJOR_VERSION < 7
zval** holder = *(zval***)memory;
- php_proto_zval_ptr_dtor(*holder);
+ zval_ptr_dtor(holder);
FREE(holder);
#else
php_proto_zval_ptr_dtor(*(zval**)memory);
@@ -1621,6 +1621,7 @@ static void discard_unknown_fields(MessageHeader* msg) {
stringsink* unknown = DEREF(message_data(msg), 0, stringsink*);
if (unknown != NULL) {
stringsink_uninit(unknown);
+ FREE(unknown);
DEREF(message_data(msg), 0, stringsink*) = NULL;
}
diff --git a/php/ext/google/protobuf/map.c b/php/ext/google/protobuf/map.c
index 2680b547..ab8a518a 100644
--- a/php/ext/google/protobuf/map.c
+++ b/php/ext/google/protobuf/map.c
@@ -293,13 +293,46 @@ static bool map_field_read_dimension(zval *object, zval *key, int type,
}
}
+static bool map_index_unset(Map *intern, const char* keyval, int length) {
+ upb_value old_value;
+ if (upb_strtable_remove2(&intern->table, keyval, length, &old_value)) {
+ switch (intern->value_type) {
+ case UPB_TYPE_MESSAGE: {
+#if PHP_MAJOR_VERSION < 7
+ zval_ptr_dtor(upb_value_memory(&old_value));
+#else
+ zend_object* object = *(zend_object**)upb_value_memory(&old_value);
+ if(--GC_REFCOUNT(object) == 0) {
+ zend_objects_store_del(object);
+ }
+#endif
+ break;
+ }
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+#if PHP_MAJOR_VERSION < 7
+ zval_ptr_dtor(upb_value_memory(&old_value));
+#else
+ zend_string* object = *(zend_string**)upb_value_memory(&old_value);
+ zend_string_release(object);
+#endif
+ break;
+ }
+ default:
+ break;
+ }
+ }
+}
+
bool map_index_set(Map *intern, const char* keyval, int length, upb_value v) {
// Replace any existing value by issuing a 'remove' operation first.
- upb_strtable_remove2(&intern->table, keyval, length, NULL);
+ map_index_unset(intern, keyval, length);
+
if (!upb_strtable_insert2(&intern->table, keyval, length, v)) {
zend_error(E_USER_ERROR, "Could not insert into table");
return false;
}
+
return true;
}
@@ -326,12 +359,7 @@ static void map_field_write_dimension(zval *object, zval *key,
v.ctype = UPB_CTYPE_UINT64;
#endif
- // Replace any existing value by issuing a 'remove' operation first.
- upb_strtable_remove2(&intern->table, keyval, length, NULL);
- if (!upb_strtable_insert2(&intern->table, keyval, length, v)) {
- zend_error(E_USER_ERROR, "Could not insert into table");
- return;
- }
+ map_index_set(intern, keyval, length, v);
}
static bool map_field_unset_dimension(zval *object, zval *key TSRMLS_DC) {
@@ -348,7 +376,7 @@ static bool map_field_unset_dimension(zval *object, zval *key TSRMLS_DC) {
v.ctype = UPB_CTYPE_UINT64;
#endif
- upb_strtable_remove2(&intern->table, keyval, length, &v);
+ map_index_unset(intern, keyval, length);
return true;
}
diff --git a/php/ext/google/protobuf/message.c b/php/ext/google/protobuf/message.c
index 24472682..e28e42a1 100644
--- a/php/ext/google/protobuf/message.c
+++ b/php/ext/google/protobuf/message.c
@@ -222,7 +222,13 @@ static zval* message_get_property_ptr_ptr(zval* object, zval* member, int type,
}
static HashTable* message_get_properties(zval* object TSRMLS_DC) {
- return NULL;
+ // User cannot get property directly (e.g., $a = $m->a)
+ zend_error(E_USER_ERROR, "Cannot access private properties.");
+#if PHP_MAJOR_VERSION < 7
+ return zend_std_get_properties(object TSRMLS_CC);
+#else
+ return zend_std_get_properties(object);
+#endif
}
static HashTable* message_get_gc(zval* object, CACHED_VALUE** table,
@@ -276,15 +282,118 @@ void build_class_from_descriptor(
// PHP Methods
// -----------------------------------------------------------------------------
+void Message_construct(zval* msg, zval* array_wrapper) {
+ zend_class_entry* ce = Z_OBJCE_P(msg);
+ MessageHeader* intern = NULL;
+ if (EXPECTED(class_added(ce))) {
+ intern = UNBOX(MessageHeader, msg);
+ custom_data_init(ce, intern PHP_PROTO_TSRMLS_CC);
+ }
+
+ if (array_wrapper == NULL) {
+ return;
+ }
+
+ HashTable* array = Z_ARRVAL_P(array_wrapper);
+ HashPosition pointer;
+ zval key;
+ void* value;
+ const upb_fielddef* field;
+
+ for (zend_hash_internal_pointer_reset_ex(array, &pointer);
+ php_proto_zend_hash_get_current_data_ex(array, (void**)&value,
+ &pointer) == SUCCESS;
+ zend_hash_move_forward_ex(array, &pointer)) {
+ zend_hash_get_current_key_zval_ex(array, &key, &pointer);
+ field = upb_msgdef_ntofz(intern->descriptor->msgdef, Z_STRVAL_P(&key));
+ if (field == NULL) {
+ zend_error(E_USER_ERROR, "Unknown field: %s", Z_STRVAL_P(&key));
+ }
+ if (upb_fielddef_ismap(field)) {
+ PHP_PROTO_FAKE_SCOPE_BEGIN(Z_OBJCE_P(msg));
+ zval* submap = message_get_property_internal(msg, &key TSRMLS_CC);
+ PHP_PROTO_FAKE_SCOPE_END;
+ HashTable* subtable = HASH_OF(
+ CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)value));
+ HashPosition subpointer;
+ zval subkey;
+ void* memory;
+ for (zend_hash_internal_pointer_reset_ex(subtable, &subpointer);
+ php_proto_zend_hash_get_current_data_ex(subtable, (void**)&memory,
+ &subpointer) == SUCCESS;
+ zend_hash_move_forward_ex(subtable, &subpointer)) {
+ zend_hash_get_current_key_zval_ex(subtable, &subkey, &subpointer);
+ map_field_handlers->write_dimension(
+ submap, &subkey,
+ CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)memory) TSRMLS_CC);
+ zval_dtor(&subkey);
+ }
+ } else if (upb_fielddef_isseq(field)) {
+ PHP_PROTO_FAKE_SCOPE_BEGIN(Z_OBJCE_P(msg));
+ zval* subarray = message_get_property_internal(msg, &key TSRMLS_CC);
+ PHP_PROTO_FAKE_SCOPE_END;
+ HashTable* subtable = HASH_OF(
+ CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)value));
+ HashPosition subpointer;
+ void* memory;
+ for (zend_hash_internal_pointer_reset_ex(subtable, &subpointer);
+ php_proto_zend_hash_get_current_data_ex(subtable, (void**)&memory,
+ &subpointer) == SUCCESS;
+ zend_hash_move_forward_ex(subtable, &subpointer)) {
+ repeated_field_handlers->write_dimension(
+ subarray, NULL,
+ CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)memory) TSRMLS_CC);
+ }
+ } else if (upb_fielddef_issubmsg(field)) {
+ const upb_msgdef* submsgdef = upb_fielddef_msgsubdef(field);
+ PHP_PROTO_HASHTABLE_VALUE desc_php = get_def_obj(submsgdef);
+ Descriptor* desc = UNBOX_HASHTABLE_VALUE(Descriptor, desc_php);
+ zend_property_info* property_info;
+ PHP_PROTO_FAKE_SCOPE_BEGIN(Z_OBJCE_P(msg));
+#if PHP_MAJOR_VERSION < 7
+ property_info =
+ zend_get_property_info(Z_OBJCE_P(msg), &key, true TSRMLS_CC);
+#else
+ property_info =
+ zend_get_property_info(Z_OBJCE_P(msg), Z_STR_P(&key), true);
+#endif
+ PHP_PROTO_FAKE_SCOPE_END;
+ CACHED_VALUE* cached = OBJ_PROP(Z_OBJ_P(msg), property_info->offset);
+#if PHP_MAJOR_VERSION < 7
+ SEPARATE_ZVAL_IF_NOT_REF(cached);
+#endif
+ zval* submsg = CACHED_PTR_TO_ZVAL_PTR(cached);
+ ZVAL_OBJ(submsg, desc->klass->create_object(desc->klass TSRMLS_CC));
+ Message_construct(submsg, NULL);
+ MessageHeader* from = UNBOX(MessageHeader,
+ CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)value));
+ MessageHeader* to = UNBOX(MessageHeader, submsg);
+ if(from->descriptor != to->descriptor) {
+ zend_error(E_USER_ERROR, "Cannot merge messages with different class.");
+ return;
+ }
+
+ layout_merge(from->descriptor->layout, from, to TSRMLS_CC);
+ } else {
+ message_set_property_internal(msg, &key,
+ CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)value) TSRMLS_CC);
+ }
+ zval_dtor(&key);
+ }
+}
+
// At the first time the message is created, the class entry hasn't been
// modified. As a result, the first created instance will be a normal zend
// object. Here, we manually modify it to our message in such a case.
PHP_METHOD(Message, __construct) {
- zend_class_entry* ce = Z_OBJCE_P(getThis());
- if (EXPECTED(class_added(ce))) {
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
- custom_data_init(ce, intern PHP_PROTO_TSRMLS_CC);
+ // Init message with array
+ zval* array_wrapper = NULL;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
+ "|a!", &array_wrapper) == FAILURE) {
+ return;
}
+
+ Message_construct(getThis(), array_wrapper);
}
PHP_METHOD(Message, clear) {
@@ -292,7 +401,9 @@ PHP_METHOD(Message, clear) {
Descriptor* desc = msg->descriptor;
zend_class_entry* ce = desc->klass;
+ zend_object_std_dtor(&msg->std TSRMLS_CC);
object_properties_init(&msg->std, ce);
+
layout_init(desc->layout, message_data(msg), &msg->std TSRMLS_CC);
}
@@ -445,8 +556,7 @@ static void init_file_wrappers(TSRMLS_D);
// Define file init functions
static void init_file_any(TSRMLS_D) {
- static bool is_initialized = false;
- if (is_initialized) return;
+ if (is_inited_file_any) return;
init_generated_pool_once(TSRMLS_C);
const char* generated_file =
"0acd010a19676f6f676c652f70726f746f6275662f616e792e70726f746f"
@@ -461,12 +571,11 @@ static void init_file_any(TSRMLS_D) {
hex_to_binary(generated_file, &binary, &binary_len);
internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
FREE(binary);
- is_initialized = true;
+ is_inited_file_any = true;
}
static void init_file_api(TSRMLS_D) {
- static bool is_initialized = false;
- if (is_initialized) return;
+ if (is_inited_file_api) return;
init_file_source_context(TSRMLS_C);
init_file_type(TSRMLS_C);
init_generated_pool_once(TSRMLS_C);
@@ -502,12 +611,11 @@ static void init_file_api(TSRMLS_D) {
hex_to_binary(generated_file, &binary, &binary_len);
internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
FREE(binary);
- is_initialized = true;
+ is_inited_file_api = true;
}
static void init_file_duration(TSRMLS_D) {
- static bool is_initialized = false;
- if (is_initialized) return;
+ if (is_inited_file_duration) return;
init_generated_pool_once(TSRMLS_C);
const char* generated_file =
"0ae3010a1e676f6f676c652f70726f746f6275662f6475726174696f6e2e"
@@ -523,12 +631,11 @@ static void init_file_duration(TSRMLS_D) {
hex_to_binary(generated_file, &binary, &binary_len);
internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
FREE(binary);
- is_initialized = true;
+ is_inited_file_duration = true;
}
static void init_file_field_mask(TSRMLS_D) {
- static bool is_initialized = false;
- if (is_initialized) return;
+ if (is_inited_file_field_mask) return;
init_generated_pool_once(TSRMLS_C);
const char* generated_file =
"0ae3010a20676f6f676c652f70726f746f6275662f6669656c645f6d6173"
@@ -544,12 +651,11 @@ static void init_file_field_mask(TSRMLS_D) {
hex_to_binary(generated_file, &binary, &binary_len);
internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
FREE(binary);
- is_initialized = true;
+ is_inited_file_field_mask = true;
}
static void init_file_empty(TSRMLS_D) {
- static bool is_initialized = false;
- if (is_initialized) return;
+ if (is_inited_file_empty) return;
init_generated_pool_once(TSRMLS_C);
const char* generated_file =
"0ab7010a1b676f6f676c652f70726f746f6275662f656d7074792e70726f"
@@ -564,12 +670,11 @@ static void init_file_empty(TSRMLS_D) {
hex_to_binary(generated_file, &binary, &binary_len);
internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
FREE(binary);
- is_initialized = true;
+ is_inited_file_empty = true;
}
static void init_file_source_context(TSRMLS_D) {
- static bool is_initialized = false;
- if (is_initialized) return;
+ if (is_inited_file_source_context) return;
init_generated_pool_once(TSRMLS_C);
const char* generated_file =
"0afb010a24676f6f676c652f70726f746f6275662f736f757263655f636f"
@@ -586,12 +691,11 @@ static void init_file_source_context(TSRMLS_D) {
hex_to_binary(generated_file, &binary, &binary_len);
internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
FREE(binary);
- is_initialized = true;
+ is_inited_file_source_context = true;
}
static void init_file_struct(TSRMLS_D) {
- static bool is_initialized = false;
- if (is_initialized) return;
+ if (is_inited_file_struct) return;
init_generated_pool_once(TSRMLS_C);
const char* generated_file =
"0a81050a1c676f6f676c652f70726f746f6275662f7374727563742e7072"
@@ -621,12 +725,11 @@ static void init_file_struct(TSRMLS_D) {
hex_to_binary(generated_file, &binary, &binary_len);
internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
FREE(binary);
- is_initialized = true;
+ is_inited_file_struct = true;
}
static void init_file_timestamp(TSRMLS_D) {
- static bool is_initialized = false;
- if (is_initialized) return;
+ if (is_inited_file_timestamp) return;
init_generated_pool_once(TSRMLS_C);
const char* generated_file =
"0ae7010a1f676f6f676c652f70726f746f6275662f74696d657374616d70"
@@ -642,12 +745,11 @@ static void init_file_timestamp(TSRMLS_D) {
hex_to_binary(generated_file, &binary, &binary_len);
internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
FREE(binary);
- is_initialized = true;
+ is_inited_file_timestamp = true;
}
static void init_file_type(TSRMLS_D) {
- static bool is_initialized = false;
- if (is_initialized) return;
+ if (is_inited_file_type) return;
init_file_any(TSRMLS_C);
init_file_source_context(TSRMLS_C);
init_generated_pool_once(TSRMLS_C);
@@ -711,12 +813,11 @@ static void init_file_type(TSRMLS_D) {
hex_to_binary(generated_file, &binary, &binary_len);
internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
FREE(binary);
- is_initialized = true;
+ is_inited_file_type = true;
}
static void init_file_wrappers(TSRMLS_D) {
- static bool is_initialized = false;
- if (is_initialized) return;
+ if (is_inited_file_wrappers) return;
init_generated_pool_once(TSRMLS_C);
const char* generated_file =
"0abf030a1e676f6f676c652f70726f746f6275662f77726170706572732e"
@@ -739,7 +840,7 @@ static void init_file_wrappers(TSRMLS_D) {
hex_to_binary(generated_file, &binary, &binary_len);
internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
FREE(binary);
- is_initialized = true;
+ is_inited_file_wrappers = true;
}
// -----------------------------------------------------------------------------
@@ -757,7 +858,7 @@ static zend_function_entry field_cardinality_methods[] = {
zend_class_entry* field_cardinality_type;
// Init class entry.
-PHP_PROTO_INIT_ENUMCLASS_START("Google\\Protobuf\\Field_Cardinality",
+PHP_PROTO_INIT_ENUMCLASS_START("Google\\Protobuf\\Field\\Cardinality",
Field_Cardinality, field_cardinality)
zend_declare_class_constant_long(field_cardinality_type,
"CARDINALITY_UNKNOWN", 19, 0 TSRMLS_CC);
@@ -767,6 +868,8 @@ PHP_PROTO_INIT_ENUMCLASS_START("Google\\Protobuf\\Field_Cardinality",
"CARDINALITY_REQUIRED", 20, 2 TSRMLS_CC);
zend_declare_class_constant_long(field_cardinality_type,
"CARDINALITY_REPEATED", 20, 3 TSRMLS_CC);
+ const char *alias = "Google\\Protobuf\\Field_Cardinality";
+ zend_register_class_alias_ex(alias, strlen(alias), field_cardinality_type TSRMLS_CC);
PHP_PROTO_INIT_ENUMCLASS_END
// -----------------------------------------------------------------------------
@@ -780,7 +883,7 @@ static zend_function_entry field_kind_methods[] = {
zend_class_entry* field_kind_type;
// Init class entry.
-PHP_PROTO_INIT_ENUMCLASS_START("Google\\Protobuf\\Field_Kind",
+PHP_PROTO_INIT_ENUMCLASS_START("Google\\Protobuf\\Field\\Kind",
Field_Kind, field_kind)
zend_declare_class_constant_long(field_kind_type,
"TYPE_UNKNOWN", 12, 0 TSRMLS_CC);
@@ -820,6 +923,8 @@ PHP_PROTO_INIT_ENUMCLASS_START("Google\\Protobuf\\Field_Kind",
"TYPE_SINT32", 11, 17 TSRMLS_CC);
zend_declare_class_constant_long(field_kind_type,
"TYPE_SINT64", 11, 18 TSRMLS_CC);
+ const char *alias = "Google\\Protobuf\\Field_Kind";
+ zend_register_class_alias_ex(alias, strlen(alias), field_kind_type TSRMLS_CC);
PHP_PROTO_INIT_ENUMCLASS_END
// -----------------------------------------------------------------------------
@@ -928,6 +1033,7 @@ PHP_METHOD(Any, unpack) {
PHP_PROTO_FAKE_SCOPE_BEGIN(any_type);
zval* type_url_php = php_proto_message_read_property(
getThis(), &type_url_member PHP_PROTO_TSRMLS_CC);
+ zval_dtor(&type_url_member);
PHP_PROTO_FAKE_SCOPE_END;
// Get fully-qualified name from type url.
@@ -938,7 +1044,7 @@ PHP_METHOD(Any, unpack) {
if (url_prefix_len > type_url_len ||
strncmp(TYPE_URL_PREFIX, type_url, url_prefix_len) != 0) {
zend_throw_exception(
- NULL, "Type url needs to be type.googleapis.com/fully-qulified",
+ NULL, "Type url needs to be type.googleapis.com/fully-qualified",
0 TSRMLS_CC);
return;
}
@@ -963,6 +1069,7 @@ PHP_METHOD(Any, unpack) {
PHP_PROTO_FAKE_SCOPE_RESTART(any_type);
zval* value = php_proto_message_read_property(
getThis(), &value_member PHP_PROTO_TSRMLS_CC);
+ zval_dtor(&value_member);
PHP_PROTO_FAKE_SCOPE_END;
merge_from_string(Z_STRVAL_P(value), Z_STRLEN_P(value), desc, msg);
@@ -991,6 +1098,8 @@ PHP_METHOD(Any, pack) {
PHP_PROTO_FAKE_SCOPE_BEGIN(any_type);
message_handlers->write_property(getThis(), &member, &data,
NULL PHP_PROTO_TSRMLS_CC);
+ zval_dtor(&data);
+ zval_dtor(&member);
PHP_PROTO_FAKE_SCOPE_END;
// Set type url.
@@ -1008,6 +1117,8 @@ PHP_METHOD(Any, pack) {
PHP_PROTO_FAKE_SCOPE_RESTART(any_type);
message_handlers->write_property(getThis(), &member, &type_url_php,
NULL PHP_PROTO_TSRMLS_CC);
+ zval_dtor(&type_url_php);
+ zval_dtor(&member);
PHP_PROTO_FAKE_SCOPE_END;
FREE(type_url);
}
@@ -1040,6 +1151,7 @@ PHP_METHOD(Any, is) {
PHP_PROTO_FAKE_SCOPE_BEGIN(any_type);
zval* value =
php_proto_message_read_property(getThis(), &member PHP_PROTO_TSRMLS_CC);
+ zval_dtor(&member);
PHP_PROTO_FAKE_SCOPE_END;
// Compare two type url.
diff --git a/php/ext/google/protobuf/package.xml b/php/ext/google/protobuf/package.xml
index 626eb46b..28d713f3 100644
--- a/php/ext/google/protobuf/package.xml
+++ b/php/ext/google/protobuf/package.xml
@@ -10,11 +10,11 @@
<email>protobuf-opensource@google.com</email>
<active>yes</active>
</lead>
- <date>2017-12-11</date>
+ <date>2018-06-06</date>
<time>11:02:07</time>
<version>
- <release>3.5.1</release>
- <api>3.5.1</api>
+ <release>3.6.0</release>
+ <api>3.6.0</api>
</version>
<stability>
<release>stable</release>
@@ -216,5 +216,37 @@ GA release.
GA release.
</notes>
</release>
+ <release>
+ <version>
+ <release>3.5.2</release>
+ <api>3.5.2</api>
+ </version>
+ <stability>
+ <release>stable</release>
+ <api>stable</api>
+ </stability>
+ <date>2018-03-06</date>
+ <time>11:02:07</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>
+G A release.
+ </notes>
+ </release>
+ <release>
+ <version>
+ <release>3.6.0</release>
+ <api>3.6.0</api>
+ </version>
+ <stability>
+ <release>stable</release>
+ <api>stable</api>
+ </stability>
+ <date>2018-06-06</date>
+ <time>11:02:07</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>
+G A release.
+ </notes>
+ </release>
</changelog>
</package>
diff --git a/php/ext/google/protobuf/protobuf.c b/php/ext/google/protobuf/protobuf.c
index daebb460..da00302f 100644
--- a/php/ext/google/protobuf/protobuf.c
+++ b/php/ext/google/protobuf/protobuf.c
@@ -145,6 +145,21 @@ PHP_PROTO_HASHTABLE_VALUE get_proto_obj(const char* proto) {
}
// -----------------------------------------------------------------------------
+// Well Known Types.
+// -----------------------------------------------------------------------------
+
+bool is_inited_file_any;
+bool is_inited_file_api;
+bool is_inited_file_duration;
+bool is_inited_file_field_mask;
+bool is_inited_file_empty;
+bool is_inited_file_source_context;
+bool is_inited_file_struct;
+bool is_inited_file_timestamp;
+bool is_inited_file_type;
+bool is_inited_file_wrappers;
+
+// -----------------------------------------------------------------------------
// Reserved Name.
// -----------------------------------------------------------------------------
@@ -250,6 +265,17 @@ static PHP_RINIT_FUNCTION(protobuf) {
generated_pool_php = NULL;
internal_generated_pool_php = NULL;
+ is_inited_file_any = false;
+ is_inited_file_api = false;
+ is_inited_file_duration = false;
+ is_inited_file_field_mask = false;
+ is_inited_file_empty = false;
+ is_inited_file_source_context = false;
+ is_inited_file_struct = false;
+ is_inited_file_timestamp = false;
+ is_inited_file_type = false;
+ is_inited_file_wrappers = false;
+
return 0;
}
@@ -288,6 +314,17 @@ static PHP_RSHUTDOWN_FUNCTION(protobuf) {
}
#endif
+ is_inited_file_any = true;
+ is_inited_file_api = true;
+ is_inited_file_duration = true;
+ is_inited_file_field_mask = true;
+ is_inited_file_empty = true;
+ is_inited_file_source_context = true;
+ is_inited_file_struct = true;
+ is_inited_file_timestamp = true;
+ is_inited_file_type = true;
+ is_inited_file_wrappers = true;
+
return 0;
}
diff --git a/php/ext/google/protobuf/protobuf.h b/php/ext/google/protobuf/protobuf.h
index 6ab0f134..20035ab7 100644
--- a/php/ext/google/protobuf/protobuf.h
+++ b/php/ext/google/protobuf/protobuf.h
@@ -37,7 +37,7 @@
#include "upb.h"
#define PHP_PROTOBUF_EXTNAME "protobuf"
-#define PHP_PROTOBUF_VERSION "3.5.1"
+#define PHP_PROTOBUF_VERSION "3.6.0"
#define MAX_LENGTH_OF_INT64 20
#define SIZEOF_INT64 8
@@ -1172,6 +1172,17 @@ extern zend_class_entry* oneof_descriptor_type;
// Well Known Type.
// -----------------------------------------------------------------------------
+extern bool is_inited_file_any;
+extern bool is_inited_file_api;
+extern bool is_inited_file_duration;
+extern bool is_inited_file_field_mask;
+extern bool is_inited_file_empty;
+extern bool is_inited_file_source_context;
+extern bool is_inited_file_struct;
+extern bool is_inited_file_timestamp;
+extern bool is_inited_file_type;
+extern bool is_inited_file_wrappers;
+
PHP_METHOD(GPBMetadata_Any, initOnce);
PHP_METHOD(GPBMetadata_Api, initOnce);
PHP_METHOD(GPBMetadata_Duration, initOnce);
diff --git a/php/ext/google/protobuf/upb.c b/php/ext/google/protobuf/upb.c
index c02a5ce4..e01f3bfd 100644
--- a/php/ext/google/protobuf/upb.c
+++ b/php/ext/google/protobuf/upb.c
@@ -1,9 +1,1908 @@
// Amalgamated source file
#include "upb.h"
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/descriptor.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+
+
+struct google_protobuf_FileDescriptorSet {
+ upb_array* file;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_FileDescriptorSet_submsgs[1] = {
+ &google_protobuf_FileDescriptorProto_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_FileDescriptorSet__fields[1] = {
+ {1, offsetof(google_protobuf_FileDescriptorSet, file), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_FileDescriptorSet_msginit = {
+ &google_protobuf_FileDescriptorSet_submsgs[0],
+ &google_protobuf_FileDescriptorSet__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_FileDescriptorSet), 1, 0, false, true
+};
+
+google_protobuf_FileDescriptorSet *google_protobuf_FileDescriptorSet_new(upb_env *env) {
+ google_protobuf_FileDescriptorSet *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_FileDescriptorSet *google_protobuf_FileDescriptorSet_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_FileDescriptorSet *msg = google_protobuf_FileDescriptorSet_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_FileDescriptorSet_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_FileDescriptorSet_serialize(google_protobuf_FileDescriptorSet *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_FileDescriptorSet_msginit, env, size);
+}
+const upb_array* google_protobuf_FileDescriptorSet_file(const google_protobuf_FileDescriptorSet *msg) {
+ return msg->file;
+}
+void google_protobuf_FileDescriptorSet_set_file(google_protobuf_FileDescriptorSet *msg, upb_array* value) {
+ msg->file = value;
+}
+struct google_protobuf_FileDescriptorProto {
+ upb_stringview name;
+ upb_stringview package;
+ upb_stringview syntax;
+ google_protobuf_FileOptions* options;
+ google_protobuf_SourceCodeInfo* source_code_info;
+ upb_array* dependency;
+ upb_array* message_type;
+ upb_array* enum_type;
+ upb_array* service;
+ upb_array* extension;
+ upb_array* public_dependency;
+ upb_array* weak_dependency;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_FileDescriptorProto_submsgs[6] = {
+ &google_protobuf_DescriptorProto_msginit,
+ &google_protobuf_EnumDescriptorProto_msginit,
+ &google_protobuf_FieldDescriptorProto_msginit,
+ &google_protobuf_FileOptions_msginit,
+ &google_protobuf_ServiceDescriptorProto_msginit,
+ &google_protobuf_SourceCodeInfo_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_FileDescriptorProto__fields[12] = {
+ {1, offsetof(google_protobuf_FileDescriptorProto, name), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {2, offsetof(google_protobuf_FileDescriptorProto, package), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {3, offsetof(google_protobuf_FileDescriptorProto, dependency), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 3},
+ {4, offsetof(google_protobuf_FileDescriptorProto, message_type), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+ {5, offsetof(google_protobuf_FileDescriptorProto, enum_type), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 1, 11, 3},
+ {6, offsetof(google_protobuf_FileDescriptorProto, service), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 4, 11, 3},
+ {7, offsetof(google_protobuf_FileDescriptorProto, extension), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 2, 11, 3},
+ {8, offsetof(google_protobuf_FileDescriptorProto, options), 3, UPB_NOT_IN_ONEOF, 3, 11, 1},
+ {9, offsetof(google_protobuf_FileDescriptorProto, source_code_info), 4, UPB_NOT_IN_ONEOF, 5, 11, 1},
+ {10, offsetof(google_protobuf_FileDescriptorProto, public_dependency), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 3},
+ {11, offsetof(google_protobuf_FileDescriptorProto, weak_dependency), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 3},
+ {12, offsetof(google_protobuf_FileDescriptorProto, syntax), 2, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_FileDescriptorProto_msginit = {
+ &google_protobuf_FileDescriptorProto_submsgs[0],
+ &google_protobuf_FileDescriptorProto__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_FileDescriptorProto), 12, 0, false, true
+};
+
+google_protobuf_FileDescriptorProto *google_protobuf_FileDescriptorProto_new(upb_env *env) {
+ google_protobuf_FileDescriptorProto *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_FileDescriptorProto *google_protobuf_FileDescriptorProto_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_FileDescriptorProto *msg = google_protobuf_FileDescriptorProto_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_FileDescriptorProto_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_FileDescriptorProto_serialize(google_protobuf_FileDescriptorProto *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_FileDescriptorProto_msginit, env, size);
+}
+upb_stringview google_protobuf_FileDescriptorProto_name(const google_protobuf_FileDescriptorProto *msg) {
+ return msg->name;
+}
+void google_protobuf_FileDescriptorProto_set_name(google_protobuf_FileDescriptorProto *msg, upb_stringview value) {
+ msg->name = value;
+}
+upb_stringview google_protobuf_FileDescriptorProto_package(const google_protobuf_FileDescriptorProto *msg) {
+ return msg->package;
+}
+void google_protobuf_FileDescriptorProto_set_package(google_protobuf_FileDescriptorProto *msg, upb_stringview value) {
+ msg->package = value;
+}
+const upb_array* google_protobuf_FileDescriptorProto_dependency(const google_protobuf_FileDescriptorProto *msg) {
+ return msg->dependency;
+}
+void google_protobuf_FileDescriptorProto_set_dependency(google_protobuf_FileDescriptorProto *msg, upb_array* value) {
+ msg->dependency = value;
+}
+const upb_array* google_protobuf_FileDescriptorProto_message_type(const google_protobuf_FileDescriptorProto *msg) {
+ return msg->message_type;
+}
+void google_protobuf_FileDescriptorProto_set_message_type(google_protobuf_FileDescriptorProto *msg, upb_array* value) {
+ msg->message_type = value;
+}
+const upb_array* google_protobuf_FileDescriptorProto_enum_type(const google_protobuf_FileDescriptorProto *msg) {
+ return msg->enum_type;
+}
+void google_protobuf_FileDescriptorProto_set_enum_type(google_protobuf_FileDescriptorProto *msg, upb_array* value) {
+ msg->enum_type = value;
+}
+const upb_array* google_protobuf_FileDescriptorProto_service(const google_protobuf_FileDescriptorProto *msg) {
+ return msg->service;
+}
+void google_protobuf_FileDescriptorProto_set_service(google_protobuf_FileDescriptorProto *msg, upb_array* value) {
+ msg->service = value;
+}
+const upb_array* google_protobuf_FileDescriptorProto_extension(const google_protobuf_FileDescriptorProto *msg) {
+ return msg->extension;
+}
+void google_protobuf_FileDescriptorProto_set_extension(google_protobuf_FileDescriptorProto *msg, upb_array* value) {
+ msg->extension = value;
+}
+const google_protobuf_FileOptions* google_protobuf_FileDescriptorProto_options(const google_protobuf_FileDescriptorProto *msg) {
+ return msg->options;
+}
+void google_protobuf_FileDescriptorProto_set_options(google_protobuf_FileDescriptorProto *msg, google_protobuf_FileOptions* value) {
+ msg->options = value;
+}
+const google_protobuf_SourceCodeInfo* google_protobuf_FileDescriptorProto_source_code_info(const google_protobuf_FileDescriptorProto *msg) {
+ return msg->source_code_info;
+}
+void google_protobuf_FileDescriptorProto_set_source_code_info(google_protobuf_FileDescriptorProto *msg, google_protobuf_SourceCodeInfo* value) {
+ msg->source_code_info = value;
+}
+const upb_array* google_protobuf_FileDescriptorProto_public_dependency(const google_protobuf_FileDescriptorProto *msg) {
+ return msg->public_dependency;
+}
+void google_protobuf_FileDescriptorProto_set_public_dependency(google_protobuf_FileDescriptorProto *msg, upb_array* value) {
+ msg->public_dependency = value;
+}
+const upb_array* google_protobuf_FileDescriptorProto_weak_dependency(const google_protobuf_FileDescriptorProto *msg) {
+ return msg->weak_dependency;
+}
+void google_protobuf_FileDescriptorProto_set_weak_dependency(google_protobuf_FileDescriptorProto *msg, upb_array* value) {
+ msg->weak_dependency = value;
+}
+upb_stringview google_protobuf_FileDescriptorProto_syntax(const google_protobuf_FileDescriptorProto *msg) {
+ return msg->syntax;
+}
+void google_protobuf_FileDescriptorProto_set_syntax(google_protobuf_FileDescriptorProto *msg, upb_stringview value) {
+ msg->syntax = value;
+}
+struct google_protobuf_DescriptorProto {
+ upb_stringview name;
+ google_protobuf_MessageOptions* options;
+ upb_array* field;
+ upb_array* nested_type;
+ upb_array* enum_type;
+ upb_array* extension_range;
+ upb_array* extension;
+ upb_array* oneof_decl;
+ upb_array* reserved_range;
+ upb_array* reserved_name;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_DescriptorProto_submsgs[8] = {
+ &google_protobuf_DescriptorProto_msginit,
+ &google_protobuf_DescriptorProto_ExtensionRange_msginit,
+ &google_protobuf_DescriptorProto_ReservedRange_msginit,
+ &google_protobuf_EnumDescriptorProto_msginit,
+ &google_protobuf_FieldDescriptorProto_msginit,
+ &google_protobuf_MessageOptions_msginit,
+ &google_protobuf_OneofDescriptorProto_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_DescriptorProto__fields[10] = {
+ {1, offsetof(google_protobuf_DescriptorProto, name), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {2, offsetof(google_protobuf_DescriptorProto, field), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 4, 11, 3},
+ {3, offsetof(google_protobuf_DescriptorProto, nested_type), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+ {4, offsetof(google_protobuf_DescriptorProto, enum_type), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 3, 11, 3},
+ {5, offsetof(google_protobuf_DescriptorProto, extension_range), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 1, 11, 3},
+ {6, offsetof(google_protobuf_DescriptorProto, extension), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 4, 11, 3},
+ {7, offsetof(google_protobuf_DescriptorProto, options), 1, UPB_NOT_IN_ONEOF, 5, 11, 1},
+ {8, offsetof(google_protobuf_DescriptorProto, oneof_decl), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 6, 11, 3},
+ {9, offsetof(google_protobuf_DescriptorProto, reserved_range), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 2, 11, 3},
+ {10, offsetof(google_protobuf_DescriptorProto, reserved_name), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 3},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_DescriptorProto_msginit = {
+ &google_protobuf_DescriptorProto_submsgs[0],
+ &google_protobuf_DescriptorProto__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_DescriptorProto), 10, 0, false, true
+};
+
+google_protobuf_DescriptorProto *google_protobuf_DescriptorProto_new(upb_env *env) {
+ google_protobuf_DescriptorProto *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_DescriptorProto *google_protobuf_DescriptorProto_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_DescriptorProto *msg = google_protobuf_DescriptorProto_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_DescriptorProto_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_DescriptorProto_serialize(google_protobuf_DescriptorProto *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_DescriptorProto_msginit, env, size);
+}
+upb_stringview google_protobuf_DescriptorProto_name(const google_protobuf_DescriptorProto *msg) {
+ return msg->name;
+}
+void google_protobuf_DescriptorProto_set_name(google_protobuf_DescriptorProto *msg, upb_stringview value) {
+ msg->name = value;
+}
+const upb_array* google_protobuf_DescriptorProto_field(const google_protobuf_DescriptorProto *msg) {
+ return msg->field;
+}
+void google_protobuf_DescriptorProto_set_field(google_protobuf_DescriptorProto *msg, upb_array* value) {
+ msg->field = value;
+}
+const upb_array* google_protobuf_DescriptorProto_nested_type(const google_protobuf_DescriptorProto *msg) {
+ return msg->nested_type;
+}
+void google_protobuf_DescriptorProto_set_nested_type(google_protobuf_DescriptorProto *msg, upb_array* value) {
+ msg->nested_type = value;
+}
+const upb_array* google_protobuf_DescriptorProto_enum_type(const google_protobuf_DescriptorProto *msg) {
+ return msg->enum_type;
+}
+void google_protobuf_DescriptorProto_set_enum_type(google_protobuf_DescriptorProto *msg, upb_array* value) {
+ msg->enum_type = value;
+}
+const upb_array* google_protobuf_DescriptorProto_extension_range(const google_protobuf_DescriptorProto *msg) {
+ return msg->extension_range;
+}
+void google_protobuf_DescriptorProto_set_extension_range(google_protobuf_DescriptorProto *msg, upb_array* value) {
+ msg->extension_range = value;
+}
+const upb_array* google_protobuf_DescriptorProto_extension(const google_protobuf_DescriptorProto *msg) {
+ return msg->extension;
+}
+void google_protobuf_DescriptorProto_set_extension(google_protobuf_DescriptorProto *msg, upb_array* value) {
+ msg->extension = value;
+}
+const google_protobuf_MessageOptions* google_protobuf_DescriptorProto_options(const google_protobuf_DescriptorProto *msg) {
+ return msg->options;
+}
+void google_protobuf_DescriptorProto_set_options(google_protobuf_DescriptorProto *msg, google_protobuf_MessageOptions* value) {
+ msg->options = value;
+}
+const upb_array* google_protobuf_DescriptorProto_oneof_decl(const google_protobuf_DescriptorProto *msg) {
+ return msg->oneof_decl;
+}
+void google_protobuf_DescriptorProto_set_oneof_decl(google_protobuf_DescriptorProto *msg, upb_array* value) {
+ msg->oneof_decl = value;
+}
+const upb_array* google_protobuf_DescriptorProto_reserved_range(const google_protobuf_DescriptorProto *msg) {
+ return msg->reserved_range;
+}
+void google_protobuf_DescriptorProto_set_reserved_range(google_protobuf_DescriptorProto *msg, upb_array* value) {
+ msg->reserved_range = value;
+}
+const upb_array* google_protobuf_DescriptorProto_reserved_name(const google_protobuf_DescriptorProto *msg) {
+ return msg->reserved_name;
+}
+void google_protobuf_DescriptorProto_set_reserved_name(google_protobuf_DescriptorProto *msg, upb_array* value) {
+ msg->reserved_name = value;
+}
+struct google_protobuf_DescriptorProto_ExtensionRange {
+ int32_t start;
+ int32_t end;
+ google_protobuf_ExtensionRangeOptions* options;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_DescriptorProto_ExtensionRange_submsgs[1] = {
+ &google_protobuf_ExtensionRangeOptions_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_DescriptorProto_ExtensionRange__fields[3] = {
+ {1, offsetof(google_protobuf_DescriptorProto_ExtensionRange, start), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 1},
+ {2, offsetof(google_protobuf_DescriptorProto_ExtensionRange, end), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 1},
+ {3, offsetof(google_protobuf_DescriptorProto_ExtensionRange, options), 2, UPB_NOT_IN_ONEOF, 0, 11, 1},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_DescriptorProto_ExtensionRange_msginit = {
+ &google_protobuf_DescriptorProto_ExtensionRange_submsgs[0],
+ &google_protobuf_DescriptorProto_ExtensionRange__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_DescriptorProto_ExtensionRange), 3, 0, false, true
+};
+
+google_protobuf_DescriptorProto_ExtensionRange *google_protobuf_DescriptorProto_ExtensionRange_new(upb_env *env) {
+ google_protobuf_DescriptorProto_ExtensionRange *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_DescriptorProto_ExtensionRange *google_protobuf_DescriptorProto_ExtensionRange_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_DescriptorProto_ExtensionRange *msg = google_protobuf_DescriptorProto_ExtensionRange_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_DescriptorProto_ExtensionRange_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_DescriptorProto_ExtensionRange_serialize(google_protobuf_DescriptorProto_ExtensionRange *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_DescriptorProto_ExtensionRange_msginit, env, size);
+}
+int32_t google_protobuf_DescriptorProto_ExtensionRange_start(const google_protobuf_DescriptorProto_ExtensionRange *msg) {
+ return msg->start;
+}
+void google_protobuf_DescriptorProto_ExtensionRange_set_start(google_protobuf_DescriptorProto_ExtensionRange *msg, int32_t value) {
+ msg->start = value;
+}
+int32_t google_protobuf_DescriptorProto_ExtensionRange_end(const google_protobuf_DescriptorProto_ExtensionRange *msg) {
+ return msg->end;
+}
+void google_protobuf_DescriptorProto_ExtensionRange_set_end(google_protobuf_DescriptorProto_ExtensionRange *msg, int32_t value) {
+ msg->end = value;
+}
+const google_protobuf_ExtensionRangeOptions* google_protobuf_DescriptorProto_ExtensionRange_options(const google_protobuf_DescriptorProto_ExtensionRange *msg) {
+ return msg->options;
+}
+void google_protobuf_DescriptorProto_ExtensionRange_set_options(google_protobuf_DescriptorProto_ExtensionRange *msg, google_protobuf_ExtensionRangeOptions* value) {
+ msg->options = value;
+}
+struct google_protobuf_DescriptorProto_ReservedRange {
+ int32_t start;
+ int32_t end;
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_DescriptorProto_ReservedRange__fields[2] = {
+ {1, offsetof(google_protobuf_DescriptorProto_ReservedRange, start), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 1},
+ {2, offsetof(google_protobuf_DescriptorProto_ReservedRange, end), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 1},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_DescriptorProto_ReservedRange_msginit = {
+ NULL,
+ &google_protobuf_DescriptorProto_ReservedRange__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_DescriptorProto_ReservedRange), 2, 0, false, true
+};
+
+google_protobuf_DescriptorProto_ReservedRange *google_protobuf_DescriptorProto_ReservedRange_new(upb_env *env) {
+ google_protobuf_DescriptorProto_ReservedRange *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_DescriptorProto_ReservedRange *google_protobuf_DescriptorProto_ReservedRange_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_DescriptorProto_ReservedRange *msg = google_protobuf_DescriptorProto_ReservedRange_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_DescriptorProto_ReservedRange_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_DescriptorProto_ReservedRange_serialize(google_protobuf_DescriptorProto_ReservedRange *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_DescriptorProto_ReservedRange_msginit, env, size);
+}
+int32_t google_protobuf_DescriptorProto_ReservedRange_start(const google_protobuf_DescriptorProto_ReservedRange *msg) {
+ return msg->start;
+}
+void google_protobuf_DescriptorProto_ReservedRange_set_start(google_protobuf_DescriptorProto_ReservedRange *msg, int32_t value) {
+ msg->start = value;
+}
+int32_t google_protobuf_DescriptorProto_ReservedRange_end(const google_protobuf_DescriptorProto_ReservedRange *msg) {
+ return msg->end;
+}
+void google_protobuf_DescriptorProto_ReservedRange_set_end(google_protobuf_DescriptorProto_ReservedRange *msg, int32_t value) {
+ msg->end = value;
+}
+struct google_protobuf_ExtensionRangeOptions {
+ upb_array* uninterpreted_option;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_ExtensionRangeOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_ExtensionRangeOptions__fields[1] = {
+ {999, offsetof(google_protobuf_ExtensionRangeOptions, uninterpreted_option), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_ExtensionRangeOptions_msginit = {
+ &google_protobuf_ExtensionRangeOptions_submsgs[0],
+ &google_protobuf_ExtensionRangeOptions__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_ExtensionRangeOptions), 1, 0, false, true
+};
+
+google_protobuf_ExtensionRangeOptions *google_protobuf_ExtensionRangeOptions_new(upb_env *env) {
+ google_protobuf_ExtensionRangeOptions *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_ExtensionRangeOptions *google_protobuf_ExtensionRangeOptions_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_ExtensionRangeOptions *msg = google_protobuf_ExtensionRangeOptions_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_ExtensionRangeOptions_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_ExtensionRangeOptions_serialize(google_protobuf_ExtensionRangeOptions *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_ExtensionRangeOptions_msginit, env, size);
+}
+const upb_array* google_protobuf_ExtensionRangeOptions_uninterpreted_option(const google_protobuf_ExtensionRangeOptions *msg) {
+ return msg->uninterpreted_option;
+}
+void google_protobuf_ExtensionRangeOptions_set_uninterpreted_option(google_protobuf_ExtensionRangeOptions *msg, upb_array* value) {
+ msg->uninterpreted_option = value;
+}
+struct google_protobuf_FieldDescriptorProto {
+ google_protobuf_FieldDescriptorProto_Label label;
+ google_protobuf_FieldDescriptorProto_Type type;
+ int32_t number;
+ int32_t oneof_index;
+ upb_stringview name;
+ upb_stringview extendee;
+ upb_stringview type_name;
+ upb_stringview default_value;
+ upb_stringview json_name;
+ google_protobuf_FieldOptions* options;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_FieldDescriptorProto_submsgs[1] = {
+ &google_protobuf_FieldOptions_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_FieldDescriptorProto__fields[10] = {
+ {1, offsetof(google_protobuf_FieldDescriptorProto, name), 4, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {2, offsetof(google_protobuf_FieldDescriptorProto, extendee), 5, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {3, offsetof(google_protobuf_FieldDescriptorProto, number), 2, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 1},
+ {4, offsetof(google_protobuf_FieldDescriptorProto, label), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 14, 1},
+ {5, offsetof(google_protobuf_FieldDescriptorProto, type), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 14, 1},
+ {6, offsetof(google_protobuf_FieldDescriptorProto, type_name), 6, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {7, offsetof(google_protobuf_FieldDescriptorProto, default_value), 7, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {8, offsetof(google_protobuf_FieldDescriptorProto, options), 9, UPB_NOT_IN_ONEOF, 0, 11, 1},
+ {9, offsetof(google_protobuf_FieldDescriptorProto, oneof_index), 3, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 1},
+ {10, offsetof(google_protobuf_FieldDescriptorProto, json_name), 8, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_FieldDescriptorProto_msginit = {
+ &google_protobuf_FieldDescriptorProto_submsgs[0],
+ &google_protobuf_FieldDescriptorProto__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_FieldDescriptorProto), 10, 0, false, true
+};
+
+google_protobuf_FieldDescriptorProto *google_protobuf_FieldDescriptorProto_new(upb_env *env) {
+ google_protobuf_FieldDescriptorProto *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_FieldDescriptorProto *google_protobuf_FieldDescriptorProto_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_FieldDescriptorProto *msg = google_protobuf_FieldDescriptorProto_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_FieldDescriptorProto_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_FieldDescriptorProto_serialize(google_protobuf_FieldDescriptorProto *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_FieldDescriptorProto_msginit, env, size);
+}
+upb_stringview google_protobuf_FieldDescriptorProto_name(const google_protobuf_FieldDescriptorProto *msg) {
+ return msg->name;
+}
+void google_protobuf_FieldDescriptorProto_set_name(google_protobuf_FieldDescriptorProto *msg, upb_stringview value) {
+ msg->name = value;
+}
+upb_stringview google_protobuf_FieldDescriptorProto_extendee(const google_protobuf_FieldDescriptorProto *msg) {
+ return msg->extendee;
+}
+void google_protobuf_FieldDescriptorProto_set_extendee(google_protobuf_FieldDescriptorProto *msg, upb_stringview value) {
+ msg->extendee = value;
+}
+int32_t google_protobuf_FieldDescriptorProto_number(const google_protobuf_FieldDescriptorProto *msg) {
+ return msg->number;
+}
+void google_protobuf_FieldDescriptorProto_set_number(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
+ msg->number = value;
+}
+google_protobuf_FieldDescriptorProto_Label google_protobuf_FieldDescriptorProto_label(const google_protobuf_FieldDescriptorProto *msg) {
+ return msg->label;
+}
+void google_protobuf_FieldDescriptorProto_set_label(google_protobuf_FieldDescriptorProto *msg, google_protobuf_FieldDescriptorProto_Label value) {
+ msg->label = value;
+}
+google_protobuf_FieldDescriptorProto_Type google_protobuf_FieldDescriptorProto_type(const google_protobuf_FieldDescriptorProto *msg) {
+ return msg->type;
+}
+void google_protobuf_FieldDescriptorProto_set_type(google_protobuf_FieldDescriptorProto *msg, google_protobuf_FieldDescriptorProto_Type value) {
+ msg->type = value;
+}
+upb_stringview google_protobuf_FieldDescriptorProto_type_name(const google_protobuf_FieldDescriptorProto *msg) {
+ return msg->type_name;
+}
+void google_protobuf_FieldDescriptorProto_set_type_name(google_protobuf_FieldDescriptorProto *msg, upb_stringview value) {
+ msg->type_name = value;
+}
+upb_stringview google_protobuf_FieldDescriptorProto_default_value(const google_protobuf_FieldDescriptorProto *msg) {
+ return msg->default_value;
+}
+void google_protobuf_FieldDescriptorProto_set_default_value(google_protobuf_FieldDescriptorProto *msg, upb_stringview value) {
+ msg->default_value = value;
+}
+const google_protobuf_FieldOptions* google_protobuf_FieldDescriptorProto_options(const google_protobuf_FieldDescriptorProto *msg) {
+ return msg->options;
+}
+void google_protobuf_FieldDescriptorProto_set_options(google_protobuf_FieldDescriptorProto *msg, google_protobuf_FieldOptions* value) {
+ msg->options = value;
+}
+int32_t google_protobuf_FieldDescriptorProto_oneof_index(const google_protobuf_FieldDescriptorProto *msg) {
+ return msg->oneof_index;
+}
+void google_protobuf_FieldDescriptorProto_set_oneof_index(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
+ msg->oneof_index = value;
+}
+upb_stringview google_protobuf_FieldDescriptorProto_json_name(const google_protobuf_FieldDescriptorProto *msg) {
+ return msg->json_name;
+}
+void google_protobuf_FieldDescriptorProto_set_json_name(google_protobuf_FieldDescriptorProto *msg, upb_stringview value) {
+ msg->json_name = value;
+}
+struct google_protobuf_OneofDescriptorProto {
+ upb_stringview name;
+ google_protobuf_OneofOptions* options;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_OneofDescriptorProto_submsgs[1] = {
+ &google_protobuf_OneofOptions_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_OneofDescriptorProto__fields[2] = {
+ {1, offsetof(google_protobuf_OneofDescriptorProto, name), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {2, offsetof(google_protobuf_OneofDescriptorProto, options), 1, UPB_NOT_IN_ONEOF, 0, 11, 1},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_OneofDescriptorProto_msginit = {
+ &google_protobuf_OneofDescriptorProto_submsgs[0],
+ &google_protobuf_OneofDescriptorProto__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_OneofDescriptorProto), 2, 0, false, true
+};
+
+google_protobuf_OneofDescriptorProto *google_protobuf_OneofDescriptorProto_new(upb_env *env) {
+ google_protobuf_OneofDescriptorProto *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_OneofDescriptorProto *google_protobuf_OneofDescriptorProto_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_OneofDescriptorProto *msg = google_protobuf_OneofDescriptorProto_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_OneofDescriptorProto_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_OneofDescriptorProto_serialize(google_protobuf_OneofDescriptorProto *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_OneofDescriptorProto_msginit, env, size);
+}
+upb_stringview google_protobuf_OneofDescriptorProto_name(const google_protobuf_OneofDescriptorProto *msg) {
+ return msg->name;
+}
+void google_protobuf_OneofDescriptorProto_set_name(google_protobuf_OneofDescriptorProto *msg, upb_stringview value) {
+ msg->name = value;
+}
+const google_protobuf_OneofOptions* google_protobuf_OneofDescriptorProto_options(const google_protobuf_OneofDescriptorProto *msg) {
+ return msg->options;
+}
+void google_protobuf_OneofDescriptorProto_set_options(google_protobuf_OneofDescriptorProto *msg, google_protobuf_OneofOptions* value) {
+ msg->options = value;
+}
+struct google_protobuf_EnumDescriptorProto {
+ upb_stringview name;
+ google_protobuf_EnumOptions* options;
+ upb_array* value;
+ upb_array* reserved_range;
+ upb_array* reserved_name;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_EnumDescriptorProto_submsgs[3] = {
+ &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit,
+ &google_protobuf_EnumOptions_msginit,
+ &google_protobuf_EnumValueDescriptorProto_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_EnumDescriptorProto__fields[5] = {
+ {1, offsetof(google_protobuf_EnumDescriptorProto, name), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {2, offsetof(google_protobuf_EnumDescriptorProto, value), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 2, 11, 3},
+ {3, offsetof(google_protobuf_EnumDescriptorProto, options), 1, UPB_NOT_IN_ONEOF, 1, 11, 1},
+ {4, offsetof(google_protobuf_EnumDescriptorProto, reserved_range), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+ {5, offsetof(google_protobuf_EnumDescriptorProto, reserved_name), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 3},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_EnumDescriptorProto_msginit = {
+ &google_protobuf_EnumDescriptorProto_submsgs[0],
+ &google_protobuf_EnumDescriptorProto__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_EnumDescriptorProto), 5, 0, false, true
+};
+
+google_protobuf_EnumDescriptorProto *google_protobuf_EnumDescriptorProto_new(upb_env *env) {
+ google_protobuf_EnumDescriptorProto *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_EnumDescriptorProto *google_protobuf_EnumDescriptorProto_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_EnumDescriptorProto *msg = google_protobuf_EnumDescriptorProto_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_EnumDescriptorProto_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_EnumDescriptorProto_serialize(google_protobuf_EnumDescriptorProto *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_EnumDescriptorProto_msginit, env, size);
+}
+upb_stringview google_protobuf_EnumDescriptorProto_name(const google_protobuf_EnumDescriptorProto *msg) {
+ return msg->name;
+}
+void google_protobuf_EnumDescriptorProto_set_name(google_protobuf_EnumDescriptorProto *msg, upb_stringview value) {
+ msg->name = value;
+}
+const upb_array* google_protobuf_EnumDescriptorProto_value(const google_protobuf_EnumDescriptorProto *msg) {
+ return msg->value;
+}
+void google_protobuf_EnumDescriptorProto_set_value(google_protobuf_EnumDescriptorProto *msg, upb_array* value) {
+ msg->value = value;
+}
+const google_protobuf_EnumOptions* google_protobuf_EnumDescriptorProto_options(const google_protobuf_EnumDescriptorProto *msg) {
+ return msg->options;
+}
+void google_protobuf_EnumDescriptorProto_set_options(google_protobuf_EnumDescriptorProto *msg, google_protobuf_EnumOptions* value) {
+ msg->options = value;
+}
+const upb_array* google_protobuf_EnumDescriptorProto_reserved_range(const google_protobuf_EnumDescriptorProto *msg) {
+ return msg->reserved_range;
+}
+void google_protobuf_EnumDescriptorProto_set_reserved_range(google_protobuf_EnumDescriptorProto *msg, upb_array* value) {
+ msg->reserved_range = value;
+}
+const upb_array* google_protobuf_EnumDescriptorProto_reserved_name(const google_protobuf_EnumDescriptorProto *msg) {
+ return msg->reserved_name;
+}
+void google_protobuf_EnumDescriptorProto_set_reserved_name(google_protobuf_EnumDescriptorProto *msg, upb_array* value) {
+ msg->reserved_name = value;
+}
+struct google_protobuf_EnumDescriptorProto_EnumReservedRange {
+ int32_t start;
+ int32_t end;
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[2] = {
+ {1, offsetof(google_protobuf_EnumDescriptorProto_EnumReservedRange, start), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 1},
+ {2, offsetof(google_protobuf_EnumDescriptorProto_EnumReservedRange, end), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 1},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit = {
+ NULL,
+ &google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_EnumDescriptorProto_EnumReservedRange), 2, 0, false, true
+};
+
+google_protobuf_EnumDescriptorProto_EnumReservedRange *google_protobuf_EnumDescriptorProto_EnumReservedRange_new(upb_env *env) {
+ google_protobuf_EnumDescriptorProto_EnumReservedRange *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_EnumDescriptorProto_EnumReservedRange *google_protobuf_EnumDescriptorProto_EnumReservedRange_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_EnumDescriptorProto_EnumReservedRange *msg = google_protobuf_EnumDescriptorProto_EnumReservedRange_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_EnumDescriptorProto_EnumReservedRange_serialize(google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, env, size);
+}
+int32_t google_protobuf_EnumDescriptorProto_EnumReservedRange_start(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) {
+ return msg->start;
+}
+void google_protobuf_EnumDescriptorProto_EnumReservedRange_set_start(google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, int32_t value) {
+ msg->start = value;
+}
+int32_t google_protobuf_EnumDescriptorProto_EnumReservedRange_end(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) {
+ return msg->end;
+}
+void google_protobuf_EnumDescriptorProto_EnumReservedRange_set_end(google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, int32_t value) {
+ msg->end = value;
+}
+struct google_protobuf_EnumValueDescriptorProto {
+ int32_t number;
+ upb_stringview name;
+ google_protobuf_EnumValueOptions* options;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_EnumValueDescriptorProto_submsgs[1] = {
+ &google_protobuf_EnumValueOptions_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_EnumValueDescriptorProto__fields[3] = {
+ {1, offsetof(google_protobuf_EnumValueDescriptorProto, name), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {2, offsetof(google_protobuf_EnumValueDescriptorProto, number), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 1},
+ {3, offsetof(google_protobuf_EnumValueDescriptorProto, options), 2, UPB_NOT_IN_ONEOF, 0, 11, 1},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_EnumValueDescriptorProto_msginit = {
+ &google_protobuf_EnumValueDescriptorProto_submsgs[0],
+ &google_protobuf_EnumValueDescriptorProto__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_EnumValueDescriptorProto), 3, 0, false, true
+};
+
+google_protobuf_EnumValueDescriptorProto *google_protobuf_EnumValueDescriptorProto_new(upb_env *env) {
+ google_protobuf_EnumValueDescriptorProto *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_EnumValueDescriptorProto *google_protobuf_EnumValueDescriptorProto_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_EnumValueDescriptorProto *msg = google_protobuf_EnumValueDescriptorProto_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_EnumValueDescriptorProto_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_EnumValueDescriptorProto_serialize(google_protobuf_EnumValueDescriptorProto *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_EnumValueDescriptorProto_msginit, env, size);
+}
+upb_stringview google_protobuf_EnumValueDescriptorProto_name(const google_protobuf_EnumValueDescriptorProto *msg) {
+ return msg->name;
+}
+void google_protobuf_EnumValueDescriptorProto_set_name(google_protobuf_EnumValueDescriptorProto *msg, upb_stringview value) {
+ msg->name = value;
+}
+int32_t google_protobuf_EnumValueDescriptorProto_number(const google_protobuf_EnumValueDescriptorProto *msg) {
+ return msg->number;
+}
+void google_protobuf_EnumValueDescriptorProto_set_number(google_protobuf_EnumValueDescriptorProto *msg, int32_t value) {
+ msg->number = value;
+}
+const google_protobuf_EnumValueOptions* google_protobuf_EnumValueDescriptorProto_options(const google_protobuf_EnumValueDescriptorProto *msg) {
+ return msg->options;
+}
+void google_protobuf_EnumValueDescriptorProto_set_options(google_protobuf_EnumValueDescriptorProto *msg, google_protobuf_EnumValueOptions* value) {
+ msg->options = value;
+}
+struct google_protobuf_ServiceDescriptorProto {
+ upb_stringview name;
+ google_protobuf_ServiceOptions* options;
+ upb_array* method;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_ServiceDescriptorProto_submsgs[2] = {
+ &google_protobuf_MethodDescriptorProto_msginit,
+ &google_protobuf_ServiceOptions_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_ServiceDescriptorProto__fields[3] = {
+ {1, offsetof(google_protobuf_ServiceDescriptorProto, name), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {2, offsetof(google_protobuf_ServiceDescriptorProto, method), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+ {3, offsetof(google_protobuf_ServiceDescriptorProto, options), 1, UPB_NOT_IN_ONEOF, 1, 11, 1},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_ServiceDescriptorProto_msginit = {
+ &google_protobuf_ServiceDescriptorProto_submsgs[0],
+ &google_protobuf_ServiceDescriptorProto__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_ServiceDescriptorProto), 3, 0, false, true
+};
+
+google_protobuf_ServiceDescriptorProto *google_protobuf_ServiceDescriptorProto_new(upb_env *env) {
+ google_protobuf_ServiceDescriptorProto *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_ServiceDescriptorProto *google_protobuf_ServiceDescriptorProto_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_ServiceDescriptorProto *msg = google_protobuf_ServiceDescriptorProto_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_ServiceDescriptorProto_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_ServiceDescriptorProto_serialize(google_protobuf_ServiceDescriptorProto *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_ServiceDescriptorProto_msginit, env, size);
+}
+upb_stringview google_protobuf_ServiceDescriptorProto_name(const google_protobuf_ServiceDescriptorProto *msg) {
+ return msg->name;
+}
+void google_protobuf_ServiceDescriptorProto_set_name(google_protobuf_ServiceDescriptorProto *msg, upb_stringview value) {
+ msg->name = value;
+}
+const upb_array* google_protobuf_ServiceDescriptorProto_method(const google_protobuf_ServiceDescriptorProto *msg) {
+ return msg->method;
+}
+void google_protobuf_ServiceDescriptorProto_set_method(google_protobuf_ServiceDescriptorProto *msg, upb_array* value) {
+ msg->method = value;
+}
+const google_protobuf_ServiceOptions* google_protobuf_ServiceDescriptorProto_options(const google_protobuf_ServiceDescriptorProto *msg) {
+ return msg->options;
+}
+void google_protobuf_ServiceDescriptorProto_set_options(google_protobuf_ServiceDescriptorProto *msg, google_protobuf_ServiceOptions* value) {
+ msg->options = value;
+}
+struct google_protobuf_MethodDescriptorProto {
+ bool client_streaming;
+ bool server_streaming;
+ upb_stringview name;
+ upb_stringview input_type;
+ upb_stringview output_type;
+ google_protobuf_MethodOptions* options;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_MethodDescriptorProto_submsgs[1] = {
+ &google_protobuf_MethodOptions_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_MethodDescriptorProto__fields[6] = {
+ {1, offsetof(google_protobuf_MethodDescriptorProto, name), 2, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {2, offsetof(google_protobuf_MethodDescriptorProto, input_type), 3, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {3, offsetof(google_protobuf_MethodDescriptorProto, output_type), 4, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {4, offsetof(google_protobuf_MethodDescriptorProto, options), 5, UPB_NOT_IN_ONEOF, 0, 11, 1},
+ {5, offsetof(google_protobuf_MethodDescriptorProto, client_streaming), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {6, offsetof(google_protobuf_MethodDescriptorProto, server_streaming), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_MethodDescriptorProto_msginit = {
+ &google_protobuf_MethodDescriptorProto_submsgs[0],
+ &google_protobuf_MethodDescriptorProto__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_MethodDescriptorProto), 6, 0, false, true
+};
+
+google_protobuf_MethodDescriptorProto *google_protobuf_MethodDescriptorProto_new(upb_env *env) {
+ google_protobuf_MethodDescriptorProto *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_MethodDescriptorProto *google_protobuf_MethodDescriptorProto_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_MethodDescriptorProto *msg = google_protobuf_MethodDescriptorProto_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_MethodDescriptorProto_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_MethodDescriptorProto_serialize(google_protobuf_MethodDescriptorProto *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_MethodDescriptorProto_msginit, env, size);
+}
+upb_stringview google_protobuf_MethodDescriptorProto_name(const google_protobuf_MethodDescriptorProto *msg) {
+ return msg->name;
+}
+void google_protobuf_MethodDescriptorProto_set_name(google_protobuf_MethodDescriptorProto *msg, upb_stringview value) {
+ msg->name = value;
+}
+upb_stringview google_protobuf_MethodDescriptorProto_input_type(const google_protobuf_MethodDescriptorProto *msg) {
+ return msg->input_type;
+}
+void google_protobuf_MethodDescriptorProto_set_input_type(google_protobuf_MethodDescriptorProto *msg, upb_stringview value) {
+ msg->input_type = value;
+}
+upb_stringview google_protobuf_MethodDescriptorProto_output_type(const google_protobuf_MethodDescriptorProto *msg) {
+ return msg->output_type;
+}
+void google_protobuf_MethodDescriptorProto_set_output_type(google_protobuf_MethodDescriptorProto *msg, upb_stringview value) {
+ msg->output_type = value;
+}
+const google_protobuf_MethodOptions* google_protobuf_MethodDescriptorProto_options(const google_protobuf_MethodDescriptorProto *msg) {
+ return msg->options;
+}
+void google_protobuf_MethodDescriptorProto_set_options(google_protobuf_MethodDescriptorProto *msg, google_protobuf_MethodOptions* value) {
+ msg->options = value;
+}
+bool google_protobuf_MethodDescriptorProto_client_streaming(const google_protobuf_MethodDescriptorProto *msg) {
+ return msg->client_streaming;
+}
+void google_protobuf_MethodDescriptorProto_set_client_streaming(google_protobuf_MethodDescriptorProto *msg, bool value) {
+ msg->client_streaming = value;
+}
+bool google_protobuf_MethodDescriptorProto_server_streaming(const google_protobuf_MethodDescriptorProto *msg) {
+ return msg->server_streaming;
+}
+void google_protobuf_MethodDescriptorProto_set_server_streaming(google_protobuf_MethodDescriptorProto *msg, bool value) {
+ msg->server_streaming = value;
+}
+struct google_protobuf_FileOptions {
+ google_protobuf_FileOptions_OptimizeMode optimize_for;
+ bool java_multiple_files;
+ bool cc_generic_services;
+ bool java_generic_services;
+ bool py_generic_services;
+ bool java_generate_equals_and_hash;
+ bool deprecated;
+ bool java_string_check_utf8;
+ bool cc_enable_arenas;
+ bool php_generic_services;
+ upb_stringview java_package;
+ upb_stringview java_outer_classname;
+ upb_stringview go_package;
+ upb_stringview objc_class_prefix;
+ upb_stringview csharp_namespace;
+ upb_stringview swift_prefix;
+ upb_stringview php_class_prefix;
+ upb_stringview php_namespace;
+ upb_array* uninterpreted_option;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_FileOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_FileOptions__fields[19] = {
+ {1, offsetof(google_protobuf_FileOptions, java_package), 10, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {8, offsetof(google_protobuf_FileOptions, java_outer_classname), 11, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {9, offsetof(google_protobuf_FileOptions, optimize_for), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 14, 1},
+ {10, offsetof(google_protobuf_FileOptions, java_multiple_files), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {11, offsetof(google_protobuf_FileOptions, go_package), 12, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {16, offsetof(google_protobuf_FileOptions, cc_generic_services), 2, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {17, offsetof(google_protobuf_FileOptions, java_generic_services), 3, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {18, offsetof(google_protobuf_FileOptions, py_generic_services), 4, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {20, offsetof(google_protobuf_FileOptions, java_generate_equals_and_hash), 5, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {23, offsetof(google_protobuf_FileOptions, deprecated), 6, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {27, offsetof(google_protobuf_FileOptions, java_string_check_utf8), 7, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {31, offsetof(google_protobuf_FileOptions, cc_enable_arenas), 8, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {36, offsetof(google_protobuf_FileOptions, objc_class_prefix), 13, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {37, offsetof(google_protobuf_FileOptions, csharp_namespace), 14, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {39, offsetof(google_protobuf_FileOptions, swift_prefix), 15, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {40, offsetof(google_protobuf_FileOptions, php_class_prefix), 16, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {41, offsetof(google_protobuf_FileOptions, php_namespace), 17, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {42, offsetof(google_protobuf_FileOptions, php_generic_services), 9, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {999, offsetof(google_protobuf_FileOptions, uninterpreted_option), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_FileOptions_msginit = {
+ &google_protobuf_FileOptions_submsgs[0],
+ &google_protobuf_FileOptions__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_FileOptions), 19, 0, false, true
+};
+
+google_protobuf_FileOptions *google_protobuf_FileOptions_new(upb_env *env) {
+ google_protobuf_FileOptions *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_FileOptions *google_protobuf_FileOptions_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_FileOptions *msg = google_protobuf_FileOptions_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_FileOptions_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_FileOptions_serialize(google_protobuf_FileOptions *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_FileOptions_msginit, env, size);
+}
+upb_stringview google_protobuf_FileOptions_java_package(const google_protobuf_FileOptions *msg) {
+ return msg->java_package;
+}
+void google_protobuf_FileOptions_set_java_package(google_protobuf_FileOptions *msg, upb_stringview value) {
+ msg->java_package = value;
+}
+upb_stringview google_protobuf_FileOptions_java_outer_classname(const google_protobuf_FileOptions *msg) {
+ return msg->java_outer_classname;
+}
+void google_protobuf_FileOptions_set_java_outer_classname(google_protobuf_FileOptions *msg, upb_stringview value) {
+ msg->java_outer_classname = value;
+}
+google_protobuf_FileOptions_OptimizeMode google_protobuf_FileOptions_optimize_for(const google_protobuf_FileOptions *msg) {
+ return msg->optimize_for;
+}
+void google_protobuf_FileOptions_set_optimize_for(google_protobuf_FileOptions *msg, google_protobuf_FileOptions_OptimizeMode value) {
+ msg->optimize_for = value;
+}
+bool google_protobuf_FileOptions_java_multiple_files(const google_protobuf_FileOptions *msg) {
+ return msg->java_multiple_files;
+}
+void google_protobuf_FileOptions_set_java_multiple_files(google_protobuf_FileOptions *msg, bool value) {
+ msg->java_multiple_files = value;
+}
+upb_stringview google_protobuf_FileOptions_go_package(const google_protobuf_FileOptions *msg) {
+ return msg->go_package;
+}
+void google_protobuf_FileOptions_set_go_package(google_protobuf_FileOptions *msg, upb_stringview value) {
+ msg->go_package = value;
+}
+bool google_protobuf_FileOptions_cc_generic_services(const google_protobuf_FileOptions *msg) {
+ return msg->cc_generic_services;
+}
+void google_protobuf_FileOptions_set_cc_generic_services(google_protobuf_FileOptions *msg, bool value) {
+ msg->cc_generic_services = value;
+}
+bool google_protobuf_FileOptions_java_generic_services(const google_protobuf_FileOptions *msg) {
+ return msg->java_generic_services;
+}
+void google_protobuf_FileOptions_set_java_generic_services(google_protobuf_FileOptions *msg, bool value) {
+ msg->java_generic_services = value;
+}
+bool google_protobuf_FileOptions_py_generic_services(const google_protobuf_FileOptions *msg) {
+ return msg->py_generic_services;
+}
+void google_protobuf_FileOptions_set_py_generic_services(google_protobuf_FileOptions *msg, bool value) {
+ msg->py_generic_services = value;
+}
+bool google_protobuf_FileOptions_java_generate_equals_and_hash(const google_protobuf_FileOptions *msg) {
+ return msg->java_generate_equals_and_hash;
+}
+void google_protobuf_FileOptions_set_java_generate_equals_and_hash(google_protobuf_FileOptions *msg, bool value) {
+ msg->java_generate_equals_and_hash = value;
+}
+bool google_protobuf_FileOptions_deprecated(const google_protobuf_FileOptions *msg) {
+ return msg->deprecated;
+}
+void google_protobuf_FileOptions_set_deprecated(google_protobuf_FileOptions *msg, bool value) {
+ msg->deprecated = value;
+}
+bool google_protobuf_FileOptions_java_string_check_utf8(const google_protobuf_FileOptions *msg) {
+ return msg->java_string_check_utf8;
+}
+void google_protobuf_FileOptions_set_java_string_check_utf8(google_protobuf_FileOptions *msg, bool value) {
+ msg->java_string_check_utf8 = value;
+}
+bool google_protobuf_FileOptions_cc_enable_arenas(const google_protobuf_FileOptions *msg) {
+ return msg->cc_enable_arenas;
+}
+void google_protobuf_FileOptions_set_cc_enable_arenas(google_protobuf_FileOptions *msg, bool value) {
+ msg->cc_enable_arenas = value;
+}
+upb_stringview google_protobuf_FileOptions_objc_class_prefix(const google_protobuf_FileOptions *msg) {
+ return msg->objc_class_prefix;
+}
+void google_protobuf_FileOptions_set_objc_class_prefix(google_protobuf_FileOptions *msg, upb_stringview value) {
+ msg->objc_class_prefix = value;
+}
+upb_stringview google_protobuf_FileOptions_csharp_namespace(const google_protobuf_FileOptions *msg) {
+ return msg->csharp_namespace;
+}
+void google_protobuf_FileOptions_set_csharp_namespace(google_protobuf_FileOptions *msg, upb_stringview value) {
+ msg->csharp_namespace = value;
+}
+upb_stringview google_protobuf_FileOptions_swift_prefix(const google_protobuf_FileOptions *msg) {
+ return msg->swift_prefix;
+}
+void google_protobuf_FileOptions_set_swift_prefix(google_protobuf_FileOptions *msg, upb_stringview value) {
+ msg->swift_prefix = value;
+}
+upb_stringview google_protobuf_FileOptions_php_class_prefix(const google_protobuf_FileOptions *msg) {
+ return msg->php_class_prefix;
+}
+void google_protobuf_FileOptions_set_php_class_prefix(google_protobuf_FileOptions *msg, upb_stringview value) {
+ msg->php_class_prefix = value;
+}
+upb_stringview google_protobuf_FileOptions_php_namespace(const google_protobuf_FileOptions *msg) {
+ return msg->php_namespace;
+}
+void google_protobuf_FileOptions_set_php_namespace(google_protobuf_FileOptions *msg, upb_stringview value) {
+ msg->php_namespace = value;
+}
+bool google_protobuf_FileOptions_php_generic_services(const google_protobuf_FileOptions *msg) {
+ return msg->php_generic_services;
+}
+void google_protobuf_FileOptions_set_php_generic_services(google_protobuf_FileOptions *msg, bool value) {
+ msg->php_generic_services = value;
+}
+const upb_array* google_protobuf_FileOptions_uninterpreted_option(const google_protobuf_FileOptions *msg) {
+ return msg->uninterpreted_option;
+}
+void google_protobuf_FileOptions_set_uninterpreted_option(google_protobuf_FileOptions *msg, upb_array* value) {
+ msg->uninterpreted_option = value;
+}
+struct google_protobuf_MessageOptions {
+ bool message_set_wire_format;
+ bool no_standard_descriptor_accessor;
+ bool deprecated;
+ bool map_entry;
+ upb_array* uninterpreted_option;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_MessageOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_MessageOptions__fields[5] = {
+ {1, offsetof(google_protobuf_MessageOptions, message_set_wire_format), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {2, offsetof(google_protobuf_MessageOptions, no_standard_descriptor_accessor), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {3, offsetof(google_protobuf_MessageOptions, deprecated), 2, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {7, offsetof(google_protobuf_MessageOptions, map_entry), 3, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {999, offsetof(google_protobuf_MessageOptions, uninterpreted_option), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_MessageOptions_msginit = {
+ &google_protobuf_MessageOptions_submsgs[0],
+ &google_protobuf_MessageOptions__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_MessageOptions), 5, 0, false, true
+};
+
+google_protobuf_MessageOptions *google_protobuf_MessageOptions_new(upb_env *env) {
+ google_protobuf_MessageOptions *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_MessageOptions *google_protobuf_MessageOptions_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_MessageOptions *msg = google_protobuf_MessageOptions_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_MessageOptions_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_MessageOptions_serialize(google_protobuf_MessageOptions *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_MessageOptions_msginit, env, size);
+}
+bool google_protobuf_MessageOptions_message_set_wire_format(const google_protobuf_MessageOptions *msg) {
+ return msg->message_set_wire_format;
+}
+void google_protobuf_MessageOptions_set_message_set_wire_format(google_protobuf_MessageOptions *msg, bool value) {
+ msg->message_set_wire_format = value;
+}
+bool google_protobuf_MessageOptions_no_standard_descriptor_accessor(const google_protobuf_MessageOptions *msg) {
+ return msg->no_standard_descriptor_accessor;
+}
+void google_protobuf_MessageOptions_set_no_standard_descriptor_accessor(google_protobuf_MessageOptions *msg, bool value) {
+ msg->no_standard_descriptor_accessor = value;
+}
+bool google_protobuf_MessageOptions_deprecated(const google_protobuf_MessageOptions *msg) {
+ return msg->deprecated;
+}
+void google_protobuf_MessageOptions_set_deprecated(google_protobuf_MessageOptions *msg, bool value) {
+ msg->deprecated = value;
+}
+bool google_protobuf_MessageOptions_map_entry(const google_protobuf_MessageOptions *msg) {
+ return msg->map_entry;
+}
+void google_protobuf_MessageOptions_set_map_entry(google_protobuf_MessageOptions *msg, bool value) {
+ msg->map_entry = value;
+}
+const upb_array* google_protobuf_MessageOptions_uninterpreted_option(const google_protobuf_MessageOptions *msg) {
+ return msg->uninterpreted_option;
+}
+void google_protobuf_MessageOptions_set_uninterpreted_option(google_protobuf_MessageOptions *msg, upb_array* value) {
+ msg->uninterpreted_option = value;
+}
+struct google_protobuf_FieldOptions {
+ google_protobuf_FieldOptions_CType ctype;
+ google_protobuf_FieldOptions_JSType jstype;
+ bool packed;
+ bool deprecated;
+ bool lazy;
+ bool weak;
+ upb_array* uninterpreted_option;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_FieldOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_FieldOptions__fields[7] = {
+ {1, offsetof(google_protobuf_FieldOptions, ctype), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 14, 1},
+ {2, offsetof(google_protobuf_FieldOptions, packed), 2, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {3, offsetof(google_protobuf_FieldOptions, deprecated), 3, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {5, offsetof(google_protobuf_FieldOptions, lazy), 4, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {6, offsetof(google_protobuf_FieldOptions, jstype), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 14, 1},
+ {10, offsetof(google_protobuf_FieldOptions, weak), 5, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {999, offsetof(google_protobuf_FieldOptions, uninterpreted_option), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_FieldOptions_msginit = {
+ &google_protobuf_FieldOptions_submsgs[0],
+ &google_protobuf_FieldOptions__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_FieldOptions), 7, 0, false, true
+};
+
+google_protobuf_FieldOptions *google_protobuf_FieldOptions_new(upb_env *env) {
+ google_protobuf_FieldOptions *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_FieldOptions *google_protobuf_FieldOptions_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_FieldOptions *msg = google_protobuf_FieldOptions_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_FieldOptions_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_FieldOptions_serialize(google_protobuf_FieldOptions *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_FieldOptions_msginit, env, size);
+}
+google_protobuf_FieldOptions_CType google_protobuf_FieldOptions_ctype(const google_protobuf_FieldOptions *msg) {
+ return msg->ctype;
+}
+void google_protobuf_FieldOptions_set_ctype(google_protobuf_FieldOptions *msg, google_protobuf_FieldOptions_CType value) {
+ msg->ctype = value;
+}
+bool google_protobuf_FieldOptions_packed(const google_protobuf_FieldOptions *msg) {
+ return msg->packed;
+}
+void google_protobuf_FieldOptions_set_packed(google_protobuf_FieldOptions *msg, bool value) {
+ msg->packed = value;
+}
+bool google_protobuf_FieldOptions_deprecated(const google_protobuf_FieldOptions *msg) {
+ return msg->deprecated;
+}
+void google_protobuf_FieldOptions_set_deprecated(google_protobuf_FieldOptions *msg, bool value) {
+ msg->deprecated = value;
+}
+bool google_protobuf_FieldOptions_lazy(const google_protobuf_FieldOptions *msg) {
+ return msg->lazy;
+}
+void google_protobuf_FieldOptions_set_lazy(google_protobuf_FieldOptions *msg, bool value) {
+ msg->lazy = value;
+}
+google_protobuf_FieldOptions_JSType google_protobuf_FieldOptions_jstype(const google_protobuf_FieldOptions *msg) {
+ return msg->jstype;
+}
+void google_protobuf_FieldOptions_set_jstype(google_protobuf_FieldOptions *msg, google_protobuf_FieldOptions_JSType value) {
+ msg->jstype = value;
+}
+bool google_protobuf_FieldOptions_weak(const google_protobuf_FieldOptions *msg) {
+ return msg->weak;
+}
+void google_protobuf_FieldOptions_set_weak(google_protobuf_FieldOptions *msg, bool value) {
+ msg->weak = value;
+}
+const upb_array* google_protobuf_FieldOptions_uninterpreted_option(const google_protobuf_FieldOptions *msg) {
+ return msg->uninterpreted_option;
+}
+void google_protobuf_FieldOptions_set_uninterpreted_option(google_protobuf_FieldOptions *msg, upb_array* value) {
+ msg->uninterpreted_option = value;
+}
+struct google_protobuf_OneofOptions {
+ upb_array* uninterpreted_option;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_OneofOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_OneofOptions__fields[1] = {
+ {999, offsetof(google_protobuf_OneofOptions, uninterpreted_option), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_OneofOptions_msginit = {
+ &google_protobuf_OneofOptions_submsgs[0],
+ &google_protobuf_OneofOptions__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_OneofOptions), 1, 0, false, true
+};
+
+google_protobuf_OneofOptions *google_protobuf_OneofOptions_new(upb_env *env) {
+ google_protobuf_OneofOptions *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_OneofOptions *google_protobuf_OneofOptions_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_OneofOptions *msg = google_protobuf_OneofOptions_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_OneofOptions_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_OneofOptions_serialize(google_protobuf_OneofOptions *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_OneofOptions_msginit, env, size);
+}
+const upb_array* google_protobuf_OneofOptions_uninterpreted_option(const google_protobuf_OneofOptions *msg) {
+ return msg->uninterpreted_option;
+}
+void google_protobuf_OneofOptions_set_uninterpreted_option(google_protobuf_OneofOptions *msg, upb_array* value) {
+ msg->uninterpreted_option = value;
+}
+struct google_protobuf_EnumOptions {
+ bool allow_alias;
+ bool deprecated;
+ upb_array* uninterpreted_option;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_EnumOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_EnumOptions__fields[3] = {
+ {2, offsetof(google_protobuf_EnumOptions, allow_alias), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {3, offsetof(google_protobuf_EnumOptions, deprecated), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {999, offsetof(google_protobuf_EnumOptions, uninterpreted_option), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_EnumOptions_msginit = {
+ &google_protobuf_EnumOptions_submsgs[0],
+ &google_protobuf_EnumOptions__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_EnumOptions), 3, 0, false, true
+};
+
+google_protobuf_EnumOptions *google_protobuf_EnumOptions_new(upb_env *env) {
+ google_protobuf_EnumOptions *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_EnumOptions *google_protobuf_EnumOptions_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_EnumOptions *msg = google_protobuf_EnumOptions_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_EnumOptions_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_EnumOptions_serialize(google_protobuf_EnumOptions *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_EnumOptions_msginit, env, size);
+}
+bool google_protobuf_EnumOptions_allow_alias(const google_protobuf_EnumOptions *msg) {
+ return msg->allow_alias;
+}
+void google_protobuf_EnumOptions_set_allow_alias(google_protobuf_EnumOptions *msg, bool value) {
+ msg->allow_alias = value;
+}
+bool google_protobuf_EnumOptions_deprecated(const google_protobuf_EnumOptions *msg) {
+ return msg->deprecated;
+}
+void google_protobuf_EnumOptions_set_deprecated(google_protobuf_EnumOptions *msg, bool value) {
+ msg->deprecated = value;
+}
+const upb_array* google_protobuf_EnumOptions_uninterpreted_option(const google_protobuf_EnumOptions *msg) {
+ return msg->uninterpreted_option;
+}
+void google_protobuf_EnumOptions_set_uninterpreted_option(google_protobuf_EnumOptions *msg, upb_array* value) {
+ msg->uninterpreted_option = value;
+}
+struct google_protobuf_EnumValueOptions {
+ bool deprecated;
+ upb_array* uninterpreted_option;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_EnumValueOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_EnumValueOptions__fields[2] = {
+ {1, offsetof(google_protobuf_EnumValueOptions, deprecated), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {999, offsetof(google_protobuf_EnumValueOptions, uninterpreted_option), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_EnumValueOptions_msginit = {
+ &google_protobuf_EnumValueOptions_submsgs[0],
+ &google_protobuf_EnumValueOptions__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_EnumValueOptions), 2, 0, false, true
+};
+
+google_protobuf_EnumValueOptions *google_protobuf_EnumValueOptions_new(upb_env *env) {
+ google_protobuf_EnumValueOptions *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_EnumValueOptions *google_protobuf_EnumValueOptions_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_EnumValueOptions *msg = google_protobuf_EnumValueOptions_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_EnumValueOptions_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_EnumValueOptions_serialize(google_protobuf_EnumValueOptions *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_EnumValueOptions_msginit, env, size);
+}
+bool google_protobuf_EnumValueOptions_deprecated(const google_protobuf_EnumValueOptions *msg) {
+ return msg->deprecated;
+}
+void google_protobuf_EnumValueOptions_set_deprecated(google_protobuf_EnumValueOptions *msg, bool value) {
+ msg->deprecated = value;
+}
+const upb_array* google_protobuf_EnumValueOptions_uninterpreted_option(const google_protobuf_EnumValueOptions *msg) {
+ return msg->uninterpreted_option;
+}
+void google_protobuf_EnumValueOptions_set_uninterpreted_option(google_protobuf_EnumValueOptions *msg, upb_array* value) {
+ msg->uninterpreted_option = value;
+}
+struct google_protobuf_ServiceOptions {
+ bool deprecated;
+ upb_array* uninterpreted_option;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_ServiceOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_ServiceOptions__fields[2] = {
+ {33, offsetof(google_protobuf_ServiceOptions, deprecated), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {999, offsetof(google_protobuf_ServiceOptions, uninterpreted_option), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_ServiceOptions_msginit = {
+ &google_protobuf_ServiceOptions_submsgs[0],
+ &google_protobuf_ServiceOptions__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_ServiceOptions), 2, 0, false, true
+};
+
+google_protobuf_ServiceOptions *google_protobuf_ServiceOptions_new(upb_env *env) {
+ google_protobuf_ServiceOptions *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_ServiceOptions *google_protobuf_ServiceOptions_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_ServiceOptions *msg = google_protobuf_ServiceOptions_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_ServiceOptions_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_ServiceOptions_serialize(google_protobuf_ServiceOptions *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_ServiceOptions_msginit, env, size);
+}
+bool google_protobuf_ServiceOptions_deprecated(const google_protobuf_ServiceOptions *msg) {
+ return msg->deprecated;
+}
+void google_protobuf_ServiceOptions_set_deprecated(google_protobuf_ServiceOptions *msg, bool value) {
+ msg->deprecated = value;
+}
+const upb_array* google_protobuf_ServiceOptions_uninterpreted_option(const google_protobuf_ServiceOptions *msg) {
+ return msg->uninterpreted_option;
+}
+void google_protobuf_ServiceOptions_set_uninterpreted_option(google_protobuf_ServiceOptions *msg, upb_array* value) {
+ msg->uninterpreted_option = value;
+}
+struct google_protobuf_MethodOptions {
+ google_protobuf_MethodOptions_IdempotencyLevel idempotency_level;
+ bool deprecated;
+ upb_array* uninterpreted_option;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_MethodOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_MethodOptions__fields[3] = {
+ {33, offsetof(google_protobuf_MethodOptions, deprecated), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 1},
+ {34, offsetof(google_protobuf_MethodOptions, idempotency_level), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 14, 1},
+ {999, offsetof(google_protobuf_MethodOptions, uninterpreted_option), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_MethodOptions_msginit = {
+ &google_protobuf_MethodOptions_submsgs[0],
+ &google_protobuf_MethodOptions__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_MethodOptions), 3, 0, false, true
+};
+
+google_protobuf_MethodOptions *google_protobuf_MethodOptions_new(upb_env *env) {
+ google_protobuf_MethodOptions *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_MethodOptions *google_protobuf_MethodOptions_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_MethodOptions *msg = google_protobuf_MethodOptions_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_MethodOptions_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_MethodOptions_serialize(google_protobuf_MethodOptions *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_MethodOptions_msginit, env, size);
+}
+bool google_protobuf_MethodOptions_deprecated(const google_protobuf_MethodOptions *msg) {
+ return msg->deprecated;
+}
+void google_protobuf_MethodOptions_set_deprecated(google_protobuf_MethodOptions *msg, bool value) {
+ msg->deprecated = value;
+}
+google_protobuf_MethodOptions_IdempotencyLevel google_protobuf_MethodOptions_idempotency_level(const google_protobuf_MethodOptions *msg) {
+ return msg->idempotency_level;
+}
+void google_protobuf_MethodOptions_set_idempotency_level(google_protobuf_MethodOptions *msg, google_protobuf_MethodOptions_IdempotencyLevel value) {
+ msg->idempotency_level = value;
+}
+const upb_array* google_protobuf_MethodOptions_uninterpreted_option(const google_protobuf_MethodOptions *msg) {
+ return msg->uninterpreted_option;
+}
+void google_protobuf_MethodOptions_set_uninterpreted_option(google_protobuf_MethodOptions *msg, upb_array* value) {
+ msg->uninterpreted_option = value;
+}
+struct google_protobuf_UninterpretedOption {
+ uint64_t positive_int_value;
+ int64_t negative_int_value;
+ double double_value;
+ upb_stringview identifier_value;
+ upb_stringview string_value;
+ upb_stringview aggregate_value;
+ upb_array* name;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_UninterpretedOption_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_NamePart_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_UninterpretedOption__fields[7] = {
+ {2, offsetof(google_protobuf_UninterpretedOption, name), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+ {3, offsetof(google_protobuf_UninterpretedOption, identifier_value), 3, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {4, offsetof(google_protobuf_UninterpretedOption, positive_int_value), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 4, 1},
+ {5, offsetof(google_protobuf_UninterpretedOption, negative_int_value), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 3, 1},
+ {6, offsetof(google_protobuf_UninterpretedOption, double_value), 2, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 1, 1},
+ {7, offsetof(google_protobuf_UninterpretedOption, string_value), 4, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 12, 1},
+ {8, offsetof(google_protobuf_UninterpretedOption, aggregate_value), 5, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_UninterpretedOption_msginit = {
+ &google_protobuf_UninterpretedOption_submsgs[0],
+ &google_protobuf_UninterpretedOption__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_UninterpretedOption), 7, 0, false, true
+};
+
+google_protobuf_UninterpretedOption *google_protobuf_UninterpretedOption_new(upb_env *env) {
+ google_protobuf_UninterpretedOption *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_UninterpretedOption *google_protobuf_UninterpretedOption_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_UninterpretedOption *msg = google_protobuf_UninterpretedOption_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_UninterpretedOption_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_UninterpretedOption_serialize(google_protobuf_UninterpretedOption *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_UninterpretedOption_msginit, env, size);
+}
+const upb_array* google_protobuf_UninterpretedOption_name(const google_protobuf_UninterpretedOption *msg) {
+ return msg->name;
+}
+void google_protobuf_UninterpretedOption_set_name(google_protobuf_UninterpretedOption *msg, upb_array* value) {
+ msg->name = value;
+}
+upb_stringview google_protobuf_UninterpretedOption_identifier_value(const google_protobuf_UninterpretedOption *msg) {
+ return msg->identifier_value;
+}
+void google_protobuf_UninterpretedOption_set_identifier_value(google_protobuf_UninterpretedOption *msg, upb_stringview value) {
+ msg->identifier_value = value;
+}
+uint64_t google_protobuf_UninterpretedOption_positive_int_value(const google_protobuf_UninterpretedOption *msg) {
+ return msg->positive_int_value;
+}
+void google_protobuf_UninterpretedOption_set_positive_int_value(google_protobuf_UninterpretedOption *msg, uint64_t value) {
+ msg->positive_int_value = value;
+}
+int64_t google_protobuf_UninterpretedOption_negative_int_value(const google_protobuf_UninterpretedOption *msg) {
+ return msg->negative_int_value;
+}
+void google_protobuf_UninterpretedOption_set_negative_int_value(google_protobuf_UninterpretedOption *msg, int64_t value) {
+ msg->negative_int_value = value;
+}
+double google_protobuf_UninterpretedOption_double_value(const google_protobuf_UninterpretedOption *msg) {
+ return msg->double_value;
+}
+void google_protobuf_UninterpretedOption_set_double_value(google_protobuf_UninterpretedOption *msg, double value) {
+ msg->double_value = value;
+}
+upb_stringview google_protobuf_UninterpretedOption_string_value(const google_protobuf_UninterpretedOption *msg) {
+ return msg->string_value;
+}
+void google_protobuf_UninterpretedOption_set_string_value(google_protobuf_UninterpretedOption *msg, upb_stringview value) {
+ msg->string_value = value;
+}
+upb_stringview google_protobuf_UninterpretedOption_aggregate_value(const google_protobuf_UninterpretedOption *msg) {
+ return msg->aggregate_value;
+}
+void google_protobuf_UninterpretedOption_set_aggregate_value(google_protobuf_UninterpretedOption *msg, upb_stringview value) {
+ msg->aggregate_value = value;
+}
+struct google_protobuf_UninterpretedOption_NamePart {
+ bool is_extension;
+ upb_stringview name_part;
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_UninterpretedOption_NamePart__fields[2] = {
+ {1, offsetof(google_protobuf_UninterpretedOption_NamePart, name_part), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 2},
+ {2, offsetof(google_protobuf_UninterpretedOption_NamePart, is_extension), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 8, 2},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_UninterpretedOption_NamePart_msginit = {
+ NULL,
+ &google_protobuf_UninterpretedOption_NamePart__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_UninterpretedOption_NamePart), 2, 0, false, true
+};
+
+google_protobuf_UninterpretedOption_NamePart *google_protobuf_UninterpretedOption_NamePart_new(upb_env *env) {
+ google_protobuf_UninterpretedOption_NamePart *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_UninterpretedOption_NamePart *google_protobuf_UninterpretedOption_NamePart_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_UninterpretedOption_NamePart *msg = google_protobuf_UninterpretedOption_NamePart_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_UninterpretedOption_NamePart_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_UninterpretedOption_NamePart_serialize(google_protobuf_UninterpretedOption_NamePart *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_UninterpretedOption_NamePart_msginit, env, size);
+}
+upb_stringview google_protobuf_UninterpretedOption_NamePart_name_part(const google_protobuf_UninterpretedOption_NamePart *msg) {
+ return msg->name_part;
+}
+void google_protobuf_UninterpretedOption_NamePart_set_name_part(google_protobuf_UninterpretedOption_NamePart *msg, upb_stringview value) {
+ msg->name_part = value;
+}
+bool google_protobuf_UninterpretedOption_NamePart_is_extension(const google_protobuf_UninterpretedOption_NamePart *msg) {
+ return msg->is_extension;
+}
+void google_protobuf_UninterpretedOption_NamePart_set_is_extension(google_protobuf_UninterpretedOption_NamePart *msg, bool value) {
+ msg->is_extension = value;
+}
+struct google_protobuf_SourceCodeInfo {
+ upb_array* location;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_SourceCodeInfo_submsgs[1] = {
+ &google_protobuf_SourceCodeInfo_Location_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_SourceCodeInfo__fields[1] = {
+ {1, offsetof(google_protobuf_SourceCodeInfo, location), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_SourceCodeInfo_msginit = {
+ &google_protobuf_SourceCodeInfo_submsgs[0],
+ &google_protobuf_SourceCodeInfo__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_SourceCodeInfo), 1, 0, false, true
+};
+
+google_protobuf_SourceCodeInfo *google_protobuf_SourceCodeInfo_new(upb_env *env) {
+ google_protobuf_SourceCodeInfo *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_SourceCodeInfo *google_protobuf_SourceCodeInfo_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_SourceCodeInfo *msg = google_protobuf_SourceCodeInfo_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_SourceCodeInfo_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_SourceCodeInfo_serialize(google_protobuf_SourceCodeInfo *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_SourceCodeInfo_msginit, env, size);
+}
+const upb_array* google_protobuf_SourceCodeInfo_location(const google_protobuf_SourceCodeInfo *msg) {
+ return msg->location;
+}
+void google_protobuf_SourceCodeInfo_set_location(google_protobuf_SourceCodeInfo *msg, upb_array* value) {
+ msg->location = value;
+}
+struct google_protobuf_SourceCodeInfo_Location {
+ upb_stringview leading_comments;
+ upb_stringview trailing_comments;
+ upb_array* path;
+ upb_array* span;
+ upb_array* leading_detached_comments;
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_SourceCodeInfo_Location__fields[5] = {
+ {1, offsetof(google_protobuf_SourceCodeInfo_Location, path), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 3},
+ {2, offsetof(google_protobuf_SourceCodeInfo_Location, span), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 3},
+ {3, offsetof(google_protobuf_SourceCodeInfo_Location, leading_comments), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {4, offsetof(google_protobuf_SourceCodeInfo_Location, trailing_comments), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {6, offsetof(google_protobuf_SourceCodeInfo_Location, leading_detached_comments), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 3},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_SourceCodeInfo_Location_msginit = {
+ NULL,
+ &google_protobuf_SourceCodeInfo_Location__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_SourceCodeInfo_Location), 5, 0, false, true
+};
+
+google_protobuf_SourceCodeInfo_Location *google_protobuf_SourceCodeInfo_Location_new(upb_env *env) {
+ google_protobuf_SourceCodeInfo_Location *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_SourceCodeInfo_Location *google_protobuf_SourceCodeInfo_Location_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_SourceCodeInfo_Location *msg = google_protobuf_SourceCodeInfo_Location_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_SourceCodeInfo_Location_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_SourceCodeInfo_Location_serialize(google_protobuf_SourceCodeInfo_Location *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_SourceCodeInfo_Location_msginit, env, size);
+}
+const upb_array* google_protobuf_SourceCodeInfo_Location_path(const google_protobuf_SourceCodeInfo_Location *msg) {
+ return msg->path;
+}
+void google_protobuf_SourceCodeInfo_Location_set_path(google_protobuf_SourceCodeInfo_Location *msg, upb_array* value) {
+ msg->path = value;
+}
+const upb_array* google_protobuf_SourceCodeInfo_Location_span(const google_protobuf_SourceCodeInfo_Location *msg) {
+ return msg->span;
+}
+void google_protobuf_SourceCodeInfo_Location_set_span(google_protobuf_SourceCodeInfo_Location *msg, upb_array* value) {
+ msg->span = value;
+}
+upb_stringview google_protobuf_SourceCodeInfo_Location_leading_comments(const google_protobuf_SourceCodeInfo_Location *msg) {
+ return msg->leading_comments;
+}
+void google_protobuf_SourceCodeInfo_Location_set_leading_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_stringview value) {
+ msg->leading_comments = value;
+}
+upb_stringview google_protobuf_SourceCodeInfo_Location_trailing_comments(const google_protobuf_SourceCodeInfo_Location *msg) {
+ return msg->trailing_comments;
+}
+void google_protobuf_SourceCodeInfo_Location_set_trailing_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_stringview value) {
+ msg->trailing_comments = value;
+}
+const upb_array* google_protobuf_SourceCodeInfo_Location_leading_detached_comments(const google_protobuf_SourceCodeInfo_Location *msg) {
+ return msg->leading_detached_comments;
+}
+void google_protobuf_SourceCodeInfo_Location_set_leading_detached_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_array* value) {
+ msg->leading_detached_comments = value;
+}
+struct google_protobuf_GeneratedCodeInfo {
+ upb_array* annotation;
+};
+
+static const upb_msglayout_msginit_v1 *const google_protobuf_GeneratedCodeInfo_submsgs[1] = {
+ &google_protobuf_GeneratedCodeInfo_Annotation_msginit,
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_GeneratedCodeInfo__fields[1] = {
+ {1, offsetof(google_protobuf_GeneratedCodeInfo, annotation), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, 0, 11, 3},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_GeneratedCodeInfo_msginit = {
+ &google_protobuf_GeneratedCodeInfo_submsgs[0],
+ &google_protobuf_GeneratedCodeInfo__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_GeneratedCodeInfo), 1, 0, false, true
+};
+
+google_protobuf_GeneratedCodeInfo *google_protobuf_GeneratedCodeInfo_new(upb_env *env) {
+ google_protobuf_GeneratedCodeInfo *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_GeneratedCodeInfo *google_protobuf_GeneratedCodeInfo_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_GeneratedCodeInfo *msg = google_protobuf_GeneratedCodeInfo_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_GeneratedCodeInfo_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_GeneratedCodeInfo_serialize(google_protobuf_GeneratedCodeInfo *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_GeneratedCodeInfo_msginit, env, size);
+}
+const upb_array* google_protobuf_GeneratedCodeInfo_annotation(const google_protobuf_GeneratedCodeInfo *msg) {
+ return msg->annotation;
+}
+void google_protobuf_GeneratedCodeInfo_set_annotation(google_protobuf_GeneratedCodeInfo *msg, upb_array* value) {
+ msg->annotation = value;
+}
+struct google_protobuf_GeneratedCodeInfo_Annotation {
+ int32_t begin;
+ int32_t end;
+ upb_stringview source_file;
+ upb_array* path;
+};
+
+static const upb_msglayout_fieldinit_v1 google_protobuf_GeneratedCodeInfo_Annotation__fields[4] = {
+ {1, offsetof(google_protobuf_GeneratedCodeInfo_Annotation, path), UPB_NO_HASBIT, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 3},
+ {2, offsetof(google_protobuf_GeneratedCodeInfo_Annotation, source_file), 2, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 9, 1},
+ {3, offsetof(google_protobuf_GeneratedCodeInfo_Annotation, begin), 0, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 1},
+ {4, offsetof(google_protobuf_GeneratedCodeInfo_Annotation, end), 1, UPB_NOT_IN_ONEOF, UPB_NO_SUBMSG, 5, 1},
+};
+
+const upb_msglayout_msginit_v1 google_protobuf_GeneratedCodeInfo_Annotation_msginit = {
+ NULL,
+ &google_protobuf_GeneratedCodeInfo_Annotation__fields[0],
+ NULL,
+ NULL, /* TODO. default_msg */
+ UPB_ALIGNED_SIZEOF(google_protobuf_GeneratedCodeInfo_Annotation), 4, 0, false, true
+};
+
+google_protobuf_GeneratedCodeInfo_Annotation *google_protobuf_GeneratedCodeInfo_Annotation_new(upb_env *env) {
+ google_protobuf_GeneratedCodeInfo_Annotation *msg = upb_env_malloc(env, sizeof(*msg));
+ memset(msg, 0, sizeof(*msg)); /* TODO: defaults */
+ return msg;
+}
+google_protobuf_GeneratedCodeInfo_Annotation *google_protobuf_GeneratedCodeInfo_Annotation_parsenew(upb_stringview buf, upb_env *env) {
+ google_protobuf_GeneratedCodeInfo_Annotation *msg = google_protobuf_GeneratedCodeInfo_Annotation_new(env);
+ if (upb_decode(buf, msg, &google_protobuf_GeneratedCodeInfo_Annotation_msginit, env)) {
+ return msg;
+ } else {
+ return NULL;
+ }
+}
+char *google_protobuf_GeneratedCodeInfo_Annotation_serialize(google_protobuf_GeneratedCodeInfo_Annotation *msg, upb_env *env, size_t *size) {
+ return upb_encode(msg, &google_protobuf_GeneratedCodeInfo_Annotation_msginit, env, size);
+}
+const upb_array* google_protobuf_GeneratedCodeInfo_Annotation_path(const google_protobuf_GeneratedCodeInfo_Annotation *msg) {
+ return msg->path;
+}
+void google_protobuf_GeneratedCodeInfo_Annotation_set_path(google_protobuf_GeneratedCodeInfo_Annotation *msg, upb_array* value) {
+ msg->path = value;
+}
+upb_stringview google_protobuf_GeneratedCodeInfo_Annotation_source_file(const google_protobuf_GeneratedCodeInfo_Annotation *msg) {
+ return msg->source_file;
+}
+void google_protobuf_GeneratedCodeInfo_Annotation_set_source_file(google_protobuf_GeneratedCodeInfo_Annotation *msg, upb_stringview value) {
+ msg->source_file = value;
+}
+int32_t google_protobuf_GeneratedCodeInfo_Annotation_begin(const google_protobuf_GeneratedCodeInfo_Annotation *msg) {
+ return msg->begin;
+}
+void google_protobuf_GeneratedCodeInfo_Annotation_set_begin(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t value) {
+ msg->begin = value;
+}
+int32_t google_protobuf_GeneratedCodeInfo_Annotation_end(const google_protobuf_GeneratedCodeInfo_Annotation *msg) {
+ return msg->end;
+}
+void google_protobuf_GeneratedCodeInfo_Annotation_set_end(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t value) {
+ msg->end = value;
+}
/* Maps descriptor type -> upb field type. */
-static const uint8_t upb_desctype_to_fieldtype[] = {
+const uint8_t upb_desctype_to_fieldtype[] = {
UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
UPB_TYPE_DOUBLE, /* DOUBLE */
UPB_TYPE_FLOAT, /* FLOAT */
@@ -215,7 +2114,7 @@ static upb_array *upb_getorcreatearr(upb_decstate *d,
if (!arr) {
return NULL;
}
- upb_array_init(arr, upb_desctype_to_fieldtype[field->type],
+ upb_array_init(arr, upb_desctype_to_fieldtype[field->descriptortype],
upb_arena_alloc(upb_env_arena(d->env)));
*(upb_array**)&frame->msg[field->offset] = arr;
}
@@ -268,7 +2167,8 @@ static bool upb_decode_submsg(upb_decstate *d,
const char *limit,
const upb_msglayout_fieldinit_v1 *field,
int group_number) {
- char *submsg = *(void**)&frame->msg[field->offset];
+ char *submsg_slot = upb_decode_prepareslot(d, frame, field);
+ char *submsg = *(void**)submsg_slot;
const upb_msglayout_msginit_v1 *subm;
UPB_ASSERT(field->submsg_index != UPB_NO_SUBMSG);
@@ -280,7 +2180,7 @@ static bool upb_decode_submsg(upb_decstate *d,
CHK(submsg);
submsg = upb_msg_init(
submsg, (upb_msglayout*)subm, upb_arena_alloc(upb_env_arena(d->env)));
- *(void**)&frame->msg[field->offset] = submsg;
+ *(void**)submsg_slot = submsg;
}
upb_decode_message(d, limit, group_number, submsg, subm);
@@ -298,7 +2198,7 @@ static bool upb_decode_varintfield(upb_decstate *d, upb_decframe *frame,
CHK(field_mem);
CHK(upb_decode_varint(&d->ptr, frame->limit, &val));
- switch ((upb_descriptortype_t)field->type) {
+ switch ((upb_descriptortype_t)field->descriptortype) {
case UPB_DESCRIPTOR_TYPE_INT64:
case UPB_DESCRIPTOR_TYPE_UINT64:
memcpy(field_mem, &val, sizeof(val));
@@ -343,7 +2243,7 @@ static bool upb_decode_64bitfield(upb_decstate *d, upb_decframe *frame,
CHK(field_mem);
CHK(upb_decode_64bit(&d->ptr, frame->limit, &val));
- switch ((upb_descriptortype_t)field->type) {
+ switch ((upb_descriptortype_t)field->descriptortype) {
case UPB_DESCRIPTOR_TYPE_DOUBLE:
case UPB_DESCRIPTOR_TYPE_FIXED64:
case UPB_DESCRIPTOR_TYPE_SFIXED64:
@@ -367,7 +2267,7 @@ static bool upb_decode_32bitfield(upb_decstate *d, upb_decframe *frame,
CHK(field_mem);
CHK(upb_decode_32bit(&d->ptr, frame->limit, &val));
- switch ((upb_descriptortype_t)field->type) {
+ switch ((upb_descriptortype_t)field->descriptortype) {
case UPB_DESCRIPTOR_TYPE_FLOAT:
case UPB_DESCRIPTOR_TYPE_FIXED32:
case UPB_DESCRIPTOR_TYPE_SFIXED32:
@@ -415,7 +2315,7 @@ static bool upb_decode_toarray(upb_decstate *d, upb_decframe *frame,
return true; \
}
- switch ((upb_descriptortype_t)field->type) {
+ switch ((upb_descriptortype_t)field->descriptortype) {
case UPB_DESCRIPTOR_TYPE_STRING:
case UPB_DESCRIPTOR_TYPE_BYTES: {
void *field_mem = upb_array_add(arr, 1);
@@ -445,9 +2345,31 @@ static bool upb_decode_toarray(upb_decstate *d, upb_decframe *frame,
VARINT_CASE(int32_t, upb_zzdecode_32);
case UPB_DESCRIPTOR_TYPE_SINT64:
VARINT_CASE(int64_t, upb_zzdecode_64);
- case UPB_DESCRIPTOR_TYPE_MESSAGE:
+ case UPB_DESCRIPTOR_TYPE_MESSAGE: {
+ const upb_msglayout_msginit_v1 *subm;
+ char *submsg;
+ void *field_mem;
+
CHK(val.size <= (size_t)(frame->limit - val.data));
- return upb_decode_submsg(d, frame, val.data + val.size, field, 0);
+ d->ptr -= val.size;
+
+ /* Create elemente message. */
+ UPB_ASSERT(field->submsg_index != UPB_NO_SUBMSG);
+ subm = frame->m->submsgs[field->submsg_index];
+ UPB_ASSERT(subm);
+
+ submsg = upb_env_malloc(d->env, upb_msg_sizeof((upb_msglayout *)subm));
+ CHK(submsg);
+ submsg = upb_msg_init(submsg, (upb_msglayout*)subm,
+ upb_arena_alloc(upb_env_arena(d->env)));
+
+ field_mem = upb_array_add(arr, 1);
+ CHK(field_mem);
+ *(void**)field_mem = submsg;
+
+ return upb_decode_message(
+ d, val.data + val.size, frame->group_number, submsg, subm);
+ }
case UPB_DESCRIPTOR_TYPE_GROUP:
return upb_append_unknown(d, frame, field_start);
}
@@ -465,7 +2387,7 @@ static bool upb_decode_delimitedfield(upb_decstate *d, upb_decframe *frame,
if (field->label == UPB_LABEL_REPEATED) {
return upb_decode_toarray(d, frame, field_start, field, val);
} else {
- switch ((upb_descriptortype_t)field->type) {
+ switch ((upb_descriptortype_t)field->descriptortype) {
case UPB_DESCRIPTOR_TYPE_STRING:
case UPB_DESCRIPTOR_TYPE_BYTES: {
void *field_mem = upb_decode_prepareslot(d, frame, field);
@@ -475,6 +2397,7 @@ static bool upb_decode_delimitedfield(upb_decstate *d, upb_decframe *frame,
}
case UPB_DESCRIPTOR_TYPE_MESSAGE:
CHK(val.size <= (size_t)(frame->limit - val.data));
+ d->ptr -= val.size;
CHK(upb_decode_submsg(d, frame, val.data + val.size, field, 0));
break;
default:
@@ -519,7 +2442,7 @@ static bool upb_decode_field(upb_decstate *d, upb_decframe *frame) {
case UPB_WIRE_TYPE_DELIMITED:
return upb_decode_delimitedfield(d, frame, field_start, field);
case UPB_WIRE_TYPE_START_GROUP:
- CHK(field->type == UPB_DESCRIPTOR_TYPE_GROUP);
+ CHK(field->descriptortype == UPB_DESCRIPTOR_TYPE_GROUP);
return upb_decode_submsg(d, frame, frame->limit, field, field_number);
case UPB_WIRE_TYPE_END_GROUP:
CHK(frame->group_number == field_number)
@@ -3004,7 +4927,7 @@ static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
CHK(new_buf);
/* We want previous data at the end, realloc() put it at the beginning. */
- memmove(e->limit - old_size, e->buf, old_size);
+ memmove(new_buf + new_size - old_size, e->buf, old_size);
e->ptr = new_buf + new_size - (e->limit - e->ptr);
e->limit = new_buf + new_size;
@@ -3100,7 +5023,7 @@ static bool upb_encode_array(upb_encstate *e, const char *field_mem,
return true;
}
- UPB_ASSERT(arr->type == upb_desctype_to_fieldtype2[f->type]);
+ UPB_ASSERT(arr->type == upb_desctype_to_fieldtype2[f->descriptortype]);
#define VARINT_CASE(ctype, encode) { \
ctype *start = arr->data; \
@@ -3115,7 +5038,7 @@ static bool upb_encode_array(upb_encstate *e, const char *field_mem,
break; \
do { ; } while(0)
- switch (f->type) {
+ switch (f->descriptortype) {
case UPB_DESCRIPTOR_TYPE_DOUBLE:
CHK(upb_put_fixedarray(e, arr, sizeof(double)));
break;
@@ -3134,9 +5057,10 @@ do { ; } while(0)
case UPB_DESCRIPTOR_TYPE_UINT64:
VARINT_CASE(uint64_t, *ptr);
case UPB_DESCRIPTOR_TYPE_UINT32:
+ VARINT_CASE(uint32_t, *ptr);
case UPB_DESCRIPTOR_TYPE_INT32:
case UPB_DESCRIPTOR_TYPE_ENUM:
- VARINT_CASE(uint32_t, *ptr);
+ VARINT_CASE(int32_t, (int64_t)*ptr);
case UPB_DESCRIPTOR_TYPE_BOOL:
VARINT_CASE(bool, *ptr);
case UPB_DESCRIPTOR_TYPE_SINT32:
@@ -3205,7 +5129,7 @@ static bool upb_encode_scalarfield(upb_encstate *e, const char *field_mem,
upb_put_tag(e, f->number, wire_type); \
} while(0)
- switch (f->type) {
+ switch (f->descriptortype) {
case UPB_DESCRIPTOR_TYPE_DOUBLE:
CASE(double, double, UPB_WIRE_TYPE_64BIT, val);
case UPB_DESCRIPTOR_TYPE_FLOAT:
@@ -3214,9 +5138,10 @@ static bool upb_encode_scalarfield(upb_encstate *e, const char *field_mem,
case UPB_DESCRIPTOR_TYPE_UINT64:
CASE(uint64_t, varint, UPB_WIRE_TYPE_VARINT, val);
case UPB_DESCRIPTOR_TYPE_UINT32:
+ CASE(uint32_t, varint, UPB_WIRE_TYPE_VARINT, val);
case UPB_DESCRIPTOR_TYPE_INT32:
case UPB_DESCRIPTOR_TYPE_ENUM:
- CASE(uint32_t, varint, UPB_WIRE_TYPE_VARINT, val);
+ CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, (int64_t)val);
case UPB_DESCRIPTOR_TYPE_SFIXED64:
case UPB_DESCRIPTOR_TYPE_FIXED64:
CASE(uint64_t, fixed64, UPB_WIRE_TYPE_64BIT, val);
@@ -3283,7 +5208,7 @@ bool upb_encode_message(upb_encstate* e, const char *msg,
const upb_msglayout_msginit_v1 *m,
size_t *size) {
int i;
- char *buf_end = e->ptr;
+ size_t pre_len = e->limit - e->ptr;
if (msg == NULL) {
return true;
@@ -3296,12 +5221,18 @@ bool upb_encode_message(upb_encstate* e, const char *msg,
CHK(upb_encode_array(e, msg + f->offset, m, f));
} else {
if (upb_encode_hasscalarfield(msg, m, f)) {
- CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, !m->is_proto2));
+ if (f->oneof_index == UPB_NOT_IN_ONEOF) {
+ CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, !m->is_proto2));
+ } else {
+ const upb_msglayout_oneofinit_v1 *o = &m->oneofs[f->oneof_index];
+ CHK(upb_encode_scalarfield(e, msg + o->data_offset,
+ m, f, !m->is_proto2));
+ }
}
}
}
- *size = buf_end - e->ptr;
+ *size = (e->limit - e->ptr) - pre_len;
return true;
}
@@ -4095,9 +6026,9 @@ static size_t upb_msgval_sizeof(upb_fieldtype_t type) {
return 4;
case UPB_TYPE_BOOL:
return 1;
- case UPB_TYPE_BYTES:
case UPB_TYPE_MESSAGE:
return sizeof(void*);
+ case UPB_TYPE_BYTES:
case UPB_TYPE_STRING:
return sizeof(upb_stringview);
}
@@ -4108,7 +6039,7 @@ static uint8_t upb_msg_fieldsize(const upb_msglayout_fieldinit_v1 *field) {
if (field->label == UPB_LABEL_REPEATED) {
return sizeof(void*);
} else {
- return upb_msgval_sizeof(field->type);
+ return upb_msgval_sizeof(upb_desctype_to_fieldtype[field->descriptortype]);
}
}
@@ -4252,10 +6183,11 @@ static bool upb_msglayout_initdefault(upb_msglayout *l, const upb_msgdef *m) {
return true;
}
-static upb_msglayout *upb_msglayout_new(const upb_msgdef *m) {
+static bool upb_msglayout_init(const upb_msgdef *m,
+ upb_msglayout *l,
+ upb_msgfactory *factory) {
upb_msg_field_iter it;
upb_msg_oneof_iter oit;
- upb_msglayout *l;
size_t hasbit;
size_t submsg_count = 0;
const upb_msglayout_msginit_v1 **submsgs;
@@ -4271,9 +6203,6 @@ static upb_msglayout *upb_msglayout_new(const upb_msgdef *m) {
}
}
- l = upb_gmalloc(sizeof(*l));
- if (!l) return NULL;
-
memset(l, 0, sizeof(*l));
fields = upb_gmalloc(upb_msgdef_numfields(m) * sizeof(*fields));
@@ -4284,11 +6213,10 @@ static upb_msglayout *upb_msglayout_new(const upb_msgdef *m) {
(!submsgs && submsg_count) ||
(!oneofs && upb_msgdef_numoneofs(m))) {
/* OOM. */
- upb_gfree(l);
upb_gfree(fields);
upb_gfree(submsgs);
upb_gfree(oneofs);
- return NULL;
+ return false;
}
l->data.field_count = upb_msgdef_numfields(m);
@@ -4308,6 +6236,7 @@ static upb_msglayout *upb_msglayout_new(const upb_msgdef *m) {
*/
/* Allocate hasbits and set basic field attributes. */
+ submsg_count = 0;
for (upb_msg_field_begin(&it, m), hasbit = 0;
!upb_msg_field_done(&it);
upb_msg_field_next(&it)) {
@@ -4315,7 +6244,7 @@ static upb_msglayout *upb_msglayout_new(const upb_msgdef *m) {
upb_msglayout_fieldinit_v1 *field = &fields[upb_fielddef_index(f)];
field->number = upb_fielddef_number(f);
- field->type = upb_fielddef_type(f);
+ field->descriptortype = upb_fielddef_descriptortype(f);
field->label = upb_fielddef_label(f);
if (upb_fielddef_containingoneof(f)) {
@@ -4324,8 +6253,19 @@ static upb_msglayout *upb_msglayout_new(const upb_msgdef *m) {
field->oneof_index = UPB_NOT_IN_ONEOF;
}
+ if (upb_fielddef_issubmsg(f)) {
+ const upb_msglayout *sub_layout =
+ upb_msgfactory_getlayout(factory, upb_fielddef_msgsubdef(f));
+ field->submsg_index = submsg_count++;
+ submsgs[field->submsg_index] = &sub_layout->data;
+ } else {
+ field->submsg_index = UPB_NO_SUBMSG;
+ }
+
if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
field->hasbit = hasbit++;
+ } else {
+ field->hasbit = UPB_NO_HASBIT;
}
}
@@ -4375,12 +6315,7 @@ static upb_msglayout *upb_msglayout_new(const upb_msgdef *m) {
* alignment. TODO: track overall alignment for real? */
l->data.size = align_up(l->data.size, 8);
- if (upb_msglayout_initdefault(l, m)) {
- return l;
- } else {
- upb_msglayout_free(l);
- return NULL;
- }
+ return upb_msglayout_initdefault(l, m);
}
@@ -4435,10 +6370,14 @@ const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
UPB_ASSERT(upb_value_getptr(v));
return upb_value_getptr(v);
} else {
+ /* In case of circular dependency, layout has to be inserted first. */
+ upb_msglayout *l = upb_gmalloc(sizeof(*l));
upb_msgfactory *mutable_f = (void*)f;
- upb_msglayout *l = upb_msglayout_new(m);
upb_inttable_insertptr(&mutable_f->layouts, m, upb_value_ptr(l));
UPB_ASSERT(l);
+ if (!upb_msglayout_init(m, l, f)) {
+ upb_msglayout_free(l);
+ }
return l;
}
}
diff --git a/php/ext/google/protobuf/upb.h b/php/ext/google/protobuf/upb.h
index 10371e8b..a263db30 100644
--- a/php/ext/google/protobuf/upb.h
+++ b/php/ext/google/protobuf/upb.h
@@ -1,4 +1,111 @@
// Amalgamated source file
+
+// php.h intentionally defined NDEBUG. We have to define this macro in order to
+// be used together with php.h
+#ifndef NDEBUG
+#define NDEBUG
+#endif
+
+/*
+** upb_decode: parsing into a upb_msg using a upb_msglayout.
+*/
+
+#ifndef UPB_DECODE_H_
+#define UPB_DECODE_H_
+
+/*
+** upb::Message is a representation for protobuf messages.
+**
+** However it differs from other common representations like
+** google::protobuf::Message in one key way: it does not prescribe any
+** ownership between messages and submessages, and it relies on the
+** client to delete each message/submessage/array/map at the appropriate
+** time.
+**
+** A client can access a upb::Message without knowing anything about
+** ownership semantics, but to create or mutate a message a user needs
+** to implement the memory management themselves.
+**
+** Currently all messages, arrays, and maps store a upb_alloc* internally.
+** Mutating operations use this when they require dynamically-allocated
+** memory. We could potentially eliminate this size overhead later by
+** letting the user flip a bit on the factory that prevents this from
+** being stored. The user would then need to use separate functions where
+** the upb_alloc* is passed explicitly. However for handlers to populate
+** such structures, they would need a place to store this upb_alloc* during
+** parsing; upb_handlers don't currently have a good way to accommodate this.
+**
+** TODO: UTF-8 checking?
+**/
+
+#ifndef UPB_MSG_H_
+#define UPB_MSG_H_
+
+/*
+** Defs are upb's internal representation of the constructs that can appear
+** in a .proto file:
+**
+** - upb::MessageDef (upb_msgdef): describes a "message" construct.
+** - upb::FieldDef (upb_fielddef): describes a message field.
+** - upb::FileDef (upb_filedef): describes a .proto file and its defs.
+** - upb::EnumDef (upb_enumdef): describes an enum.
+** - upb::OneofDef (upb_oneofdef): describes a oneof.
+** - upb::Def (upb_def): base class of all the others.
+**
+** TODO: definitions of services.
+**
+** Like upb_refcounted objects, defs are mutable only until frozen, and are
+** only thread-safe once frozen.
+**
+** This is a mixed C/C++ interface that offers a full API to both languages.
+** See the top-level README for more information.
+*/
+
+#ifndef UPB_DEF_H_
+#define UPB_DEF_H_
+
+/*
+** upb::RefCounted (upb_refcounted)
+**
+** A refcounting scheme that supports circular refs. It accomplishes this by
+** partitioning the set of objects into groups such that no cycle spans groups;
+** we can then reference-count the group as a whole and ignore refs within the
+** group. When objects are mutable, these groups are computed very
+** conservatively; we group any objects that have ever had a link between them.
+** When objects are frozen, we compute strongly-connected components which
+** allows us to be precise and only group objects that are actually cyclic.
+**
+** This is a mixed C/C++ interface that offers a full API to both languages.
+** See the top-level README for more information.
+*/
+
+#ifndef UPB_REFCOUNTED_H_
+#define UPB_REFCOUNTED_H_
+
+/*
+** upb_table
+**
+** This header is INTERNAL-ONLY! Its interfaces are not public or stable!
+** This file defines very fast int->upb_value (inttable) and string->upb_value
+** (strtable) hash tables.
+**
+** The table uses chained scatter with Brent's variation (inspired by the Lua
+** implementation of hash tables). The hash function for strings is Austin
+** Appleby's "MurmurHash."
+**
+** The inttable uses uintptr_t as its key, which guarantees it can be used to
+** store pointers or integers of at least 32 bits (upb isn't really useful on
+** systems where sizeof(void*) < 4).
+**
+** The table must be homogenous (all values of the same type). In debug
+** mode, we check this on insert and lookup.
+*/
+
+#ifndef UPB_TABLE_H_
+#define UPB_TABLE_H_
+
+#include <stdint.h>
+#include <string.h>
/*
** This file contains shared definitions that are widely used across upb.
**
@@ -9,12 +116,6 @@
#ifndef UPB_H_
#define UPB_H_
-// php.h intentionally defined NDEBUG. We have to define this macro in order to
-// be used together with php.h
-#ifndef NDEBUG
-#define NDEBUG
-#endif
-
#include <assert.h>
#include <stdarg.h>
#include <stdbool.h>
@@ -743,106 +844,6 @@ template <int N> class upb::InlinedEnvironment : public upb::Environment {
#endif /* UPB_H_ */
-/*
-** upb_decode: parsing into a upb_msg using a upb_msglayout.
-*/
-
-#ifndef UPB_DECODE_H_
-#define UPB_DECODE_H_
-
-/*
-** upb::Message is a representation for protobuf messages.
-**
-** However it differs from other common representations like
-** google::protobuf::Message in one key way: it does not prescribe any
-** ownership between messages and submessages, and it relies on the
-** client to delete each message/submessage/array/map at the appropriate
-** time.
-**
-** A client can access a upb::Message without knowing anything about
-** ownership semantics, but to create or mutate a message a user needs
-** to implement the memory management themselves.
-**
-** Currently all messages, arrays, and maps store a upb_alloc* internally.
-** Mutating operations use this when they require dynamically-allocated
-** memory. We could potentially eliminate this size overhead later by
-** letting the user flip a bit on the factory that prevents this from
-** being stored. The user would then need to use separate functions where
-** the upb_alloc* is passed explicitly. However for handlers to populate
-** such structures, they would need a place to store this upb_alloc* during
-** parsing; upb_handlers don't currently have a good way to accommodate this.
-**
-** TODO: UTF-8 checking?
-**/
-
-#ifndef UPB_MSG_H_
-#define UPB_MSG_H_
-
-/*
-** Defs are upb's internal representation of the constructs that can appear
-** in a .proto file:
-**
-** - upb::MessageDef (upb_msgdef): describes a "message" construct.
-** - upb::FieldDef (upb_fielddef): describes a message field.
-** - upb::FileDef (upb_filedef): describes a .proto file and its defs.
-** - upb::EnumDef (upb_enumdef): describes an enum.
-** - upb::OneofDef (upb_oneofdef): describes a oneof.
-** - upb::Def (upb_def): base class of all the others.
-**
-** TODO: definitions of services.
-**
-** Like upb_refcounted objects, defs are mutable only until frozen, and are
-** only thread-safe once frozen.
-**
-** This is a mixed C/C++ interface that offers a full API to both languages.
-** See the top-level README for more information.
-*/
-
-#ifndef UPB_DEF_H_
-#define UPB_DEF_H_
-
-/*
-** upb::RefCounted (upb_refcounted)
-**
-** A refcounting scheme that supports circular refs. It accomplishes this by
-** partitioning the set of objects into groups such that no cycle spans groups;
-** we can then reference-count the group as a whole and ignore refs within the
-** group. When objects are mutable, these groups are computed very
-** conservatively; we group any objects that have ever had a link between them.
-** When objects are frozen, we compute strongly-connected components which
-** allows us to be precise and only group objects that are actually cyclic.
-**
-** This is a mixed C/C++ interface that offers a full API to both languages.
-** See the top-level README for more information.
-*/
-
-#ifndef UPB_REFCOUNTED_H_
-#define UPB_REFCOUNTED_H_
-
-/*
-** upb_table
-**
-** This header is INTERNAL-ONLY! Its interfaces are not public or stable!
-** This file defines very fast int->upb_value (inttable) and string->upb_value
-** (strtable) hash tables.
-**
-** The table uses chained scatter with Brent's variation (inspired by the Lua
-** implementation of hash tables). The hash function for strings is Austin
-** Appleby's "MurmurHash."
-**
-** The inttable uses uintptr_t as its key, which guarantees it can be used to
-** store pointers or integers of at least 32 bits (upb isn't really useful on
-** systems where sizeof(void*) < 4).
-**
-** The table must be homogenous (all values of the same type). In debug
-** mode, we check this on insert and lookup.
-*/
-
-#ifndef UPB_TABLE_H_
-#define UPB_TABLE_H_
-
-#include <stdint.h>
-#include <string.h>
#ifdef __cplusplus
extern "C" {
@@ -2001,6 +2002,9 @@ typedef enum {
UPB_SYNTAX_PROTO3 = 3
} upb_syntax_t;
+/* Maps descriptor type -> upb field type. */
+extern const uint8_t upb_desctype_to_fieldtype[];
+
/* Maximum field number allowed for FieldDefs. This is an inherent limit of the
* protobuf wire format. */
#define UPB_MAX_FIELDNUMBER ((1 << 29) - 1)
@@ -6747,7 +6751,7 @@ typedef struct {
uint16_t hasbit; /* UPB_NO_HASBIT if no hasbit. */
uint16_t oneof_index; /* UPB_NOT_IN_ONEOF if not in a oneof. */
uint16_t submsg_index; /* UPB_NO_SUBMSG if no submsg. */
- uint8_t type;
+ uint8_t descriptortype;
uint8_t label;
} upb_msglayout_fieldinit_v1;
@@ -6793,6 +6797,714 @@ UPB_END_EXTERN_C
#endif /* UPB_DECODE_H_ */
/*
+** upb_encode: parsing into a upb_msg using a upb_msglayout.
+*/
+
+#ifndef UPB_ENCODE_H_
+#define UPB_ENCODE_H_
+
+
+UPB_BEGIN_EXTERN_C
+
+char *upb_encode(const void *msg, const upb_msglayout_msginit_v1 *l,
+ upb_env *env, size_t *size);
+
+UPB_END_EXTERN_C
+
+#endif /* UPB_ENCODE_H_ */
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/descriptor.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_
+#define GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_
+
+
+UPB_BEGIN_EXTERN_C
+
+struct google_protobuf_FileDescriptorSet;
+typedef struct google_protobuf_FileDescriptorSet google_protobuf_FileDescriptorSet;
+struct google_protobuf_FileDescriptorProto;
+typedef struct google_protobuf_FileDescriptorProto google_protobuf_FileDescriptorProto;
+struct google_protobuf_DescriptorProto;
+typedef struct google_protobuf_DescriptorProto google_protobuf_DescriptorProto;
+struct google_protobuf_DescriptorProto_ExtensionRange;
+typedef struct google_protobuf_DescriptorProto_ExtensionRange google_protobuf_DescriptorProto_ExtensionRange;
+struct google_protobuf_DescriptorProto_ReservedRange;
+typedef struct google_protobuf_DescriptorProto_ReservedRange google_protobuf_DescriptorProto_ReservedRange;
+struct google_protobuf_ExtensionRangeOptions;
+typedef struct google_protobuf_ExtensionRangeOptions google_protobuf_ExtensionRangeOptions;
+struct google_protobuf_FieldDescriptorProto;
+typedef struct google_protobuf_FieldDescriptorProto google_protobuf_FieldDescriptorProto;
+struct google_protobuf_OneofDescriptorProto;
+typedef struct google_protobuf_OneofDescriptorProto google_protobuf_OneofDescriptorProto;
+struct google_protobuf_EnumDescriptorProto;
+typedef struct google_protobuf_EnumDescriptorProto google_protobuf_EnumDescriptorProto;
+struct google_protobuf_EnumDescriptorProto_EnumReservedRange;
+typedef struct google_protobuf_EnumDescriptorProto_EnumReservedRange google_protobuf_EnumDescriptorProto_EnumReservedRange;
+struct google_protobuf_EnumValueDescriptorProto;
+typedef struct google_protobuf_EnumValueDescriptorProto google_protobuf_EnumValueDescriptorProto;
+struct google_protobuf_ServiceDescriptorProto;
+typedef struct google_protobuf_ServiceDescriptorProto google_protobuf_ServiceDescriptorProto;
+struct google_protobuf_MethodDescriptorProto;
+typedef struct google_protobuf_MethodDescriptorProto google_protobuf_MethodDescriptorProto;
+struct google_protobuf_FileOptions;
+typedef struct google_protobuf_FileOptions google_protobuf_FileOptions;
+struct google_protobuf_MessageOptions;
+typedef struct google_protobuf_MessageOptions google_protobuf_MessageOptions;
+struct google_protobuf_FieldOptions;
+typedef struct google_protobuf_FieldOptions google_protobuf_FieldOptions;
+struct google_protobuf_OneofOptions;
+typedef struct google_protobuf_OneofOptions google_protobuf_OneofOptions;
+struct google_protobuf_EnumOptions;
+typedef struct google_protobuf_EnumOptions google_protobuf_EnumOptions;
+struct google_protobuf_EnumValueOptions;
+typedef struct google_protobuf_EnumValueOptions google_protobuf_EnumValueOptions;
+struct google_protobuf_ServiceOptions;
+typedef struct google_protobuf_ServiceOptions google_protobuf_ServiceOptions;
+struct google_protobuf_MethodOptions;
+typedef struct google_protobuf_MethodOptions google_protobuf_MethodOptions;
+struct google_protobuf_UninterpretedOption;
+typedef struct google_protobuf_UninterpretedOption google_protobuf_UninterpretedOption;
+struct google_protobuf_UninterpretedOption_NamePart;
+typedef struct google_protobuf_UninterpretedOption_NamePart google_protobuf_UninterpretedOption_NamePart;
+struct google_protobuf_SourceCodeInfo;
+typedef struct google_protobuf_SourceCodeInfo google_protobuf_SourceCodeInfo;
+struct google_protobuf_SourceCodeInfo_Location;
+typedef struct google_protobuf_SourceCodeInfo_Location google_protobuf_SourceCodeInfo_Location;
+struct google_protobuf_GeneratedCodeInfo;
+typedef struct google_protobuf_GeneratedCodeInfo google_protobuf_GeneratedCodeInfo;
+struct google_protobuf_GeneratedCodeInfo_Annotation;
+typedef struct google_protobuf_GeneratedCodeInfo_Annotation google_protobuf_GeneratedCodeInfo_Annotation;
+/* Enums */
+
+typedef enum {
+ google_protobuf_FieldDescriptorProto_LABEL_OPTIONAL = 1,
+ google_protobuf_FieldDescriptorProto_LABEL_REQUIRED = 2,
+ google_protobuf_FieldDescriptorProto_LABEL_REPEATED = 3
+} google_protobuf_FieldDescriptorProto_Label;
+
+typedef enum {
+ google_protobuf_FieldDescriptorProto_TYPE_DOUBLE = 1,
+ google_protobuf_FieldDescriptorProto_TYPE_FLOAT = 2,
+ google_protobuf_FieldDescriptorProto_TYPE_INT64 = 3,
+ google_protobuf_FieldDescriptorProto_TYPE_UINT64 = 4,
+ google_protobuf_FieldDescriptorProto_TYPE_INT32 = 5,
+ google_protobuf_FieldDescriptorProto_TYPE_FIXED64 = 6,
+ google_protobuf_FieldDescriptorProto_TYPE_FIXED32 = 7,
+ google_protobuf_FieldDescriptorProto_TYPE_BOOL = 8,
+ google_protobuf_FieldDescriptorProto_TYPE_STRING = 9,
+ google_protobuf_FieldDescriptorProto_TYPE_GROUP = 10,
+ google_protobuf_FieldDescriptorProto_TYPE_MESSAGE = 11,
+ google_protobuf_FieldDescriptorProto_TYPE_BYTES = 12,
+ google_protobuf_FieldDescriptorProto_TYPE_UINT32 = 13,
+ google_protobuf_FieldDescriptorProto_TYPE_ENUM = 14,
+ google_protobuf_FieldDescriptorProto_TYPE_SFIXED32 = 15,
+ google_protobuf_FieldDescriptorProto_TYPE_SFIXED64 = 16,
+ google_protobuf_FieldDescriptorProto_TYPE_SINT32 = 17,
+ google_protobuf_FieldDescriptorProto_TYPE_SINT64 = 18
+} google_protobuf_FieldDescriptorProto_Type;
+
+typedef enum {
+ google_protobuf_FieldOptions_STRING = 0,
+ google_protobuf_FieldOptions_CORD = 1,
+ google_protobuf_FieldOptions_STRING_PIECE = 2
+} google_protobuf_FieldOptions_CType;
+
+typedef enum {
+ google_protobuf_FieldOptions_JS_NORMAL = 0,
+ google_protobuf_FieldOptions_JS_STRING = 1,
+ google_protobuf_FieldOptions_JS_NUMBER = 2
+} google_protobuf_FieldOptions_JSType;
+
+typedef enum {
+ google_protobuf_FileOptions_SPEED = 1,
+ google_protobuf_FileOptions_CODE_SIZE = 2,
+ google_protobuf_FileOptions_LITE_RUNTIME = 3
+} google_protobuf_FileOptions_OptimizeMode;
+
+typedef enum {
+ google_protobuf_MethodOptions_IDEMPOTENCY_UNKNOWN = 0,
+ google_protobuf_MethodOptions_NO_SIDE_EFFECTS = 1,
+ google_protobuf_MethodOptions_IDEMPOTENT = 2
+} google_protobuf_MethodOptions_IdempotencyLevel;
+
+/* google_protobuf_FileDescriptorSet */
+extern const upb_msglayout_msginit_v1 google_protobuf_FileDescriptorSet_msginit;
+google_protobuf_FileDescriptorSet *google_protobuf_FileDescriptorSet_new(upb_env *env);
+google_protobuf_FileDescriptorSet *google_protobuf_FileDescriptorSet_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_FileDescriptorSet_serialize(google_protobuf_FileDescriptorSet *msg, upb_env *env, size_t *len);
+void google_protobuf_FileDescriptorSet_free(google_protobuf_FileDescriptorSet *msg, upb_env *env);
+
+/* getters. */
+const upb_array* google_protobuf_FileDescriptorSet_file(const google_protobuf_FileDescriptorSet *msg);
+
+/* setters. */
+void google_protobuf_FileDescriptorSet_set_file(google_protobuf_FileDescriptorSet *msg, upb_array* value);
+
+
+/* google_protobuf_FileDescriptorProto */
+extern const upb_msglayout_msginit_v1 google_protobuf_FileDescriptorProto_msginit;
+google_protobuf_FileDescriptorProto *google_protobuf_FileDescriptorProto_new(upb_env *env);
+google_protobuf_FileDescriptorProto *google_protobuf_FileDescriptorProto_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_FileDescriptorProto_serialize(google_protobuf_FileDescriptorProto *msg, upb_env *env, size_t *len);
+void google_protobuf_FileDescriptorProto_free(google_protobuf_FileDescriptorProto *msg, upb_env *env);
+
+/* getters. */
+upb_stringview google_protobuf_FileDescriptorProto_name(const google_protobuf_FileDescriptorProto *msg);
+upb_stringview google_protobuf_FileDescriptorProto_package(const google_protobuf_FileDescriptorProto *msg);
+const upb_array* google_protobuf_FileDescriptorProto_dependency(const google_protobuf_FileDescriptorProto *msg);
+const upb_array* google_protobuf_FileDescriptorProto_message_type(const google_protobuf_FileDescriptorProto *msg);
+const upb_array* google_protobuf_FileDescriptorProto_enum_type(const google_protobuf_FileDescriptorProto *msg);
+const upb_array* google_protobuf_FileDescriptorProto_service(const google_protobuf_FileDescriptorProto *msg);
+const upb_array* google_protobuf_FileDescriptorProto_extension(const google_protobuf_FileDescriptorProto *msg);
+const google_protobuf_FileOptions* google_protobuf_FileDescriptorProto_options(const google_protobuf_FileDescriptorProto *msg);
+const google_protobuf_SourceCodeInfo* google_protobuf_FileDescriptorProto_source_code_info(const google_protobuf_FileDescriptorProto *msg);
+const upb_array* google_protobuf_FileDescriptorProto_public_dependency(const google_protobuf_FileDescriptorProto *msg);
+const upb_array* google_protobuf_FileDescriptorProto_weak_dependency(const google_protobuf_FileDescriptorProto *msg);
+upb_stringview google_protobuf_FileDescriptorProto_syntax(const google_protobuf_FileDescriptorProto *msg);
+
+/* setters. */
+void google_protobuf_FileDescriptorProto_set_name(google_protobuf_FileDescriptorProto *msg, upb_stringview value);
+void google_protobuf_FileDescriptorProto_set_package(google_protobuf_FileDescriptorProto *msg, upb_stringview value);
+void google_protobuf_FileDescriptorProto_set_dependency(google_protobuf_FileDescriptorProto *msg, upb_array* value);
+void google_protobuf_FileDescriptorProto_set_message_type(google_protobuf_FileDescriptorProto *msg, upb_array* value);
+void google_protobuf_FileDescriptorProto_set_enum_type(google_protobuf_FileDescriptorProto *msg, upb_array* value);
+void google_protobuf_FileDescriptorProto_set_service(google_protobuf_FileDescriptorProto *msg, upb_array* value);
+void google_protobuf_FileDescriptorProto_set_extension(google_protobuf_FileDescriptorProto *msg, upb_array* value);
+void google_protobuf_FileDescriptorProto_set_options(google_protobuf_FileDescriptorProto *msg, google_protobuf_FileOptions* value);
+void google_protobuf_FileDescriptorProto_set_source_code_info(google_protobuf_FileDescriptorProto *msg, google_protobuf_SourceCodeInfo* value);
+void google_protobuf_FileDescriptorProto_set_public_dependency(google_protobuf_FileDescriptorProto *msg, upb_array* value);
+void google_protobuf_FileDescriptorProto_set_weak_dependency(google_protobuf_FileDescriptorProto *msg, upb_array* value);
+void google_protobuf_FileDescriptorProto_set_syntax(google_protobuf_FileDescriptorProto *msg, upb_stringview value);
+
+
+/* google_protobuf_DescriptorProto */
+extern const upb_msglayout_msginit_v1 google_protobuf_DescriptorProto_msginit;
+google_protobuf_DescriptorProto *google_protobuf_DescriptorProto_new(upb_env *env);
+google_protobuf_DescriptorProto *google_protobuf_DescriptorProto_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_DescriptorProto_serialize(google_protobuf_DescriptorProto *msg, upb_env *env, size_t *len);
+void google_protobuf_DescriptorProto_free(google_protobuf_DescriptorProto *msg, upb_env *env);
+
+/* getters. */
+upb_stringview google_protobuf_DescriptorProto_name(const google_protobuf_DescriptorProto *msg);
+const upb_array* google_protobuf_DescriptorProto_field(const google_protobuf_DescriptorProto *msg);
+const upb_array* google_protobuf_DescriptorProto_nested_type(const google_protobuf_DescriptorProto *msg);
+const upb_array* google_protobuf_DescriptorProto_enum_type(const google_protobuf_DescriptorProto *msg);
+const upb_array* google_protobuf_DescriptorProto_extension_range(const google_protobuf_DescriptorProto *msg);
+const upb_array* google_protobuf_DescriptorProto_extension(const google_protobuf_DescriptorProto *msg);
+const google_protobuf_MessageOptions* google_protobuf_DescriptorProto_options(const google_protobuf_DescriptorProto *msg);
+const upb_array* google_protobuf_DescriptorProto_oneof_decl(const google_protobuf_DescriptorProto *msg);
+const upb_array* google_protobuf_DescriptorProto_reserved_range(const google_protobuf_DescriptorProto *msg);
+const upb_array* google_protobuf_DescriptorProto_reserved_name(const google_protobuf_DescriptorProto *msg);
+
+/* setters. */
+void google_protobuf_DescriptorProto_set_name(google_protobuf_DescriptorProto *msg, upb_stringview value);
+void google_protobuf_DescriptorProto_set_field(google_protobuf_DescriptorProto *msg, upb_array* value);
+void google_protobuf_DescriptorProto_set_nested_type(google_protobuf_DescriptorProto *msg, upb_array* value);
+void google_protobuf_DescriptorProto_set_enum_type(google_protobuf_DescriptorProto *msg, upb_array* value);
+void google_protobuf_DescriptorProto_set_extension_range(google_protobuf_DescriptorProto *msg, upb_array* value);
+void google_protobuf_DescriptorProto_set_extension(google_protobuf_DescriptorProto *msg, upb_array* value);
+void google_protobuf_DescriptorProto_set_options(google_protobuf_DescriptorProto *msg, google_protobuf_MessageOptions* value);
+void google_protobuf_DescriptorProto_set_oneof_decl(google_protobuf_DescriptorProto *msg, upb_array* value);
+void google_protobuf_DescriptorProto_set_reserved_range(google_protobuf_DescriptorProto *msg, upb_array* value);
+void google_protobuf_DescriptorProto_set_reserved_name(google_protobuf_DescriptorProto *msg, upb_array* value);
+
+
+/* google_protobuf_DescriptorProto_ExtensionRange */
+extern const upb_msglayout_msginit_v1 google_protobuf_DescriptorProto_ExtensionRange_msginit;
+google_protobuf_DescriptorProto_ExtensionRange *google_protobuf_DescriptorProto_ExtensionRange_new(upb_env *env);
+google_protobuf_DescriptorProto_ExtensionRange *google_protobuf_DescriptorProto_ExtensionRange_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_DescriptorProto_ExtensionRange_serialize(google_protobuf_DescriptorProto_ExtensionRange *msg, upb_env *env, size_t *len);
+void google_protobuf_DescriptorProto_ExtensionRange_free(google_protobuf_DescriptorProto_ExtensionRange *msg, upb_env *env);
+
+/* getters. */
+int32_t google_protobuf_DescriptorProto_ExtensionRange_start(const google_protobuf_DescriptorProto_ExtensionRange *msg);
+int32_t google_protobuf_DescriptorProto_ExtensionRange_end(const google_protobuf_DescriptorProto_ExtensionRange *msg);
+const google_protobuf_ExtensionRangeOptions* google_protobuf_DescriptorProto_ExtensionRange_options(const google_protobuf_DescriptorProto_ExtensionRange *msg);
+
+/* setters. */
+void google_protobuf_DescriptorProto_ExtensionRange_set_start(google_protobuf_DescriptorProto_ExtensionRange *msg, int32_t value);
+void google_protobuf_DescriptorProto_ExtensionRange_set_end(google_protobuf_DescriptorProto_ExtensionRange *msg, int32_t value);
+void google_protobuf_DescriptorProto_ExtensionRange_set_options(google_protobuf_DescriptorProto_ExtensionRange *msg, google_protobuf_ExtensionRangeOptions* value);
+
+
+/* google_protobuf_DescriptorProto_ReservedRange */
+extern const upb_msglayout_msginit_v1 google_protobuf_DescriptorProto_ReservedRange_msginit;
+google_protobuf_DescriptorProto_ReservedRange *google_protobuf_DescriptorProto_ReservedRange_new(upb_env *env);
+google_protobuf_DescriptorProto_ReservedRange *google_protobuf_DescriptorProto_ReservedRange_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_DescriptorProto_ReservedRange_serialize(google_protobuf_DescriptorProto_ReservedRange *msg, upb_env *env, size_t *len);
+void google_protobuf_DescriptorProto_ReservedRange_free(google_protobuf_DescriptorProto_ReservedRange *msg, upb_env *env);
+
+/* getters. */
+int32_t google_protobuf_DescriptorProto_ReservedRange_start(const google_protobuf_DescriptorProto_ReservedRange *msg);
+int32_t google_protobuf_DescriptorProto_ReservedRange_end(const google_protobuf_DescriptorProto_ReservedRange *msg);
+
+/* setters. */
+void google_protobuf_DescriptorProto_ReservedRange_set_start(google_protobuf_DescriptorProto_ReservedRange *msg, int32_t value);
+void google_protobuf_DescriptorProto_ReservedRange_set_end(google_protobuf_DescriptorProto_ReservedRange *msg, int32_t value);
+
+
+/* google_protobuf_ExtensionRangeOptions */
+extern const upb_msglayout_msginit_v1 google_protobuf_ExtensionRangeOptions_msginit;
+google_protobuf_ExtensionRangeOptions *google_protobuf_ExtensionRangeOptions_new(upb_env *env);
+google_protobuf_ExtensionRangeOptions *google_protobuf_ExtensionRangeOptions_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_ExtensionRangeOptions_serialize(google_protobuf_ExtensionRangeOptions *msg, upb_env *env, size_t *len);
+void google_protobuf_ExtensionRangeOptions_free(google_protobuf_ExtensionRangeOptions *msg, upb_env *env);
+
+/* getters. */
+const upb_array* google_protobuf_ExtensionRangeOptions_uninterpreted_option(const google_protobuf_ExtensionRangeOptions *msg);
+
+/* setters. */
+void google_protobuf_ExtensionRangeOptions_set_uninterpreted_option(google_protobuf_ExtensionRangeOptions *msg, upb_array* value);
+
+
+/* google_protobuf_FieldDescriptorProto */
+extern const upb_msglayout_msginit_v1 google_protobuf_FieldDescriptorProto_msginit;
+google_protobuf_FieldDescriptorProto *google_protobuf_FieldDescriptorProto_new(upb_env *env);
+google_protobuf_FieldDescriptorProto *google_protobuf_FieldDescriptorProto_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_FieldDescriptorProto_serialize(google_protobuf_FieldDescriptorProto *msg, upb_env *env, size_t *len);
+void google_protobuf_FieldDescriptorProto_free(google_protobuf_FieldDescriptorProto *msg, upb_env *env);
+
+/* getters. */
+upb_stringview google_protobuf_FieldDescriptorProto_name(const google_protobuf_FieldDescriptorProto *msg);
+upb_stringview google_protobuf_FieldDescriptorProto_extendee(const google_protobuf_FieldDescriptorProto *msg);
+int32_t google_protobuf_FieldDescriptorProto_number(const google_protobuf_FieldDescriptorProto *msg);
+google_protobuf_FieldDescriptorProto_Label google_protobuf_FieldDescriptorProto_label(const google_protobuf_FieldDescriptorProto *msg);
+google_protobuf_FieldDescriptorProto_Type google_protobuf_FieldDescriptorProto_type(const google_protobuf_FieldDescriptorProto *msg);
+upb_stringview google_protobuf_FieldDescriptorProto_type_name(const google_protobuf_FieldDescriptorProto *msg);
+upb_stringview google_protobuf_FieldDescriptorProto_default_value(const google_protobuf_FieldDescriptorProto *msg);
+const google_protobuf_FieldOptions* google_protobuf_FieldDescriptorProto_options(const google_protobuf_FieldDescriptorProto *msg);
+int32_t google_protobuf_FieldDescriptorProto_oneof_index(const google_protobuf_FieldDescriptorProto *msg);
+upb_stringview google_protobuf_FieldDescriptorProto_json_name(const google_protobuf_FieldDescriptorProto *msg);
+
+/* setters. */
+void google_protobuf_FieldDescriptorProto_set_name(google_protobuf_FieldDescriptorProto *msg, upb_stringview value);
+void google_protobuf_FieldDescriptorProto_set_extendee(google_protobuf_FieldDescriptorProto *msg, upb_stringview value);
+void google_protobuf_FieldDescriptorProto_set_number(google_protobuf_FieldDescriptorProto *msg, int32_t value);
+void google_protobuf_FieldDescriptorProto_set_label(google_protobuf_FieldDescriptorProto *msg, google_protobuf_FieldDescriptorProto_Label value);
+void google_protobuf_FieldDescriptorProto_set_type(google_protobuf_FieldDescriptorProto *msg, google_protobuf_FieldDescriptorProto_Type value);
+void google_protobuf_FieldDescriptorProto_set_type_name(google_protobuf_FieldDescriptorProto *msg, upb_stringview value);
+void google_protobuf_FieldDescriptorProto_set_default_value(google_protobuf_FieldDescriptorProto *msg, upb_stringview value);
+void google_protobuf_FieldDescriptorProto_set_options(google_protobuf_FieldDescriptorProto *msg, google_protobuf_FieldOptions* value);
+void google_protobuf_FieldDescriptorProto_set_oneof_index(google_protobuf_FieldDescriptorProto *msg, int32_t value);
+void google_protobuf_FieldDescriptorProto_set_json_name(google_protobuf_FieldDescriptorProto *msg, upb_stringview value);
+
+
+/* google_protobuf_OneofDescriptorProto */
+extern const upb_msglayout_msginit_v1 google_protobuf_OneofDescriptorProto_msginit;
+google_protobuf_OneofDescriptorProto *google_protobuf_OneofDescriptorProto_new(upb_env *env);
+google_protobuf_OneofDescriptorProto *google_protobuf_OneofDescriptorProto_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_OneofDescriptorProto_serialize(google_protobuf_OneofDescriptorProto *msg, upb_env *env, size_t *len);
+void google_protobuf_OneofDescriptorProto_free(google_protobuf_OneofDescriptorProto *msg, upb_env *env);
+
+/* getters. */
+upb_stringview google_protobuf_OneofDescriptorProto_name(const google_protobuf_OneofDescriptorProto *msg);
+const google_protobuf_OneofOptions* google_protobuf_OneofDescriptorProto_options(const google_protobuf_OneofDescriptorProto *msg);
+
+/* setters. */
+void google_protobuf_OneofDescriptorProto_set_name(google_protobuf_OneofDescriptorProto *msg, upb_stringview value);
+void google_protobuf_OneofDescriptorProto_set_options(google_protobuf_OneofDescriptorProto *msg, google_protobuf_OneofOptions* value);
+
+
+/* google_protobuf_EnumDescriptorProto */
+extern const upb_msglayout_msginit_v1 google_protobuf_EnumDescriptorProto_msginit;
+google_protobuf_EnumDescriptorProto *google_protobuf_EnumDescriptorProto_new(upb_env *env);
+google_protobuf_EnumDescriptorProto *google_protobuf_EnumDescriptorProto_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_EnumDescriptorProto_serialize(google_protobuf_EnumDescriptorProto *msg, upb_env *env, size_t *len);
+void google_protobuf_EnumDescriptorProto_free(google_protobuf_EnumDescriptorProto *msg, upb_env *env);
+
+/* getters. */
+upb_stringview google_protobuf_EnumDescriptorProto_name(const google_protobuf_EnumDescriptorProto *msg);
+const upb_array* google_protobuf_EnumDescriptorProto_value(const google_protobuf_EnumDescriptorProto *msg);
+const google_protobuf_EnumOptions* google_protobuf_EnumDescriptorProto_options(const google_protobuf_EnumDescriptorProto *msg);
+const upb_array* google_protobuf_EnumDescriptorProto_reserved_range(const google_protobuf_EnumDescriptorProto *msg);
+const upb_array* google_protobuf_EnumDescriptorProto_reserved_name(const google_protobuf_EnumDescriptorProto *msg);
+
+/* setters. */
+void google_protobuf_EnumDescriptorProto_set_name(google_protobuf_EnumDescriptorProto *msg, upb_stringview value);
+void google_protobuf_EnumDescriptorProto_set_value(google_protobuf_EnumDescriptorProto *msg, upb_array* value);
+void google_protobuf_EnumDescriptorProto_set_options(google_protobuf_EnumDescriptorProto *msg, google_protobuf_EnumOptions* value);
+void google_protobuf_EnumDescriptorProto_set_reserved_range(google_protobuf_EnumDescriptorProto *msg, upb_array* value);
+void google_protobuf_EnumDescriptorProto_set_reserved_name(google_protobuf_EnumDescriptorProto *msg, upb_array* value);
+
+
+/* google_protobuf_EnumDescriptorProto_EnumReservedRange */
+extern const upb_msglayout_msginit_v1 google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit;
+google_protobuf_EnumDescriptorProto_EnumReservedRange *google_protobuf_EnumDescriptorProto_EnumReservedRange_new(upb_env *env);
+google_protobuf_EnumDescriptorProto_EnumReservedRange *google_protobuf_EnumDescriptorProto_EnumReservedRange_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_EnumDescriptorProto_EnumReservedRange_serialize(google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, upb_env *env, size_t *len);
+void google_protobuf_EnumDescriptorProto_EnumReservedRange_free(google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, upb_env *env);
+
+/* getters. */
+int32_t google_protobuf_EnumDescriptorProto_EnumReservedRange_start(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg);
+int32_t google_protobuf_EnumDescriptorProto_EnumReservedRange_end(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg);
+
+/* setters. */
+void google_protobuf_EnumDescriptorProto_EnumReservedRange_set_start(google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, int32_t value);
+void google_protobuf_EnumDescriptorProto_EnumReservedRange_set_end(google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, int32_t value);
+
+
+/* google_protobuf_EnumValueDescriptorProto */
+extern const upb_msglayout_msginit_v1 google_protobuf_EnumValueDescriptorProto_msginit;
+google_protobuf_EnumValueDescriptorProto *google_protobuf_EnumValueDescriptorProto_new(upb_env *env);
+google_protobuf_EnumValueDescriptorProto *google_protobuf_EnumValueDescriptorProto_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_EnumValueDescriptorProto_serialize(google_protobuf_EnumValueDescriptorProto *msg, upb_env *env, size_t *len);
+void google_protobuf_EnumValueDescriptorProto_free(google_protobuf_EnumValueDescriptorProto *msg, upb_env *env);
+
+/* getters. */
+upb_stringview google_protobuf_EnumValueDescriptorProto_name(const google_protobuf_EnumValueDescriptorProto *msg);
+int32_t google_protobuf_EnumValueDescriptorProto_number(const google_protobuf_EnumValueDescriptorProto *msg);
+const google_protobuf_EnumValueOptions* google_protobuf_EnumValueDescriptorProto_options(const google_protobuf_EnumValueDescriptorProto *msg);
+
+/* setters. */
+void google_protobuf_EnumValueDescriptorProto_set_name(google_protobuf_EnumValueDescriptorProto *msg, upb_stringview value);
+void google_protobuf_EnumValueDescriptorProto_set_number(google_protobuf_EnumValueDescriptorProto *msg, int32_t value);
+void google_protobuf_EnumValueDescriptorProto_set_options(google_protobuf_EnumValueDescriptorProto *msg, google_protobuf_EnumValueOptions* value);
+
+
+/* google_protobuf_ServiceDescriptorProto */
+extern const upb_msglayout_msginit_v1 google_protobuf_ServiceDescriptorProto_msginit;
+google_protobuf_ServiceDescriptorProto *google_protobuf_ServiceDescriptorProto_new(upb_env *env);
+google_protobuf_ServiceDescriptorProto *google_protobuf_ServiceDescriptorProto_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_ServiceDescriptorProto_serialize(google_protobuf_ServiceDescriptorProto *msg, upb_env *env, size_t *len);
+void google_protobuf_ServiceDescriptorProto_free(google_protobuf_ServiceDescriptorProto *msg, upb_env *env);
+
+/* getters. */
+upb_stringview google_protobuf_ServiceDescriptorProto_name(const google_protobuf_ServiceDescriptorProto *msg);
+const upb_array* google_protobuf_ServiceDescriptorProto_method(const google_protobuf_ServiceDescriptorProto *msg);
+const google_protobuf_ServiceOptions* google_protobuf_ServiceDescriptorProto_options(const google_protobuf_ServiceDescriptorProto *msg);
+
+/* setters. */
+void google_protobuf_ServiceDescriptorProto_set_name(google_protobuf_ServiceDescriptorProto *msg, upb_stringview value);
+void google_protobuf_ServiceDescriptorProto_set_method(google_protobuf_ServiceDescriptorProto *msg, upb_array* value);
+void google_protobuf_ServiceDescriptorProto_set_options(google_protobuf_ServiceDescriptorProto *msg, google_protobuf_ServiceOptions* value);
+
+
+/* google_protobuf_MethodDescriptorProto */
+extern const upb_msglayout_msginit_v1 google_protobuf_MethodDescriptorProto_msginit;
+google_protobuf_MethodDescriptorProto *google_protobuf_MethodDescriptorProto_new(upb_env *env);
+google_protobuf_MethodDescriptorProto *google_protobuf_MethodDescriptorProto_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_MethodDescriptorProto_serialize(google_protobuf_MethodDescriptorProto *msg, upb_env *env, size_t *len);
+void google_protobuf_MethodDescriptorProto_free(google_protobuf_MethodDescriptorProto *msg, upb_env *env);
+
+/* getters. */
+upb_stringview google_protobuf_MethodDescriptorProto_name(const google_protobuf_MethodDescriptorProto *msg);
+upb_stringview google_protobuf_MethodDescriptorProto_input_type(const google_protobuf_MethodDescriptorProto *msg);
+upb_stringview google_protobuf_MethodDescriptorProto_output_type(const google_protobuf_MethodDescriptorProto *msg);
+const google_protobuf_MethodOptions* google_protobuf_MethodDescriptorProto_options(const google_protobuf_MethodDescriptorProto *msg);
+bool google_protobuf_MethodDescriptorProto_client_streaming(const google_protobuf_MethodDescriptorProto *msg);
+bool google_protobuf_MethodDescriptorProto_server_streaming(const google_protobuf_MethodDescriptorProto *msg);
+
+/* setters. */
+void google_protobuf_MethodDescriptorProto_set_name(google_protobuf_MethodDescriptorProto *msg, upb_stringview value);
+void google_protobuf_MethodDescriptorProto_set_input_type(google_protobuf_MethodDescriptorProto *msg, upb_stringview value);
+void google_protobuf_MethodDescriptorProto_set_output_type(google_protobuf_MethodDescriptorProto *msg, upb_stringview value);
+void google_protobuf_MethodDescriptorProto_set_options(google_protobuf_MethodDescriptorProto *msg, google_protobuf_MethodOptions* value);
+void google_protobuf_MethodDescriptorProto_set_client_streaming(google_protobuf_MethodDescriptorProto *msg, bool value);
+void google_protobuf_MethodDescriptorProto_set_server_streaming(google_protobuf_MethodDescriptorProto *msg, bool value);
+
+
+/* google_protobuf_FileOptions */
+extern const upb_msglayout_msginit_v1 google_protobuf_FileOptions_msginit;
+google_protobuf_FileOptions *google_protobuf_FileOptions_new(upb_env *env);
+google_protobuf_FileOptions *google_protobuf_FileOptions_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_FileOptions_serialize(google_protobuf_FileOptions *msg, upb_env *env, size_t *len);
+void google_protobuf_FileOptions_free(google_protobuf_FileOptions *msg, upb_env *env);
+
+/* getters. */
+upb_stringview google_protobuf_FileOptions_java_package(const google_protobuf_FileOptions *msg);
+upb_stringview google_protobuf_FileOptions_java_outer_classname(const google_protobuf_FileOptions *msg);
+google_protobuf_FileOptions_OptimizeMode google_protobuf_FileOptions_optimize_for(const google_protobuf_FileOptions *msg);
+bool google_protobuf_FileOptions_java_multiple_files(const google_protobuf_FileOptions *msg);
+upb_stringview google_protobuf_FileOptions_go_package(const google_protobuf_FileOptions *msg);
+bool google_protobuf_FileOptions_cc_generic_services(const google_protobuf_FileOptions *msg);
+bool google_protobuf_FileOptions_java_generic_services(const google_protobuf_FileOptions *msg);
+bool google_protobuf_FileOptions_py_generic_services(const google_protobuf_FileOptions *msg);
+bool google_protobuf_FileOptions_java_generate_equals_and_hash(const google_protobuf_FileOptions *msg);
+bool google_protobuf_FileOptions_deprecated(const google_protobuf_FileOptions *msg);
+bool google_protobuf_FileOptions_java_string_check_utf8(const google_protobuf_FileOptions *msg);
+bool google_protobuf_FileOptions_cc_enable_arenas(const google_protobuf_FileOptions *msg);
+upb_stringview google_protobuf_FileOptions_objc_class_prefix(const google_protobuf_FileOptions *msg);
+upb_stringview google_protobuf_FileOptions_csharp_namespace(const google_protobuf_FileOptions *msg);
+upb_stringview google_protobuf_FileOptions_swift_prefix(const google_protobuf_FileOptions *msg);
+upb_stringview google_protobuf_FileOptions_php_class_prefix(const google_protobuf_FileOptions *msg);
+upb_stringview google_protobuf_FileOptions_php_namespace(const google_protobuf_FileOptions *msg);
+bool google_protobuf_FileOptions_php_generic_services(const google_protobuf_FileOptions *msg);
+const upb_array* google_protobuf_FileOptions_uninterpreted_option(const google_protobuf_FileOptions *msg);
+
+/* setters. */
+void google_protobuf_FileOptions_set_java_package(google_protobuf_FileOptions *msg, upb_stringview value);
+void google_protobuf_FileOptions_set_java_outer_classname(google_protobuf_FileOptions *msg, upb_stringview value);
+void google_protobuf_FileOptions_set_optimize_for(google_protobuf_FileOptions *msg, google_protobuf_FileOptions_OptimizeMode value);
+void google_protobuf_FileOptions_set_java_multiple_files(google_protobuf_FileOptions *msg, bool value);
+void google_protobuf_FileOptions_set_go_package(google_protobuf_FileOptions *msg, upb_stringview value);
+void google_protobuf_FileOptions_set_cc_generic_services(google_protobuf_FileOptions *msg, bool value);
+void google_protobuf_FileOptions_set_java_generic_services(google_protobuf_FileOptions *msg, bool value);
+void google_protobuf_FileOptions_set_py_generic_services(google_protobuf_FileOptions *msg, bool value);
+void google_protobuf_FileOptions_set_java_generate_equals_and_hash(google_protobuf_FileOptions *msg, bool value);
+void google_protobuf_FileOptions_set_deprecated(google_protobuf_FileOptions *msg, bool value);
+void google_protobuf_FileOptions_set_java_string_check_utf8(google_protobuf_FileOptions *msg, bool value);
+void google_protobuf_FileOptions_set_cc_enable_arenas(google_protobuf_FileOptions *msg, bool value);
+void google_protobuf_FileOptions_set_objc_class_prefix(google_protobuf_FileOptions *msg, upb_stringview value);
+void google_protobuf_FileOptions_set_csharp_namespace(google_protobuf_FileOptions *msg, upb_stringview value);
+void google_protobuf_FileOptions_set_swift_prefix(google_protobuf_FileOptions *msg, upb_stringview value);
+void google_protobuf_FileOptions_set_php_class_prefix(google_protobuf_FileOptions *msg, upb_stringview value);
+void google_protobuf_FileOptions_set_php_namespace(google_protobuf_FileOptions *msg, upb_stringview value);
+void google_protobuf_FileOptions_set_php_generic_services(google_protobuf_FileOptions *msg, bool value);
+void google_protobuf_FileOptions_set_uninterpreted_option(google_protobuf_FileOptions *msg, upb_array* value);
+
+
+/* google_protobuf_MessageOptions */
+extern const upb_msglayout_msginit_v1 google_protobuf_MessageOptions_msginit;
+google_protobuf_MessageOptions *google_protobuf_MessageOptions_new(upb_env *env);
+google_protobuf_MessageOptions *google_protobuf_MessageOptions_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_MessageOptions_serialize(google_protobuf_MessageOptions *msg, upb_env *env, size_t *len);
+void google_protobuf_MessageOptions_free(google_protobuf_MessageOptions *msg, upb_env *env);
+
+/* getters. */
+bool google_protobuf_MessageOptions_message_set_wire_format(const google_protobuf_MessageOptions *msg);
+bool google_protobuf_MessageOptions_no_standard_descriptor_accessor(const google_protobuf_MessageOptions *msg);
+bool google_protobuf_MessageOptions_deprecated(const google_protobuf_MessageOptions *msg);
+bool google_protobuf_MessageOptions_map_entry(const google_protobuf_MessageOptions *msg);
+const upb_array* google_protobuf_MessageOptions_uninterpreted_option(const google_protobuf_MessageOptions *msg);
+
+/* setters. */
+void google_protobuf_MessageOptions_set_message_set_wire_format(google_protobuf_MessageOptions *msg, bool value);
+void google_protobuf_MessageOptions_set_no_standard_descriptor_accessor(google_protobuf_MessageOptions *msg, bool value);
+void google_protobuf_MessageOptions_set_deprecated(google_protobuf_MessageOptions *msg, bool value);
+void google_protobuf_MessageOptions_set_map_entry(google_protobuf_MessageOptions *msg, bool value);
+void google_protobuf_MessageOptions_set_uninterpreted_option(google_protobuf_MessageOptions *msg, upb_array* value);
+
+
+/* google_protobuf_FieldOptions */
+extern const upb_msglayout_msginit_v1 google_protobuf_FieldOptions_msginit;
+google_protobuf_FieldOptions *google_protobuf_FieldOptions_new(upb_env *env);
+google_protobuf_FieldOptions *google_protobuf_FieldOptions_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_FieldOptions_serialize(google_protobuf_FieldOptions *msg, upb_env *env, size_t *len);
+void google_protobuf_FieldOptions_free(google_protobuf_FieldOptions *msg, upb_env *env);
+
+/* getters. */
+google_protobuf_FieldOptions_CType google_protobuf_FieldOptions_ctype(const google_protobuf_FieldOptions *msg);
+bool google_protobuf_FieldOptions_packed(const google_protobuf_FieldOptions *msg);
+bool google_protobuf_FieldOptions_deprecated(const google_protobuf_FieldOptions *msg);
+bool google_protobuf_FieldOptions_lazy(const google_protobuf_FieldOptions *msg);
+google_protobuf_FieldOptions_JSType google_protobuf_FieldOptions_jstype(const google_protobuf_FieldOptions *msg);
+bool google_protobuf_FieldOptions_weak(const google_protobuf_FieldOptions *msg);
+const upb_array* google_protobuf_FieldOptions_uninterpreted_option(const google_protobuf_FieldOptions *msg);
+
+/* setters. */
+void google_protobuf_FieldOptions_set_ctype(google_protobuf_FieldOptions *msg, google_protobuf_FieldOptions_CType value);
+void google_protobuf_FieldOptions_set_packed(google_protobuf_FieldOptions *msg, bool value);
+void google_protobuf_FieldOptions_set_deprecated(google_protobuf_FieldOptions *msg, bool value);
+void google_protobuf_FieldOptions_set_lazy(google_protobuf_FieldOptions *msg, bool value);
+void google_protobuf_FieldOptions_set_jstype(google_protobuf_FieldOptions *msg, google_protobuf_FieldOptions_JSType value);
+void google_protobuf_FieldOptions_set_weak(google_protobuf_FieldOptions *msg, bool value);
+void google_protobuf_FieldOptions_set_uninterpreted_option(google_protobuf_FieldOptions *msg, upb_array* value);
+
+
+/* google_protobuf_OneofOptions */
+extern const upb_msglayout_msginit_v1 google_protobuf_OneofOptions_msginit;
+google_protobuf_OneofOptions *google_protobuf_OneofOptions_new(upb_env *env);
+google_protobuf_OneofOptions *google_protobuf_OneofOptions_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_OneofOptions_serialize(google_protobuf_OneofOptions *msg, upb_env *env, size_t *len);
+void google_protobuf_OneofOptions_free(google_protobuf_OneofOptions *msg, upb_env *env);
+
+/* getters. */
+const upb_array* google_protobuf_OneofOptions_uninterpreted_option(const google_protobuf_OneofOptions *msg);
+
+/* setters. */
+void google_protobuf_OneofOptions_set_uninterpreted_option(google_protobuf_OneofOptions *msg, upb_array* value);
+
+
+/* google_protobuf_EnumOptions */
+extern const upb_msglayout_msginit_v1 google_protobuf_EnumOptions_msginit;
+google_protobuf_EnumOptions *google_protobuf_EnumOptions_new(upb_env *env);
+google_protobuf_EnumOptions *google_protobuf_EnumOptions_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_EnumOptions_serialize(google_protobuf_EnumOptions *msg, upb_env *env, size_t *len);
+void google_protobuf_EnumOptions_free(google_protobuf_EnumOptions *msg, upb_env *env);
+
+/* getters. */
+bool google_protobuf_EnumOptions_allow_alias(const google_protobuf_EnumOptions *msg);
+bool google_protobuf_EnumOptions_deprecated(const google_protobuf_EnumOptions *msg);
+const upb_array* google_protobuf_EnumOptions_uninterpreted_option(const google_protobuf_EnumOptions *msg);
+
+/* setters. */
+void google_protobuf_EnumOptions_set_allow_alias(google_protobuf_EnumOptions *msg, bool value);
+void google_protobuf_EnumOptions_set_deprecated(google_protobuf_EnumOptions *msg, bool value);
+void google_protobuf_EnumOptions_set_uninterpreted_option(google_protobuf_EnumOptions *msg, upb_array* value);
+
+
+/* google_protobuf_EnumValueOptions */
+extern const upb_msglayout_msginit_v1 google_protobuf_EnumValueOptions_msginit;
+google_protobuf_EnumValueOptions *google_protobuf_EnumValueOptions_new(upb_env *env);
+google_protobuf_EnumValueOptions *google_protobuf_EnumValueOptions_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_EnumValueOptions_serialize(google_protobuf_EnumValueOptions *msg, upb_env *env, size_t *len);
+void google_protobuf_EnumValueOptions_free(google_protobuf_EnumValueOptions *msg, upb_env *env);
+
+/* getters. */
+bool google_protobuf_EnumValueOptions_deprecated(const google_protobuf_EnumValueOptions *msg);
+const upb_array* google_protobuf_EnumValueOptions_uninterpreted_option(const google_protobuf_EnumValueOptions *msg);
+
+/* setters. */
+void google_protobuf_EnumValueOptions_set_deprecated(google_protobuf_EnumValueOptions *msg, bool value);
+void google_protobuf_EnumValueOptions_set_uninterpreted_option(google_protobuf_EnumValueOptions *msg, upb_array* value);
+
+
+/* google_protobuf_ServiceOptions */
+extern const upb_msglayout_msginit_v1 google_protobuf_ServiceOptions_msginit;
+google_protobuf_ServiceOptions *google_protobuf_ServiceOptions_new(upb_env *env);
+google_protobuf_ServiceOptions *google_protobuf_ServiceOptions_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_ServiceOptions_serialize(google_protobuf_ServiceOptions *msg, upb_env *env, size_t *len);
+void google_protobuf_ServiceOptions_free(google_protobuf_ServiceOptions *msg, upb_env *env);
+
+/* getters. */
+bool google_protobuf_ServiceOptions_deprecated(const google_protobuf_ServiceOptions *msg);
+const upb_array* google_protobuf_ServiceOptions_uninterpreted_option(const google_protobuf_ServiceOptions *msg);
+
+/* setters. */
+void google_protobuf_ServiceOptions_set_deprecated(google_protobuf_ServiceOptions *msg, bool value);
+void google_protobuf_ServiceOptions_set_uninterpreted_option(google_protobuf_ServiceOptions *msg, upb_array* value);
+
+
+/* google_protobuf_MethodOptions */
+extern const upb_msglayout_msginit_v1 google_protobuf_MethodOptions_msginit;
+google_protobuf_MethodOptions *google_protobuf_MethodOptions_new(upb_env *env);
+google_protobuf_MethodOptions *google_protobuf_MethodOptions_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_MethodOptions_serialize(google_protobuf_MethodOptions *msg, upb_env *env, size_t *len);
+void google_protobuf_MethodOptions_free(google_protobuf_MethodOptions *msg, upb_env *env);
+
+/* getters. */
+bool google_protobuf_MethodOptions_deprecated(const google_protobuf_MethodOptions *msg);
+google_protobuf_MethodOptions_IdempotencyLevel google_protobuf_MethodOptions_idempotency_level(const google_protobuf_MethodOptions *msg);
+const upb_array* google_protobuf_MethodOptions_uninterpreted_option(const google_protobuf_MethodOptions *msg);
+
+/* setters. */
+void google_protobuf_MethodOptions_set_deprecated(google_protobuf_MethodOptions *msg, bool value);
+void google_protobuf_MethodOptions_set_idempotency_level(google_protobuf_MethodOptions *msg, google_protobuf_MethodOptions_IdempotencyLevel value);
+void google_protobuf_MethodOptions_set_uninterpreted_option(google_protobuf_MethodOptions *msg, upb_array* value);
+
+
+/* google_protobuf_UninterpretedOption */
+extern const upb_msglayout_msginit_v1 google_protobuf_UninterpretedOption_msginit;
+google_protobuf_UninterpretedOption *google_protobuf_UninterpretedOption_new(upb_env *env);
+google_protobuf_UninterpretedOption *google_protobuf_UninterpretedOption_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_UninterpretedOption_serialize(google_protobuf_UninterpretedOption *msg, upb_env *env, size_t *len);
+void google_protobuf_UninterpretedOption_free(google_protobuf_UninterpretedOption *msg, upb_env *env);
+
+/* getters. */
+const upb_array* google_protobuf_UninterpretedOption_name(const google_protobuf_UninterpretedOption *msg);
+upb_stringview google_protobuf_UninterpretedOption_identifier_value(const google_protobuf_UninterpretedOption *msg);
+uint64_t google_protobuf_UninterpretedOption_positive_int_value(const google_protobuf_UninterpretedOption *msg);
+int64_t google_protobuf_UninterpretedOption_negative_int_value(const google_protobuf_UninterpretedOption *msg);
+double google_protobuf_UninterpretedOption_double_value(const google_protobuf_UninterpretedOption *msg);
+upb_stringview google_protobuf_UninterpretedOption_string_value(const google_protobuf_UninterpretedOption *msg);
+upb_stringview google_protobuf_UninterpretedOption_aggregate_value(const google_protobuf_UninterpretedOption *msg);
+
+/* setters. */
+void google_protobuf_UninterpretedOption_set_name(google_protobuf_UninterpretedOption *msg, upb_array* value);
+void google_protobuf_UninterpretedOption_set_identifier_value(google_protobuf_UninterpretedOption *msg, upb_stringview value);
+void google_protobuf_UninterpretedOption_set_positive_int_value(google_protobuf_UninterpretedOption *msg, uint64_t value);
+void google_protobuf_UninterpretedOption_set_negative_int_value(google_protobuf_UninterpretedOption *msg, int64_t value);
+void google_protobuf_UninterpretedOption_set_double_value(google_protobuf_UninterpretedOption *msg, double value);
+void google_protobuf_UninterpretedOption_set_string_value(google_protobuf_UninterpretedOption *msg, upb_stringview value);
+void google_protobuf_UninterpretedOption_set_aggregate_value(google_protobuf_UninterpretedOption *msg, upb_stringview value);
+
+
+/* google_protobuf_UninterpretedOption_NamePart */
+extern const upb_msglayout_msginit_v1 google_protobuf_UninterpretedOption_NamePart_msginit;
+google_protobuf_UninterpretedOption_NamePart *google_protobuf_UninterpretedOption_NamePart_new(upb_env *env);
+google_protobuf_UninterpretedOption_NamePart *google_protobuf_UninterpretedOption_NamePart_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_UninterpretedOption_NamePart_serialize(google_protobuf_UninterpretedOption_NamePart *msg, upb_env *env, size_t *len);
+void google_protobuf_UninterpretedOption_NamePart_free(google_protobuf_UninterpretedOption_NamePart *msg, upb_env *env);
+
+/* getters. */
+upb_stringview google_protobuf_UninterpretedOption_NamePart_name_part(const google_protobuf_UninterpretedOption_NamePart *msg);
+bool google_protobuf_UninterpretedOption_NamePart_is_extension(const google_protobuf_UninterpretedOption_NamePart *msg);
+
+/* setters. */
+void google_protobuf_UninterpretedOption_NamePart_set_name_part(google_protobuf_UninterpretedOption_NamePart *msg, upb_stringview value);
+void google_protobuf_UninterpretedOption_NamePart_set_is_extension(google_protobuf_UninterpretedOption_NamePart *msg, bool value);
+
+
+/* google_protobuf_SourceCodeInfo */
+extern const upb_msglayout_msginit_v1 google_protobuf_SourceCodeInfo_msginit;
+google_protobuf_SourceCodeInfo *google_protobuf_SourceCodeInfo_new(upb_env *env);
+google_protobuf_SourceCodeInfo *google_protobuf_SourceCodeInfo_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_SourceCodeInfo_serialize(google_protobuf_SourceCodeInfo *msg, upb_env *env, size_t *len);
+void google_protobuf_SourceCodeInfo_free(google_protobuf_SourceCodeInfo *msg, upb_env *env);
+
+/* getters. */
+const upb_array* google_protobuf_SourceCodeInfo_location(const google_protobuf_SourceCodeInfo *msg);
+
+/* setters. */
+void google_protobuf_SourceCodeInfo_set_location(google_protobuf_SourceCodeInfo *msg, upb_array* value);
+
+
+/* google_protobuf_SourceCodeInfo_Location */
+extern const upb_msglayout_msginit_v1 google_protobuf_SourceCodeInfo_Location_msginit;
+google_protobuf_SourceCodeInfo_Location *google_protobuf_SourceCodeInfo_Location_new(upb_env *env);
+google_protobuf_SourceCodeInfo_Location *google_protobuf_SourceCodeInfo_Location_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_SourceCodeInfo_Location_serialize(google_protobuf_SourceCodeInfo_Location *msg, upb_env *env, size_t *len);
+void google_protobuf_SourceCodeInfo_Location_free(google_protobuf_SourceCodeInfo_Location *msg, upb_env *env);
+
+/* getters. */
+const upb_array* google_protobuf_SourceCodeInfo_Location_path(const google_protobuf_SourceCodeInfo_Location *msg);
+const upb_array* google_protobuf_SourceCodeInfo_Location_span(const google_protobuf_SourceCodeInfo_Location *msg);
+upb_stringview google_protobuf_SourceCodeInfo_Location_leading_comments(const google_protobuf_SourceCodeInfo_Location *msg);
+upb_stringview google_protobuf_SourceCodeInfo_Location_trailing_comments(const google_protobuf_SourceCodeInfo_Location *msg);
+const upb_array* google_protobuf_SourceCodeInfo_Location_leading_detached_comments(const google_protobuf_SourceCodeInfo_Location *msg);
+
+/* setters. */
+void google_protobuf_SourceCodeInfo_Location_set_path(google_protobuf_SourceCodeInfo_Location *msg, upb_array* value);
+void google_protobuf_SourceCodeInfo_Location_set_span(google_protobuf_SourceCodeInfo_Location *msg, upb_array* value);
+void google_protobuf_SourceCodeInfo_Location_set_leading_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_stringview value);
+void google_protobuf_SourceCodeInfo_Location_set_trailing_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_stringview value);
+void google_protobuf_SourceCodeInfo_Location_set_leading_detached_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_array* value);
+
+
+/* google_protobuf_GeneratedCodeInfo */
+extern const upb_msglayout_msginit_v1 google_protobuf_GeneratedCodeInfo_msginit;
+google_protobuf_GeneratedCodeInfo *google_protobuf_GeneratedCodeInfo_new(upb_env *env);
+google_protobuf_GeneratedCodeInfo *google_protobuf_GeneratedCodeInfo_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_GeneratedCodeInfo_serialize(google_protobuf_GeneratedCodeInfo *msg, upb_env *env, size_t *len);
+void google_protobuf_GeneratedCodeInfo_free(google_protobuf_GeneratedCodeInfo *msg, upb_env *env);
+
+/* getters. */
+const upb_array* google_protobuf_GeneratedCodeInfo_annotation(const google_protobuf_GeneratedCodeInfo *msg);
+
+/* setters. */
+void google_protobuf_GeneratedCodeInfo_set_annotation(google_protobuf_GeneratedCodeInfo *msg, upb_array* value);
+
+
+/* google_protobuf_GeneratedCodeInfo_Annotation */
+extern const upb_msglayout_msginit_v1 google_protobuf_GeneratedCodeInfo_Annotation_msginit;
+google_protobuf_GeneratedCodeInfo_Annotation *google_protobuf_GeneratedCodeInfo_Annotation_new(upb_env *env);
+google_protobuf_GeneratedCodeInfo_Annotation *google_protobuf_GeneratedCodeInfo_Annotation_parsenew(upb_stringview buf, upb_env *env);
+char *google_protobuf_GeneratedCodeInfo_Annotation_serialize(google_protobuf_GeneratedCodeInfo_Annotation *msg, upb_env *env, size_t *len);
+void google_protobuf_GeneratedCodeInfo_Annotation_free(google_protobuf_GeneratedCodeInfo_Annotation *msg, upb_env *env);
+
+/* getters. */
+const upb_array* google_protobuf_GeneratedCodeInfo_Annotation_path(const google_protobuf_GeneratedCodeInfo_Annotation *msg);
+upb_stringview google_protobuf_GeneratedCodeInfo_Annotation_source_file(const google_protobuf_GeneratedCodeInfo_Annotation *msg);
+int32_t google_protobuf_GeneratedCodeInfo_Annotation_begin(const google_protobuf_GeneratedCodeInfo_Annotation *msg);
+int32_t google_protobuf_GeneratedCodeInfo_Annotation_end(const google_protobuf_GeneratedCodeInfo_Annotation *msg);
+
+/* setters. */
+void google_protobuf_GeneratedCodeInfo_Annotation_set_path(google_protobuf_GeneratedCodeInfo_Annotation *msg, upb_array* value);
+void google_protobuf_GeneratedCodeInfo_Annotation_set_source_file(google_protobuf_GeneratedCodeInfo_Annotation *msg, upb_stringview value);
+void google_protobuf_GeneratedCodeInfo_Annotation_set_begin(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t value);
+void google_protobuf_GeneratedCodeInfo_Annotation_set_end(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t value);
+
+
+UPB_END_EXTERN_C
+
+#endif /* GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_ */
+/*
** structs.int.h: structures definitions that are internal to upb.
*/
@@ -7001,22 +7713,6 @@ extern const struct upb_refcounted_vtbl upb_filedef_vtbl;
#endif /* UPB_STATICINIT_H_ */
/*
-** upb_encode: parsing into a upb_msg using a upb_msglayout.
-*/
-
-#ifndef UPB_ENCODE_H_
-#define UPB_ENCODE_H_
-
-
-UPB_BEGIN_EXTERN_C
-
-char *upb_encode(const void *msg, const upb_msglayout_msginit_v1 *l,
- upb_env *env, size_t *size);
-
-UPB_END_EXTERN_C
-
-#endif /* UPB_ENCODE_H_ */
-/*
** upb::descriptor::Reader (upb_descreader)
**
** Provides a way of building upb::Defs from data in descriptor.proto format.
@@ -7118,53 +7814,6 @@ inline FileDef* Reader::file(size_t i) const {
UPB_BEGIN_EXTERN_C
-/* Enums */
-
-typedef enum {
- google_protobuf_FieldDescriptorProto_LABEL_OPTIONAL = 1,
- google_protobuf_FieldDescriptorProto_LABEL_REQUIRED = 2,
- google_protobuf_FieldDescriptorProto_LABEL_REPEATED = 3
-} google_protobuf_FieldDescriptorProto_Label;
-
-typedef enum {
- google_protobuf_FieldDescriptorProto_TYPE_DOUBLE = 1,
- google_protobuf_FieldDescriptorProto_TYPE_FLOAT = 2,
- google_protobuf_FieldDescriptorProto_TYPE_INT64 = 3,
- google_protobuf_FieldDescriptorProto_TYPE_UINT64 = 4,
- google_protobuf_FieldDescriptorProto_TYPE_INT32 = 5,
- google_protobuf_FieldDescriptorProto_TYPE_FIXED64 = 6,
- google_protobuf_FieldDescriptorProto_TYPE_FIXED32 = 7,
- google_protobuf_FieldDescriptorProto_TYPE_BOOL = 8,
- google_protobuf_FieldDescriptorProto_TYPE_STRING = 9,
- google_protobuf_FieldDescriptorProto_TYPE_GROUP = 10,
- google_protobuf_FieldDescriptorProto_TYPE_MESSAGE = 11,
- google_protobuf_FieldDescriptorProto_TYPE_BYTES = 12,
- google_protobuf_FieldDescriptorProto_TYPE_UINT32 = 13,
- google_protobuf_FieldDescriptorProto_TYPE_ENUM = 14,
- google_protobuf_FieldDescriptorProto_TYPE_SFIXED32 = 15,
- google_protobuf_FieldDescriptorProto_TYPE_SFIXED64 = 16,
- google_protobuf_FieldDescriptorProto_TYPE_SINT32 = 17,
- google_protobuf_FieldDescriptorProto_TYPE_SINT64 = 18
-} google_protobuf_FieldDescriptorProto_Type;
-
-typedef enum {
- google_protobuf_FieldOptions_STRING = 0,
- google_protobuf_FieldOptions_CORD = 1,
- google_protobuf_FieldOptions_STRING_PIECE = 2
-} google_protobuf_FieldOptions_CType;
-
-typedef enum {
- google_protobuf_FieldOptions_JS_NORMAL = 0,
- google_protobuf_FieldOptions_JS_STRING = 1,
- google_protobuf_FieldOptions_JS_NUMBER = 2
-} google_protobuf_FieldOptions_JSType;
-
-typedef enum {
- google_protobuf_FileOptions_SPEED = 1,
- google_protobuf_FileOptions_CODE_SIZE = 2,
- google_protobuf_FileOptions_LITE_RUNTIME = 3
-} google_protobuf_FileOptions_OptimizeMode;
-
/* MessageDefs: call these functions to get a ref to a msgdef. */
const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_get(const void *owner);
const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_get(const void *owner);
diff --git a/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php b/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php
index b0ca8da0..e6362f2b 100644
--- a/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php
+++ b/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php
@@ -46,13 +46,13 @@ class Descriptor
->repeated('reserved_name', \Google\Protobuf\Internal\GPBType::STRING, 10)
->finalizeToPool();
- $pool->addMessage('google.protobuf.internal.DescriptorProto.ExtensionRange', \Google\Protobuf\Internal\DescriptorProto_ExtensionRange::class)
+ $pool->addMessage('google.protobuf.internal.DescriptorProto.ExtensionRange', \Google\Protobuf\Internal\DescriptorProto\ExtensionRange::class)
->optional('start', \Google\Protobuf\Internal\GPBType::INT32, 1)
->optional('end', \Google\Protobuf\Internal\GPBType::INT32, 2)
->optional('options', \Google\Protobuf\Internal\GPBType::MESSAGE, 3, 'google.protobuf.internal.ExtensionRangeOptions')
->finalizeToPool();
- $pool->addMessage('google.protobuf.internal.DescriptorProto.ReservedRange', \Google\Protobuf\Internal\DescriptorProto_ReservedRange::class)
+ $pool->addMessage('google.protobuf.internal.DescriptorProto.ReservedRange', \Google\Protobuf\Internal\DescriptorProto\ReservedRange::class)
->optional('start', \Google\Protobuf\Internal\GPBType::INT32, 1)
->optional('end', \Google\Protobuf\Internal\GPBType::INT32, 2)
->finalizeToPool();
@@ -114,7 +114,7 @@ class Descriptor
->repeated('reserved_name', \Google\Protobuf\Internal\GPBType::STRING, 5)
->finalizeToPool();
- $pool->addMessage('google.protobuf.internal.EnumDescriptorProto.EnumReservedRange', \Google\Protobuf\Internal\EnumDescriptorProto_EnumReservedRange::class)
+ $pool->addMessage('google.protobuf.internal.EnumDescriptorProto.EnumReservedRange', \Google\Protobuf\Internal\EnumDescriptorProto\EnumReservedRange::class)
->optional('start', \Google\Protobuf\Internal\GPBType::INT32, 1)
->optional('end', \Google\Protobuf\Internal\GPBType::INT32, 2)
->finalizeToPool();
@@ -159,6 +159,8 @@ class Descriptor
->optional('swift_prefix', \Google\Protobuf\Internal\GPBType::STRING, 39)
->optional('php_class_prefix', \Google\Protobuf\Internal\GPBType::STRING, 40)
->optional('php_namespace', \Google\Protobuf\Internal\GPBType::STRING, 41)
+ ->optional('php_metadata_namespace', \Google\Protobuf\Internal\GPBType::STRING, 44)
+ ->optional('ruby_package', \Google\Protobuf\Internal\GPBType::STRING, 45)
->repeated('uninterpreted_option', \Google\Protobuf\Internal\GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption')
->finalizeToPool();
@@ -240,7 +242,7 @@ class Descriptor
->optional('aggregate_value', \Google\Protobuf\Internal\GPBType::STRING, 8)
->finalizeToPool();
- $pool->addMessage('google.protobuf.internal.UninterpretedOption.NamePart', \Google\Protobuf\Internal\UninterpretedOption_NamePart::class)
+ $pool->addMessage('google.protobuf.internal.UninterpretedOption.NamePart', \Google\Protobuf\Internal\UninterpretedOption\NamePart::class)
->required('name_part', \Google\Protobuf\Internal\GPBType::STRING, 1)
->required('is_extension', \Google\Protobuf\Internal\GPBType::BOOL, 2)
->finalizeToPool();
@@ -249,7 +251,7 @@ class Descriptor
->repeated('location', \Google\Protobuf\Internal\GPBType::MESSAGE, 1, 'google.protobuf.internal.SourceCodeInfo.Location')
->finalizeToPool();
- $pool->addMessage('google.protobuf.internal.SourceCodeInfo.Location', \Google\Protobuf\Internal\SourceCodeInfo_Location::class)
+ $pool->addMessage('google.protobuf.internal.SourceCodeInfo.Location', \Google\Protobuf\Internal\SourceCodeInfo\Location::class)
->repeated('path', \Google\Protobuf\Internal\GPBType::INT32, 1)
->repeated('span', \Google\Protobuf\Internal\GPBType::INT32, 2)
->optional('leading_comments', \Google\Protobuf\Internal\GPBType::STRING, 3)
@@ -261,7 +263,7 @@ class Descriptor
->repeated('annotation', \Google\Protobuf\Internal\GPBType::MESSAGE, 1, 'google.protobuf.internal.GeneratedCodeInfo.Annotation')
->finalizeToPool();
- $pool->addMessage('google.protobuf.internal.GeneratedCodeInfo.Annotation', \Google\Protobuf\Internal\GeneratedCodeInfo_Annotation::class)
+ $pool->addMessage('google.protobuf.internal.GeneratedCodeInfo.Annotation', \Google\Protobuf\Internal\GeneratedCodeInfo\Annotation::class)
->repeated('path', \Google\Protobuf\Internal\GPBType::INT32, 1)
->optional('source_file', \Google\Protobuf\Internal\GPBType::STRING, 2)
->optional('begin', \Google\Protobuf\Internal\GPBType::INT32, 3)
diff --git a/php/src/Google/Protobuf/Any.php b/php/src/Google/Protobuf/Any.php
index f027b05d..a9928549 100644
--- a/php/src/Google/Protobuf/Any.php
+++ b/php/src/Google/Protobuf/Any.php
@@ -5,9 +5,9 @@
namespace Google\Protobuf;
use Google\Protobuf\Internal\GPBType;
-use Google\Protobuf\Internal\GPBUtil;
use Google\Protobuf\Internal\Message;
use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
/**
* `Any` contains an arbitrary serialized protocol buffer message along with a
@@ -37,6 +37,14 @@ use Google\Protobuf\Internal\RepeatedField;
* if any.Is(Foo.DESCRIPTOR):
* any.Unpack(foo)
* ...
+ * Example 4: Pack and unpack a message in Go
+ * foo := &pb.Foo{...}
+ * any, err := ptypes.MarshalAny(foo)
+ * ...
+ * foo := &pb.Foo{}
+ * if err := ptypes.UnmarshalAny(any, foo); err != nil {
+ * ...
+ * }
* The pack methods provided by protobuf library will by default use
* 'type.googleapis.com/full.type.name' as the type URL and the unpack
* methods only use the fully qualified type name after the last '/'
@@ -71,15 +79,16 @@ use Google\Protobuf\Internal\RepeatedField;
class Any extends \Google\Protobuf\Internal\Message
{
/**
- * A URL/resource name whose content describes the type of the
- * serialized protocol buffer message.
- * For URLs which use the scheme `http`, `https`, or no scheme, the
- * following restrictions and interpretations apply:
+ * 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
+ * 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).
+ * In practice, teams usually precompile into the binary all types that they
+ * expect it to use in the context of Any. However, for URLs which use the
+ * scheme `http`, `https`, or no scheme, one can optionally set up a type
+ * server that maps type URLs to message definitions as follows:
* * If no scheme is provided, `https` is assumed.
- * * The last segment of the URL's path must represent the fully
- * qualified name of the type (as in `path/google.protobuf.Duration`).
- * The name should be in a canonical form (e.g., leading "." is
- * not accepted).
* * An HTTP GET on the URL must yield a [google.protobuf.Type][]
* value in binary format, or produce an error.
* * Applications are allowed to cache lookup results based on the
@@ -87,6 +96,9 @@ class Any extends \Google\Protobuf\Internal\Message
* lookup. Therefore, binary compatibility needs to be preserved
* on changes to types. (Use versioned type names to manage
* breaking changes.)
+ * Note: this functionality is not currently available in the official
+ * protobuf release, and it is not used for type URLs beginning with
+ * type.googleapis.com.
* Schemes other than `http`, `https` (or the empty scheme) might be
* used with implementation specific semantics.
*
@@ -102,21 +114,55 @@ class Any extends \Google\Protobuf\Internal\Message
const TYPE_URL_PREFIX = 'type.googleapis.com/';
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $type_url
+ * 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
+ * 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).
+ * In practice, teams usually precompile into the binary all types that they
+ * expect it to use in the context of Any. However, for URLs which use the
+ * scheme `http`, `https`, or no scheme, one can optionally set up a type
+ * server that maps type URLs to message definitions as follows:
+ * * If no scheme is provided, `https` is assumed.
+ * * An HTTP GET on the URL must yield a [google.protobuf.Type][]
+ * value in binary format, or produce an error.
+ * * Applications are allowed to cache lookup results based on the
+ * URL, or have them precompiled into a binary to avoid any
+ * lookup. Therefore, binary compatibility needs to be preserved
+ * on changes to types. (Use versioned type names to manage
+ * breaking changes.)
+ * Note: this functionality is not currently available in the official
+ * protobuf release, and it is not used for type URLs beginning with
+ * type.googleapis.com.
+ * Schemes other than `http`, `https` (or the empty scheme) might be
+ * used with implementation specific semantics.
+ * @type string $value
+ * Must be a valid serialized protocol buffer of the above specified type.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Any::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
- * A URL/resource name whose content describes the type of the
- * serialized protocol buffer message.
- * For URLs which use the scheme `http`, `https`, or no scheme, the
- * following restrictions and interpretations apply:
+ * 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
+ * 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).
+ * In practice, teams usually precompile into the binary all types that they
+ * expect it to use in the context of Any. However, for URLs which use the
+ * scheme `http`, `https`, or no scheme, one can optionally set up a type
+ * server that maps type URLs to message definitions as follows:
* * If no scheme is provided, `https` is assumed.
- * * The last segment of the URL's path must represent the fully
- * qualified name of the type (as in `path/google.protobuf.Duration`).
- * The name should be in a canonical form (e.g., leading "." is
- * not accepted).
* * An HTTP GET on the URL must yield a [google.protobuf.Type][]
* value in binary format, or produce an error.
* * Applications are allowed to cache lookup results based on the
@@ -124,6 +170,9 @@ class Any extends \Google\Protobuf\Internal\Message
* lookup. Therefore, binary compatibility needs to be preserved
* on changes to types. (Use versioned type names to manage
* breaking changes.)
+ * Note: this functionality is not currently available in the official
+ * protobuf release, and it is not used for type URLs beginning with
+ * type.googleapis.com.
* Schemes other than `http`, `https` (or the empty scheme) might be
* used with implementation specific semantics.
*
@@ -136,15 +185,16 @@ class Any extends \Google\Protobuf\Internal\Message
}
/**
- * A URL/resource name whose content describes the type of the
- * serialized protocol buffer message.
- * For URLs which use the scheme `http`, `https`, or no scheme, the
- * following restrictions and interpretations apply:
+ * 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
+ * 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).
+ * In practice, teams usually precompile into the binary all types that they
+ * expect it to use in the context of Any. However, for URLs which use the
+ * scheme `http`, `https`, or no scheme, one can optionally set up a type
+ * server that maps type URLs to message definitions as follows:
* * If no scheme is provided, `https` is assumed.
- * * The last segment of the URL's path must represent the fully
- * qualified name of the type (as in `path/google.protobuf.Duration`).
- * The name should be in a canonical form (e.g., leading "." is
- * not accepted).
* * An HTTP GET on the URL must yield a [google.protobuf.Type][]
* value in binary format, or produce an error.
* * Applications are allowed to cache lookup results based on the
@@ -152,6 +202,9 @@ class Any extends \Google\Protobuf\Internal\Message
* lookup. Therefore, binary compatibility needs to be preserved
* on changes to types. (Use versioned type names to manage
* breaking changes.)
+ * Note: this functionality is not currently available in the official
+ * protobuf release, and it is not used for type URLs beginning with
+ * type.googleapis.com.
* Schemes other than `http`, `https` (or the empty scheme) might be
* used with implementation specific semantics.
*
@@ -269,3 +322,4 @@ class Any extends \Google\Protobuf\Internal\Message
return $this->type_url === $type_url;
}
}
+
diff --git a/php/src/Google/Protobuf/Api.php b/php/src/Google/Protobuf/Api.php
index d0dda3cd..db37ffb0 100644
--- a/php/src/Google/Protobuf/Api.php
+++ b/php/src/Google/Protobuf/Api.php
@@ -83,9 +83,49 @@ class Api extends \Google\Protobuf\Internal\Message
*/
private $syntax = 0;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name
+ * The fully qualified name of this interface, including package name
+ * followed by the interface's simple name.
+ * @type \Google\Protobuf\Method[]|\Google\Protobuf\Internal\RepeatedField $methods
+ * The methods of this interface, in unspecified order.
+ * @type \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $options
+ * Any metadata attached to the interface.
+ * @type string $version
+ * A version string for this interface. If specified, must have the form
+ * `major-version.minor-version`, as in `1.10`. If the minor version is
+ * omitted, it defaults to zero. If the entire version field is empty, the
+ * major version is derived from the package name, as outlined below. If the
+ * field is not empty, the version in the package name will be verified to be
+ * consistent with what is provided here.
+ * The versioning schema uses [semantic
+ * versioning](http://semver.org) where the major version number
+ * indicates a breaking change and the minor version an additive,
+ * non-breaking change. Both version numbers are signals to users
+ * what to expect from different versions, and should be carefully
+ * chosen based on the product plan.
+ * The major version is also reflected in the package name of the
+ * interface, which must end in `v<major-version>`, as in
+ * `google.feature.v1`. For major versions 0 and 1, the suffix can
+ * be omitted. Zero major versions must only be used for
+ * experimental, non-GA interfaces.
+ * @type \Google\Protobuf\SourceContext $source_context
+ * Source context for the protocol buffer service represented by this
+ * message.
+ * @type \Google\Protobuf\Mixin[]|\Google\Protobuf\Internal\RepeatedField $mixins
+ * Included interfaces. See [Mixin][].
+ * @type int $syntax
+ * The source syntax of the service.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Api::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/BoolValue.php b/php/src/Google/Protobuf/BoolValue.php
index c28bf941..13872eb1 100644
--- a/php/src/Google/Protobuf/BoolValue.php
+++ b/php/src/Google/Protobuf/BoolValue.php
@@ -23,9 +23,19 @@ class BoolValue extends \Google\Protobuf\Internal\Message
*/
private $value = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type bool $value
+ * The bool value.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Wrappers::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/BytesValue.php b/php/src/Google/Protobuf/BytesValue.php
index d6a6b2e6..f1b38171 100644
--- a/php/src/Google/Protobuf/BytesValue.php
+++ b/php/src/Google/Protobuf/BytesValue.php
@@ -23,9 +23,19 @@ class BytesValue extends \Google\Protobuf\Internal\Message
*/
private $value = '';
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $value
+ * The bytes value.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Wrappers::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/DoubleValue.php b/php/src/Google/Protobuf/DoubleValue.php
index 6718ce3c..236d9182 100644
--- a/php/src/Google/Protobuf/DoubleValue.php
+++ b/php/src/Google/Protobuf/DoubleValue.php
@@ -23,9 +23,19 @@ class DoubleValue extends \Google\Protobuf\Internal\Message
*/
private $value = 0.0;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type float $value
+ * The double value.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Wrappers::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Duration.php b/php/src/Google/Protobuf/Duration.php
index ca1c4c07..414a1868 100644
--- a/php/src/Google/Protobuf/Duration.php
+++ b/php/src/Google/Protobuf/Duration.php
@@ -79,9 +79,28 @@ class Duration extends \Google\Protobuf\Internal\Message
*/
private $nanos = 0;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type int|string $seconds
+ * Signed seconds of the span of time. Must be from -315,576,000,000
+ * to +315,576,000,000 inclusive. Note: these bounds are computed from:
+ * 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
+ * @type int $nanos
+ * Signed fractions of a second at nanosecond resolution of the span
+ * of time. Durations less than one second are represented with a 0
+ * `seconds` field and a positive or negative `nanos` field. For durations
+ * of one second or more, a non-zero value for the `nanos` field must be
+ * of the same sign as the `seconds` field. Must be from -999,999,999
+ * to +999,999,999 inclusive.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Duration::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
@@ -149,5 +168,6 @@ class Duration extends \Google\Protobuf\Internal\Message
return $this;
}
+
}
diff --git a/php/src/Google/Protobuf/Enum.php b/php/src/Google/Protobuf/Enum.php
index c63efc74..243c40d2 100644
--- a/php/src/Google/Protobuf/Enum.php
+++ b/php/src/Google/Protobuf/Enum.php
@@ -46,9 +46,27 @@ class Enum extends \Google\Protobuf\Internal\Message
*/
private $syntax = 0;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name
+ * Enum type name.
+ * @type \Google\Protobuf\EnumValue[]|\Google\Protobuf\Internal\RepeatedField $enumvalue
+ * Enum value definitions.
+ * @type \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $options
+ * Protocol buffer options.
+ * @type \Google\Protobuf\SourceContext $source_context
+ * The source context.
+ * @type int $syntax
+ * The source syntax.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Type::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/EnumValue.php b/php/src/Google/Protobuf/EnumValue.php
index e102c29f..1dc3c7a6 100644
--- a/php/src/Google/Protobuf/EnumValue.php
+++ b/php/src/Google/Protobuf/EnumValue.php
@@ -34,9 +34,23 @@ class EnumValue extends \Google\Protobuf\Internal\Message
*/
private $options;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name
+ * Enum value name.
+ * @type int $number
+ * Enum value number.
+ * @type \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $options
+ * Protocol buffer options.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Type::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Field.php b/php/src/Google/Protobuf/Field.php
index 0b560d89..8da43e34 100644
--- a/php/src/Google/Protobuf/Field.php
+++ b/php/src/Google/Protobuf/Field.php
@@ -78,9 +78,39 @@ class Field extends \Google\Protobuf\Internal\Message
*/
private $default_value = '';
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type int $kind
+ * The field type.
+ * @type int $cardinality
+ * The field cardinality.
+ * @type int $number
+ * The field number.
+ * @type string $name
+ * The field name.
+ * @type string $type_url
+ * The field type URL, without the scheme, for message or enumeration
+ * types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`.
+ * @type int $oneof_index
+ * The index of the field type in `Type.oneofs`, for message or enumeration
+ * types. The first type has index 1; zero means the type is not in the list.
+ * @type bool $packed
+ * Whether to use alternative packed wire representation.
+ * @type \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $options
+ * The protocol buffer options.
+ * @type string $json_name
+ * The field JSON name.
+ * @type string $default_value
+ * The string value of the default value of this field. Proto2 syntax only.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Type::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Field/Cardinality.php b/php/src/Google/Protobuf/Field/Cardinality.php
new file mode 100644
index 00000000..c887f6d3
--- /dev/null
+++ b/php/src/Google/Protobuf/Field/Cardinality.php
@@ -0,0 +1,42 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/type.proto
+
+namespace Google\Protobuf\Field;
+
+/**
+ * Whether a field is optional, required, or repeated.
+ *
+ * Protobuf type <code>google.protobuf.Field.Cardinality</code>
+ */
+class Cardinality
+{
+ /**
+ * For fields with unknown cardinality.
+ *
+ * Generated from protobuf enum <code>CARDINALITY_UNKNOWN = 0;</code>
+ */
+ const CARDINALITY_UNKNOWN = 0;
+ /**
+ * For optional fields.
+ *
+ * Generated from protobuf enum <code>CARDINALITY_OPTIONAL = 1;</code>
+ */
+ const CARDINALITY_OPTIONAL = 1;
+ /**
+ * For required fields. Proto2 syntax only.
+ *
+ * Generated from protobuf enum <code>CARDINALITY_REQUIRED = 2;</code>
+ */
+ const CARDINALITY_REQUIRED = 2;
+ /**
+ * For repeated fields.
+ *
+ * Generated from protobuf enum <code>CARDINALITY_REPEATED = 3;</code>
+ */
+ const CARDINALITY_REPEATED = 3;
+}
+
+// Adding a class alias for backwards compatibility with the previous class name.
+class_alias(Cardinality::class, \Google\Protobuf\Field_Cardinality::class);
+
diff --git a/php/src/Google/Protobuf/Field/Kind.php b/php/src/Google/Protobuf/Field/Kind.php
new file mode 100644
index 00000000..a2bbbdeb
--- /dev/null
+++ b/php/src/Google/Protobuf/Field/Kind.php
@@ -0,0 +1,132 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/type.proto
+
+namespace Google\Protobuf\Field;
+
+/**
+ * Basic field types.
+ *
+ * Protobuf type <code>google.protobuf.Field.Kind</code>
+ */
+class Kind
+{
+ /**
+ * Field type unknown.
+ *
+ * Generated from protobuf enum <code>TYPE_UNKNOWN = 0;</code>
+ */
+ const TYPE_UNKNOWN = 0;
+ /**
+ * Field type double.
+ *
+ * Generated from protobuf enum <code>TYPE_DOUBLE = 1;</code>
+ */
+ const TYPE_DOUBLE = 1;
+ /**
+ * Field type float.
+ *
+ * Generated from protobuf enum <code>TYPE_FLOAT = 2;</code>
+ */
+ const TYPE_FLOAT = 2;
+ /**
+ * Field type int64.
+ *
+ * Generated from protobuf enum <code>TYPE_INT64 = 3;</code>
+ */
+ const TYPE_INT64 = 3;
+ /**
+ * Field type uint64.
+ *
+ * Generated from protobuf enum <code>TYPE_UINT64 = 4;</code>
+ */
+ const TYPE_UINT64 = 4;
+ /**
+ * Field type int32.
+ *
+ * Generated from protobuf enum <code>TYPE_INT32 = 5;</code>
+ */
+ const TYPE_INT32 = 5;
+ /**
+ * Field type fixed64.
+ *
+ * Generated from protobuf enum <code>TYPE_FIXED64 = 6;</code>
+ */
+ const TYPE_FIXED64 = 6;
+ /**
+ * Field type fixed32.
+ *
+ * Generated from protobuf enum <code>TYPE_FIXED32 = 7;</code>
+ */
+ const TYPE_FIXED32 = 7;
+ /**
+ * Field type bool.
+ *
+ * Generated from protobuf enum <code>TYPE_BOOL = 8;</code>
+ */
+ const TYPE_BOOL = 8;
+ /**
+ * Field type string.
+ *
+ * Generated from protobuf enum <code>TYPE_STRING = 9;</code>
+ */
+ const TYPE_STRING = 9;
+ /**
+ * Field type group. Proto2 syntax only, and deprecated.
+ *
+ * Generated from protobuf enum <code>TYPE_GROUP = 10;</code>
+ */
+ const TYPE_GROUP = 10;
+ /**
+ * Field type message.
+ *
+ * Generated from protobuf enum <code>TYPE_MESSAGE = 11;</code>
+ */
+ const TYPE_MESSAGE = 11;
+ /**
+ * Field type bytes.
+ *
+ * Generated from protobuf enum <code>TYPE_BYTES = 12;</code>
+ */
+ const TYPE_BYTES = 12;
+ /**
+ * Field type uint32.
+ *
+ * Generated from protobuf enum <code>TYPE_UINT32 = 13;</code>
+ */
+ const TYPE_UINT32 = 13;
+ /**
+ * Field type enum.
+ *
+ * Generated from protobuf enum <code>TYPE_ENUM = 14;</code>
+ */
+ const TYPE_ENUM = 14;
+ /**
+ * Field type sfixed32.
+ *
+ * Generated from protobuf enum <code>TYPE_SFIXED32 = 15;</code>
+ */
+ const TYPE_SFIXED32 = 15;
+ /**
+ * Field type sfixed64.
+ *
+ * Generated from protobuf enum <code>TYPE_SFIXED64 = 16;</code>
+ */
+ const TYPE_SFIXED64 = 16;
+ /**
+ * Field type sint32.
+ *
+ * Generated from protobuf enum <code>TYPE_SINT32 = 17;</code>
+ */
+ const TYPE_SINT32 = 17;
+ /**
+ * Field type sint64.
+ *
+ * Generated from protobuf enum <code>TYPE_SINT64 = 18;</code>
+ */
+ const TYPE_SINT64 = 18;
+}
+
+// Adding a class alias for backwards compatibility with the previous class name.
+class_alias(Kind::class, \Google\Protobuf\Field_Kind::class);
+
diff --git a/php/src/Google/Protobuf/FieldMask.php b/php/src/Google/Protobuf/FieldMask.php
index e18586af..8fb38cbf 100644
--- a/php/src/Google/Protobuf/FieldMask.php
+++ b/php/src/Google/Protobuf/FieldMask.php
@@ -162,6 +162,10 @@ use Google\Protobuf\Internal\GPBUtil;
* }
* Note that oneof type names ("test_oneof" in this case) cannot be used in
* paths.
+ * ## Field Mask Verification
+ * The implementation of any API method which has a FieldMask type field in the
+ * request should verify the included field paths, and return an
+ * `INVALID_ARGUMENT` error if any path is duplicated or unmappable.
*
* Generated from protobuf message <code>google.protobuf.FieldMask</code>
*/
@@ -174,9 +178,19 @@ class FieldMask extends \Google\Protobuf\Internal\Message
*/
private $paths;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string[]|\Google\Protobuf\Internal\RepeatedField $paths
+ * The set of field mask paths.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\FieldMask::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Field_Cardinality.php b/php/src/Google/Protobuf/Field_Cardinality.php
index 422587ca..dff8f893 100644
--- a/php/src/Google/Protobuf/Field_Cardinality.php
+++ b/php/src/Google/Protobuf/Field_Cardinality.php
@@ -4,36 +4,13 @@
namespace Google\Protobuf;
-/**
- * Whether a field is optional, required, or repeated.
- *
- * Protobuf enum <code>Google\Protobuf\Field\Cardinality</code>
- */
-class Field_Cardinality
-{
+if (false) {
/**
- * For fields with unknown cardinality.
- *
- * Generated from protobuf enum <code>CARDINALITY_UNKNOWN = 0;</code>
+ * This class is deprecated. Use Google\Protobuf\Field\Cardinality instead.
+ * @deprecated
*/
- const CARDINALITY_UNKNOWN = 0;
- /**
- * For optional fields.
- *
- * Generated from protobuf enum <code>CARDINALITY_OPTIONAL = 1;</code>
- */
- const CARDINALITY_OPTIONAL = 1;
- /**
- * For required fields. Proto2 syntax only.
- *
- * Generated from protobuf enum <code>CARDINALITY_REQUIRED = 2;</code>
- */
- const CARDINALITY_REQUIRED = 2;
- /**
- * For repeated fields.
- *
- * Generated from protobuf enum <code>CARDINALITY_REPEATED = 3;</code>
- */
- const CARDINALITY_REPEATED = 3;
+ class Field_Cardinality {}
}
+class_exists(Field\Cardinality::class);
+@trigger_error('Google\Protobuf\Field_Cardinality is deprecated and will be removed in the next major release. Use Google\Protobuf\Field\Cardinality instead', E_USER_DEPRECATED);
diff --git a/php/src/Google/Protobuf/Field_Kind.php b/php/src/Google/Protobuf/Field_Kind.php
index d0774970..aa202370 100644
--- a/php/src/Google/Protobuf/Field_Kind.php
+++ b/php/src/Google/Protobuf/Field_Kind.php
@@ -4,126 +4,13 @@
namespace Google\Protobuf;
-/**
- * Basic field types.
- *
- * Protobuf enum <code>Google\Protobuf\Field\Kind</code>
- */
-class Field_Kind
-{
+if (false) {
/**
- * Field type unknown.
- *
- * Generated from protobuf enum <code>TYPE_UNKNOWN = 0;</code>
+ * This class is deprecated. Use Google\Protobuf\Field\Kind instead.
+ * @deprecated
*/
- const TYPE_UNKNOWN = 0;
- /**
- * Field type double.
- *
- * Generated from protobuf enum <code>TYPE_DOUBLE = 1;</code>
- */
- const TYPE_DOUBLE = 1;
- /**
- * Field type float.
- *
- * Generated from protobuf enum <code>TYPE_FLOAT = 2;</code>
- */
- const TYPE_FLOAT = 2;
- /**
- * Field type int64.
- *
- * Generated from protobuf enum <code>TYPE_INT64 = 3;</code>
- */
- const TYPE_INT64 = 3;
- /**
- * Field type uint64.
- *
- * Generated from protobuf enum <code>TYPE_UINT64 = 4;</code>
- */
- const TYPE_UINT64 = 4;
- /**
- * Field type int32.
- *
- * Generated from protobuf enum <code>TYPE_INT32 = 5;</code>
- */
- const TYPE_INT32 = 5;
- /**
- * Field type fixed64.
- *
- * Generated from protobuf enum <code>TYPE_FIXED64 = 6;</code>
- */
- const TYPE_FIXED64 = 6;
- /**
- * Field type fixed32.
- *
- * Generated from protobuf enum <code>TYPE_FIXED32 = 7;</code>
- */
- const TYPE_FIXED32 = 7;
- /**
- * Field type bool.
- *
- * Generated from protobuf enum <code>TYPE_BOOL = 8;</code>
- */
- const TYPE_BOOL = 8;
- /**
- * Field type string.
- *
- * Generated from protobuf enum <code>TYPE_STRING = 9;</code>
- */
- const TYPE_STRING = 9;
- /**
- * Field type group. Proto2 syntax only, and deprecated.
- *
- * Generated from protobuf enum <code>TYPE_GROUP = 10;</code>
- */
- const TYPE_GROUP = 10;
- /**
- * Field type message.
- *
- * Generated from protobuf enum <code>TYPE_MESSAGE = 11;</code>
- */
- const TYPE_MESSAGE = 11;
- /**
- * Field type bytes.
- *
- * Generated from protobuf enum <code>TYPE_BYTES = 12;</code>
- */
- const TYPE_BYTES = 12;
- /**
- * Field type uint32.
- *
- * Generated from protobuf enum <code>TYPE_UINT32 = 13;</code>
- */
- const TYPE_UINT32 = 13;
- /**
- * Field type enum.
- *
- * Generated from protobuf enum <code>TYPE_ENUM = 14;</code>
- */
- const TYPE_ENUM = 14;
- /**
- * Field type sfixed32.
- *
- * Generated from protobuf enum <code>TYPE_SFIXED32 = 15;</code>
- */
- const TYPE_SFIXED32 = 15;
- /**
- * Field type sfixed64.
- *
- * Generated from protobuf enum <code>TYPE_SFIXED64 = 16;</code>
- */
- const TYPE_SFIXED64 = 16;
- /**
- * Field type sint32.
- *
- * Generated from protobuf enum <code>TYPE_SINT32 = 17;</code>
- */
- const TYPE_SINT32 = 17;
- /**
- * Field type sint64.
- *
- * Generated from protobuf enum <code>TYPE_SINT64 = 18;</code>
- */
- const TYPE_SINT64 = 18;
+ class Field_Kind {}
}
+class_exists(Field\Kind::class);
+@trigger_error('Google\Protobuf\Field_Kind is deprecated and will be removed in the next major release. Use Google\Protobuf\Field\Kind instead', E_USER_DEPRECATED);
diff --git a/php/src/Google/Protobuf/FloatValue.php b/php/src/Google/Protobuf/FloatValue.php
index 68787ef9..47ba52e6 100644
--- a/php/src/Google/Protobuf/FloatValue.php
+++ b/php/src/Google/Protobuf/FloatValue.php
@@ -23,9 +23,19 @@ class FloatValue extends \Google\Protobuf\Internal\Message
*/
private $value = 0.0;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type float $value
+ * The float value.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Wrappers::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/GPBEmpty.php b/php/src/Google/Protobuf/GPBEmpty.php
index 24a93f96..2de9c3bc 100644
--- a/php/src/Google/Protobuf/GPBEmpty.php
+++ b/php/src/Google/Protobuf/GPBEmpty.php
@@ -22,9 +22,17 @@ use Google\Protobuf\Internal\GPBUtil;
class GPBEmpty extends \Google\Protobuf\Internal\Message
{
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\GPBEmpty::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
}
diff --git a/php/src/Google/Protobuf/Int32Value.php b/php/src/Google/Protobuf/Int32Value.php
index d48aff1b..d7fd528d 100644
--- a/php/src/Google/Protobuf/Int32Value.php
+++ b/php/src/Google/Protobuf/Int32Value.php
@@ -23,9 +23,19 @@ class Int32Value extends \Google\Protobuf\Internal\Message
*/
private $value = 0;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type int $value
+ * The int32 value.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Wrappers::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Int64Value.php b/php/src/Google/Protobuf/Int64Value.php
index a6fb9c5d..ca663055 100644
--- a/php/src/Google/Protobuf/Int64Value.php
+++ b/php/src/Google/Protobuf/Int64Value.php
@@ -23,9 +23,19 @@ class Int64Value extends \Google\Protobuf\Internal\Message
*/
private $value = 0;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type int|string $value
+ * The int64 value.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Wrappers::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/Descriptor.php b/php/src/Google/Protobuf/Internal/Descriptor.php
index ee3a8bde..21ac5de3 100644
--- a/php/src/Google/Protobuf/Internal/Descriptor.php
+++ b/php/src/Google/Protobuf/Internal/Descriptor.php
@@ -44,6 +44,7 @@ class Descriptor
private $nested_type = [];
private $enum_type = [];
private $klass;
+ private $legacy_klass;
private $options;
private $oneof_decl = [];
@@ -151,6 +152,16 @@ class Descriptor
return $this->klass;
}
+ public function setLegacyClass($klass)
+ {
+ $this->legacy_klass = $klass;
+ }
+
+ public function getLegacyClass()
+ {
+ return $this->legacy_klass;
+ }
+
public function setOptions($options)
{
$this->options = $options;
@@ -167,16 +178,19 @@ class Descriptor
$message_name_without_package = "";
$classname = "";
+ $legacy_classname = "";
$fullname = "";
GPBUtil::getFullClassName(
$proto,
$containing,
$file_proto,
$message_name_without_package,
+ $legacy_classname,
$classname,
$fullname);
$desc->setFullName($fullname);
$desc->setClass($classname);
+ $desc->setLegacyClass($legacy_classname);
$desc->setOptions($proto->getOptions());
foreach ($proto->getField() as $field_proto) {
diff --git a/php/src/Google/Protobuf/Internal/DescriptorPool.php b/php/src/Google/Protobuf/Internal/DescriptorPool.php
index 304c1615..9b4dcc01 100644
--- a/php/src/Google/Protobuf/Internal/DescriptorPool.php
+++ b/php/src/Google/Protobuf/Internal/DescriptorPool.php
@@ -92,6 +92,7 @@ class DescriptorPool
$this->proto_to_class[$descriptor->getFullName()] =
$descriptor->getClass();
$this->class_to_desc[$descriptor->getClass()] = $descriptor;
+ $this->class_to_desc[$descriptor->getLegacyClass()] = $descriptor;
foreach ($descriptor->getNestedType() as $nested_type) {
$this->addDescriptor($nested_type);
}
@@ -105,6 +106,7 @@ class DescriptorPool
$this->proto_to_class[$descriptor->getFullName()] =
$descriptor->getClass();
$this->class_to_enum_desc[$descriptor->getClass()] = $descriptor;
+ $this->class_to_enum_desc[$descriptor->getLegacyClass()] = $descriptor;
}
public function getDescriptorByClassName($klass)
diff --git a/php/src/Google/Protobuf/Internal/DescriptorProto.php b/php/src/Google/Protobuf/Internal/DescriptorProto.php
index 1d6959b7..3b215d52 100644
--- a/php/src/Google/Protobuf/Internal/DescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/DescriptorProto.php
@@ -71,9 +71,29 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
private $reserved_name;
private $has_reserved_name = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name
+ * @type \Google\Protobuf\Internal\FieldDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $field
+ * @type \Google\Protobuf\Internal\FieldDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $extension
+ * @type \Google\Protobuf\Internal\DescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $nested_type
+ * @type \Google\Protobuf\Internal\EnumDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $enum_type
+ * @type \Google\Protobuf\Internal\DescriptorProto\ExtensionRange[]|\Google\Protobuf\Internal\RepeatedField $extension_range
+ * @type \Google\Protobuf\Internal\OneofDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $oneof_decl
+ * @type \Google\Protobuf\Internal\MessageOptions $options
+ * @type \Google\Protobuf\Internal\DescriptorProto\ReservedRange[]|\Google\Protobuf\Internal\RepeatedField $reserved_range
+ * @type string[]|\Google\Protobuf\Internal\RepeatedField $reserved_name
+ * Reserved field names, which may not be used by fields in the same message.
+ * A given name may only be reserved once.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
@@ -227,12 +247,12 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
/**
* Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;</code>
- * @param \Google\Protobuf\Internal\DescriptorProto_ExtensionRange[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @param \Google\Protobuf\Internal\DescriptorProto\ExtensionRange[]|\Google\Protobuf\Internal\RepeatedField $var
* @return $this
*/
public function setExtensionRange($var)
{
- $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto_ExtensionRange::class);
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto\ExtensionRange::class);
$this->extension_range = $arr;
$this->has_extension_range = true;
@@ -311,12 +331,12 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
/**
* Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;</code>
- * @param \Google\Protobuf\Internal\DescriptorProto_ReservedRange[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @param \Google\Protobuf\Internal\DescriptorProto\ReservedRange[]|\Google\Protobuf\Internal\RepeatedField $var
* @return $this
*/
public function setReservedRange($var)
{
- $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto_ReservedRange::class);
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto\ReservedRange::class);
$this->reserved_range = $arr;
$this->has_reserved_range = true;
diff --git a/php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php b/php/src/Google/Protobuf/Internal/DescriptorProto/ExtensionRange.php
index 1d455995..c06a0a6e 100644
--- a/php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php
+++ b/php/src/Google/Protobuf/Internal/DescriptorProto/ExtensionRange.php
@@ -2,7 +2,7 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-namespace Google\Protobuf\Internal;
+namespace Google\Protobuf\Internal\DescriptorProto;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
@@ -13,7 +13,7 @@ use Google\Protobuf\Internal\GPBUtil;
/**
* Generated from protobuf message <code>google.protobuf.DescriptorProto.ExtensionRange</code>
*/
-class DescriptorProto_ExtensionRange extends \Google\Protobuf\Internal\Message
+class ExtensionRange extends \Google\Protobuf\Internal\Message
{
/**
* Generated from protobuf field <code>optional int32 start = 1;</code>
@@ -31,9 +31,20 @@ class DescriptorProto_ExtensionRange extends \Google\Protobuf\Internal\Message
private $options = null;
private $has_options = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type int $start
+ * @type int $end
+ * @type \Google\Protobuf\Internal\ExtensionRangeOptions $options
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
@@ -122,3 +133,6 @@ class DescriptorProto_ExtensionRange extends \Google\Protobuf\Internal\Message
}
+// Adding a class alias for backwards compatibility with the previous class name.
+class_alias(ExtensionRange::class, \Google\Protobuf\Internal\DescriptorProto_ExtensionRange::class);
+
diff --git a/php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php b/php/src/Google/Protobuf/Internal/DescriptorProto/ReservedRange.php
index b1022d61..73c964fa 100644
--- a/php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php
+++ b/php/src/Google/Protobuf/Internal/DescriptorProto/ReservedRange.php
@@ -2,7 +2,7 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-namespace Google\Protobuf\Internal;
+namespace Google\Protobuf\Internal\DescriptorProto;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
@@ -17,7 +17,7 @@ use Google\Protobuf\Internal\GPBUtil;
*
* Generated from protobuf message <code>google.protobuf.DescriptorProto.ReservedRange</code>
*/
-class DescriptorProto_ReservedRange extends \Google\Protobuf\Internal\Message
+class ReservedRange extends \Google\Protobuf\Internal\Message
{
/**
* Inclusive.
@@ -34,9 +34,21 @@ class DescriptorProto_ReservedRange extends \Google\Protobuf\Internal\Message
private $end = 0;
private $has_end = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type int $start
+ * Inclusive.
+ * @type int $end
+ * Exclusive.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
@@ -105,3 +117,6 @@ class DescriptorProto_ReservedRange extends \Google\Protobuf\Internal\Message
}
+// Adding a class alias for backwards compatibility with the previous class name.
+class_alias(ReservedRange::class, \Google\Protobuf\Internal\DescriptorProto_ReservedRange::class);
+
diff --git a/php/src/Google/Protobuf/Internal/EnumDescriptor.php b/php/src/Google/Protobuf/Internal/EnumDescriptor.php
index 01649fec..82a42767 100644
--- a/php/src/Google/Protobuf/Internal/EnumDescriptor.php
+++ b/php/src/Google/Protobuf/Internal/EnumDescriptor.php
@@ -9,6 +9,7 @@ class EnumDescriptor
use HasPublicDescriptorTrait;
private $klass;
+ private $legacy_klass;
private $full_name;
private $value;
private $name_to_value;
@@ -66,12 +67,23 @@ class EnumDescriptor
return $this->klass;
}
+ public function setLegacyClass($klass)
+ {
+ $this->legacy_klass = $klass;
+ }
+
+ public function getLegacyClass()
+ {
+ return $this->legacy_klass;
+ }
+
public static function buildFromProto($proto, $file_proto, $containing)
{
$desc = new EnumDescriptor();
$enum_name_without_package = "";
$classname = "";
+ $legacy_classname = "";
$fullname = "";
GPBUtil::getFullClassName(
$proto,
@@ -79,9 +91,11 @@ class EnumDescriptor
$file_proto,
$enum_name_without_package,
$classname,
+ $legacy_classname,
$fullname);
$desc->setFullName($fullname);
$desc->setClass($classname);
+ $desc->setLegacyClass($legacy_classname);
$values = $proto->getValue();
foreach ($values as $value) {
$desc->addValue($value->getNumber(), $value);
diff --git a/php/src/Google/Protobuf/Internal/EnumDescriptorProto.php b/php/src/Google/Protobuf/Internal/EnumDescriptorProto.php
index 930f26ef..da30fa99 100644
--- a/php/src/Google/Protobuf/Internal/EnumDescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/EnumDescriptorProto.php
@@ -50,9 +50,27 @@ class EnumDescriptorProto extends \Google\Protobuf\Internal\Message
private $reserved_name;
private $has_reserved_name = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name
+ * @type \Google\Protobuf\Internal\EnumValueDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $value
+ * @type \Google\Protobuf\Internal\EnumOptions $options
+ * @type \Google\Protobuf\Internal\EnumDescriptorProto\EnumReservedRange[]|\Google\Protobuf\Internal\RepeatedField $reserved_range
+ * Range of reserved numeric values. Reserved numeric values may not be used
+ * by enum values in the same enum declaration. Reserved ranges may not
+ * overlap.
+ * @type string[]|\Google\Protobuf\Internal\RepeatedField $reserved_name
+ * Reserved enum value names, which may not be reused. A given name may only
+ * be reserved once.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
@@ -158,12 +176,12 @@ class EnumDescriptorProto extends \Google\Protobuf\Internal\Message
* overlap.
*
* Generated from protobuf field <code>repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;</code>
- * @param \Google\Protobuf\Internal\EnumDescriptorProto_EnumReservedRange[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @param \Google\Protobuf\Internal\EnumDescriptorProto\EnumReservedRange[]|\Google\Protobuf\Internal\RepeatedField $var
* @return $this
*/
public function setReservedRange($var)
{
- $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\EnumDescriptorProto_EnumReservedRange::class);
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\EnumDescriptorProto\EnumReservedRange::class);
$this->reserved_range = $arr;
$this->has_reserved_range = true;
diff --git a/php/src/Google/Protobuf/Internal/EnumDescriptorProto_EnumReservedRange.php b/php/src/Google/Protobuf/Internal/EnumDescriptorProto/EnumReservedRange.php
index 6b2449fa..e1079585 100644
--- a/php/src/Google/Protobuf/Internal/EnumDescriptorProto_EnumReservedRange.php
+++ b/php/src/Google/Protobuf/Internal/EnumDescriptorProto/EnumReservedRange.php
@@ -2,7 +2,7 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-namespace Google\Protobuf\Internal;
+namespace Google\Protobuf\Internal\EnumDescriptorProto;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
@@ -19,7 +19,7 @@ use Google\Protobuf\Internal\GPBUtil;
*
* Generated from protobuf message <code>google.protobuf.EnumDescriptorProto.EnumReservedRange</code>
*/
-class EnumDescriptorProto_EnumReservedRange extends \Google\Protobuf\Internal\Message
+class EnumReservedRange extends \Google\Protobuf\Internal\Message
{
/**
* Inclusive.
@@ -36,9 +36,21 @@ class EnumDescriptorProto_EnumReservedRange extends \Google\Protobuf\Internal\Me
private $end = 0;
private $has_end = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type int $start
+ * Inclusive.
+ * @type int $end
+ * Inclusive.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
@@ -107,3 +119,6 @@ class EnumDescriptorProto_EnumReservedRange extends \Google\Protobuf\Internal\Me
}
+// Adding a class alias for backwards compatibility with the previous class name.
+class_alias(EnumReservedRange::class, \Google\Protobuf\Internal\EnumDescriptorProto_EnumReservedRange::class);
+
diff --git a/php/src/Google/Protobuf/Internal/EnumOptions.php b/php/src/Google/Protobuf/Internal/EnumOptions.php
index 3f598a41..3d74c81c 100644
--- a/php/src/Google/Protobuf/Internal/EnumOptions.php
+++ b/php/src/Google/Protobuf/Internal/EnumOptions.php
@@ -41,9 +41,27 @@ class EnumOptions extends \Google\Protobuf\Internal\Message
private $uninterpreted_option;
private $has_uninterpreted_option = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type bool $allow_alias
+ * Set this option to true to allow mapping different tag names to the same
+ * value.
+ * @type bool $deprecated
+ * Is this enum deprecated?
+ * Depending on the target platform, this can emit Deprecated annotations
+ * for the enum, or it will be completely ignored; in the very least, this
+ * is a formalization for deprecating enums.
+ * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option
+ * The parser stores options it doesn't recognize here. See above.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php b/php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php
index e363220f..50bda008 100644
--- a/php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php
@@ -33,9 +33,20 @@ class EnumValueDescriptorProto extends \Google\Protobuf\Internal\Message
private $options = null;
private $has_options = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name
+ * @type int $number
+ * @type \Google\Protobuf\Internal\EnumValueOptions $options
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/EnumValueOptions.php b/php/src/Google/Protobuf/Internal/EnumValueOptions.php
index db8de174..a267c6d5 100644
--- a/php/src/Google/Protobuf/Internal/EnumValueOptions.php
+++ b/php/src/Google/Protobuf/Internal/EnumValueOptions.php
@@ -33,9 +33,24 @@ class EnumValueOptions extends \Google\Protobuf\Internal\Message
private $uninterpreted_option;
private $has_uninterpreted_option = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type bool $deprecated
+ * Is this enum value deprecated?
+ * Depending on the target platform, this can emit Deprecated annotations
+ * for the enum value, or it will be completely ignored; in the very least,
+ * this is a formalization for deprecating enum values.
+ * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option
+ * The parser stores options it doesn't recognize here. See above.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php b/php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php
index ee9e38bb..00fbebec 100644
--- a/php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php
+++ b/php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php
@@ -23,9 +23,19 @@ class ExtensionRangeOptions extends \Google\Protobuf\Internal\Message
private $uninterpreted_option;
private $has_uninterpreted_option = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option
+ * The parser stores options it doesn't recognize here. See above.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/FieldDescriptorProto.php b/php/src/Google/Protobuf/Internal/FieldDescriptorProto.php
index 10c27593..e5781975 100644
--- a/php/src/Google/Protobuf/Internal/FieldDescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/FieldDescriptorProto.php
@@ -94,9 +94,47 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
private $options = null;
private $has_options = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name
+ * @type int $number
+ * @type int $label
+ * @type int $type
+ * If type_name is set, this need not be set. If both this and type_name
+ * are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
+ * @type string $type_name
+ * For message and enum types, this is the name of the type. If the name
+ * starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
+ * rules are used to find the type (i.e. first the nested types within this
+ * message are searched, then within the parent, on up to the root
+ * namespace).
+ * @type string $extendee
+ * For extensions, this is the name of the type being extended. It is
+ * resolved in the same manner as type_name.
+ * @type string $default_value
+ * For numeric types, contains the original text representation of the value.
+ * For booleans, "true" or "false".
+ * For strings, contains the default text contents (not escaped in any way).
+ * For bytes, contains the C escaped value. All bytes >= 128 are escaped.
+ * TODO(kenton): Base-64 encode?
+ * @type int $oneof_index
+ * If set, gives the index of a oneof in the containing type's oneof_decl
+ * list. This field is a member of that oneof.
+ * @type string $json_name
+ * JSON name of this field. The value is set by protocol compiler. If the
+ * user has set a "json_name" option on this field, that option's value
+ * will be used. Otherwise, it's deduced from the field's name by converting
+ * it to camelCase.
+ * @type \Google\Protobuf\Internal\FieldOptions $options
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php b/php/src/Google/Protobuf/Internal/FieldDescriptorProto/Label.php
index f2a32fdf..b105088e 100644
--- a/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php
+++ b/php/src/Google/Protobuf/Internal/FieldDescriptorProto/Label.php
@@ -2,12 +2,12 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-namespace Google\Protobuf\Internal;
+namespace Google\Protobuf\Internal\FieldDescriptorProto;
/**
- * Protobuf enum <code>Google\Protobuf\Internal</code>
+ * Protobuf type <code>google.protobuf.FieldDescriptorProto.Label</code>
*/
-class FieldDescriptorProto_Label
+class Label
{
/**
* 0 is reserved for errors
@@ -25,3 +25,6 @@ class FieldDescriptorProto_Label
const LABEL_REPEATED = 3;
}
+// Adding a class alias for backwards compatibility with the previous class name.
+class_alias(Label::class, \Google\Protobuf\Internal\FieldDescriptorProto_Label::class);
+
diff --git a/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php b/php/src/Google/Protobuf/Internal/FieldDescriptorProto/Type.php
index 1b022deb..ea228a77 100644
--- a/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php
+++ b/php/src/Google/Protobuf/Internal/FieldDescriptorProto/Type.php
@@ -2,12 +2,12 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-namespace Google\Protobuf\Internal;
+namespace Google\Protobuf\Internal\FieldDescriptorProto;
/**
- * Protobuf enum <code>Google\Protobuf\Internal</code>
+ * Protobuf type <code>google.protobuf.FieldDescriptorProto.Type</code>
*/
-class FieldDescriptorProto_Type
+class Type
{
/**
* 0 is reserved for errors.
@@ -105,3 +105,6 @@ class FieldDescriptorProto_Type
const TYPE_SINT64 = 18;
}
+// Adding a class alias for backwards compatibility with the previous class name.
+class_alias(Type::class, \Google\Protobuf\Internal\FieldDescriptorProto_Type::class);
+
diff --git a/php/src/Google/Protobuf/Internal/FieldOptions.php b/php/src/Google/Protobuf/Internal/FieldOptions.php
index 169f860b..751c278d 100644
--- a/php/src/Google/Protobuf/Internal/FieldOptions.php
+++ b/php/src/Google/Protobuf/Internal/FieldOptions.php
@@ -107,9 +107,73 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
private $uninterpreted_option;
private $has_uninterpreted_option = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type int $ctype
+ * The ctype option instructs the C++ code generator to use a different
+ * representation of the field than it normally would. See the specific
+ * options below. This option is not yet implemented in the open source
+ * release -- sorry, we'll try to include it in a future version!
+ * @type bool $packed
+ * The packed option can be enabled for repeated primitive fields to enable
+ * a more efficient representation on the wire. Rather than repeatedly
+ * writing the tag and type for each element, the entire array is encoded as
+ * a single length-delimited blob. In proto3, only explicit setting it to
+ * false will avoid using packed encoding.
+ * @type int $jstype
+ * The jstype option determines the JavaScript type used for values of the
+ * field. The option is permitted only for 64 bit integral and fixed types
+ * (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
+ * is represented as JavaScript string, which avoids loss of precision that
+ * can happen when a large value is converted to a floating point JavaScript.
+ * Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
+ * use the JavaScript "number" type. The behavior of the default option
+ * JS_NORMAL is implementation dependent.
+ * This option is an enum to permit additional types to be added, e.g.
+ * goog.math.Integer.
+ * @type bool $lazy
+ * Should this field be parsed lazily? Lazy applies only to message-type
+ * fields. It means that when the outer message is initially parsed, the
+ * inner message's contents will not be parsed but instead stored in encoded
+ * form. The inner message will actually be parsed when it is first accessed.
+ * This is only a hint. Implementations are free to choose whether to use
+ * eager or lazy parsing regardless of the value of this option. However,
+ * setting this option true suggests that the protocol author believes that
+ * using lazy parsing on this field is worth the additional bookkeeping
+ * overhead typically needed to implement it.
+ * This option does not affect the public interface of any generated code;
+ * all method signatures remain the same. Furthermore, thread-safety of the
+ * interface is not affected by this option; const methods remain safe to
+ * call from multiple threads concurrently, while non-const methods continue
+ * to require exclusive access.
+ * Note that implementations may choose not to check required fields within
+ * a lazy sub-message. That is, calling IsInitialized() on the outer message
+ * may return true even if the inner message has missing required fields.
+ * This is necessary because otherwise the inner message would have to be
+ * parsed in order to perform the check, defeating the purpose of lazy
+ * parsing. An implementation which chooses not to check required fields
+ * must be consistent about it. That is, for any particular sub-message, the
+ * implementation must either *always* check its required fields, or *never*
+ * check its required fields, regardless of whether or not the message has
+ * been parsed.
+ * @type bool $deprecated
+ * Is this field deprecated?
+ * Depending on the target platform, this can emit Deprecated annotations
+ * for accessors, or it will be completely ignored; in the very least, this
+ * is a formalization for deprecating fields.
+ * @type bool $weak
+ * For Google-internal migration only. Do not use.
+ * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option
+ * The parser stores options it doesn't recognize here. See above.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/FieldOptions_CType.php b/php/src/Google/Protobuf/Internal/FieldOptions/CType.php
index 0f33072d..016197ac 100644
--- a/php/src/Google/Protobuf/Internal/FieldOptions_CType.php
+++ b/php/src/Google/Protobuf/Internal/FieldOptions/CType.php
@@ -2,12 +2,12 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-namespace Google\Protobuf\Internal;
+namespace Google\Protobuf\Internal\FieldOptions;
/**
- * Protobuf enum <code>Google\Protobuf\Internal</code>
+ * Protobuf type <code>google.protobuf.FieldOptions.CType</code>
*/
-class FieldOptions_CType
+class CType
{
/**
* Default mode.
@@ -25,3 +25,6 @@ class FieldOptions_CType
const STRING_PIECE = 2;
}
+// Adding a class alias for backwards compatibility with the previous class name.
+class_alias(CType::class, \Google\Protobuf\Internal\FieldOptions_CType::class);
+
diff --git a/php/src/Google/Protobuf/Internal/FieldOptions_JSType.php b/php/src/Google/Protobuf/Internal/FieldOptions/JSType.php
index 73bdf3f2..f7b78a1b 100644
--- a/php/src/Google/Protobuf/Internal/FieldOptions_JSType.php
+++ b/php/src/Google/Protobuf/Internal/FieldOptions/JSType.php
@@ -2,12 +2,12 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-namespace Google\Protobuf\Internal;
+namespace Google\Protobuf\Internal\FieldOptions;
/**
- * Protobuf enum <code>Google\Protobuf\Internal</code>
+ * Protobuf type <code>google.protobuf.FieldOptions.JSType</code>
*/
-class FieldOptions_JSType
+class JSType
{
/**
* Use the default type.
@@ -29,3 +29,6 @@ class FieldOptions_JSType
const JS_NUMBER = 2;
}
+// Adding a class alias for backwards compatibility with the previous class name.
+class_alias(JSType::class, \Google\Protobuf\Internal\FieldOptions_JSType::class);
+
diff --git a/php/src/Google/Protobuf/Internal/FileDescriptorProto.php b/php/src/Google/Protobuf/Internal/FileDescriptorProto.php
index 9ee222d1..cb10aa79 100644
--- a/php/src/Google/Protobuf/Internal/FileDescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/FileDescriptorProto.php
@@ -99,9 +99,42 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
private $syntax = '';
private $has_syntax = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name
+ * file name, relative to root of source tree
+ * @type string $package
+ * e.g. "foo", "foo.bar", etc.
+ * @type string[]|\Google\Protobuf\Internal\RepeatedField $dependency
+ * Names of files imported by this file.
+ * @type int[]|\Google\Protobuf\Internal\RepeatedField $public_dependency
+ * Indexes of the public imported files in the dependency list above.
+ * @type int[]|\Google\Protobuf\Internal\RepeatedField $weak_dependency
+ * Indexes of the weak imported files in the dependency list.
+ * For Google-internal migration only. Do not use.
+ * @type \Google\Protobuf\Internal\DescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $message_type
+ * All top-level definitions in this file.
+ * @type \Google\Protobuf\Internal\EnumDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $enum_type
+ * @type \Google\Protobuf\Internal\ServiceDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $service
+ * @type \Google\Protobuf\Internal\FieldDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $extension
+ * @type \Google\Protobuf\Internal\FileOptions $options
+ * @type \Google\Protobuf\Internal\SourceCodeInfo $source_code_info
+ * This field contains optional information about the original source code.
+ * You may safely remove this entire field without harming runtime
+ * functionality of the descriptors -- the information is needed only by
+ * development tools.
+ * @type string $syntax
+ * The syntax of the proto file.
+ * The supported values are "proto2" and "proto3".
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/FileDescriptorSet.php b/php/src/Google/Protobuf/Internal/FileDescriptorSet.php
index 0b2cf957..9907b17d 100644
--- a/php/src/Google/Protobuf/Internal/FileDescriptorSet.php
+++ b/php/src/Google/Protobuf/Internal/FileDescriptorSet.php
@@ -24,9 +24,18 @@ class FileDescriptorSet extends \Google\Protobuf\Internal\Message
private $file;
private $has_file = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type \Google\Protobuf\Internal\FileDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $file
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/FileOptions.php b/php/src/Google/Protobuf/Internal/FileOptions.php
index f3bacad6..c6b36bbc 100644
--- a/php/src/Google/Protobuf/Internal/FileOptions.php
+++ b/php/src/Google/Protobuf/Internal/FileOptions.php
@@ -174,6 +174,24 @@ class FileOptions extends \Google\Protobuf\Internal\Message
private $php_namespace = '';
private $has_php_namespace = false;
/**
+ * Use this option to change the namespace of php generated metadata classes.
+ * Default is empty. When this option is empty, the proto file name will be used
+ * for determining the namespace.
+ *
+ * Generated from protobuf field <code>optional string php_metadata_namespace = 44;</code>
+ */
+ private $php_metadata_namespace = '';
+ private $has_php_metadata_namespace = false;
+ /**
+ * Use this option to change the package of ruby generated classes. Default
+ * is empty. When this option is not set, the package name will be used for
+ * determining the ruby package.
+ *
+ * Generated from protobuf field <code>optional string ruby_package = 45;</code>
+ */
+ private $ruby_package = '';
+ private $has_ruby_package = false;
+ /**
* The parser stores options it doesn't recognize here.
* See the documentation for the "Options" section above.
*
@@ -182,9 +200,100 @@ class FileOptions extends \Google\Protobuf\Internal\Message
private $uninterpreted_option;
private $has_uninterpreted_option = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $java_package
+ * Sets the Java package where classes generated from this .proto will be
+ * placed. By default, the proto package is used, but this is often
+ * inappropriate because proto packages do not normally start with backwards
+ * domain names.
+ * @type string $java_outer_classname
+ * If set, all the classes from the .proto file are wrapped in a single
+ * outer class with the given name. This applies to both Proto1
+ * (equivalent to the old "--one_java_file" option) and Proto2 (where
+ * a .proto always translates to a single class, but you may want to
+ * explicitly choose the class name).
+ * @type bool $java_multiple_files
+ * If set true, then the Java code generator will generate a separate .java
+ * file for each top-level message, enum, and service defined in the .proto
+ * file. Thus, these types will *not* be nested inside the outer class
+ * named by java_outer_classname. However, the outer class will still be
+ * generated to contain the file's getDescriptor() method as well as any
+ * top-level extensions defined in the file.
+ * @type bool $java_generate_equals_and_hash
+ * This option does nothing.
+ * @type bool $java_string_check_utf8
+ * If set true, then the Java2 code generator will generate code that
+ * throws an exception whenever an attempt is made to assign a non-UTF-8
+ * byte sequence to a string field.
+ * Message reflection will do the same.
+ * However, an extension field still accepts non-UTF-8 byte sequences.
+ * This option has no effect on when used with the lite runtime.
+ * @type int $optimize_for
+ * @type string $go_package
+ * Sets the Go package where structs generated from this .proto will be
+ * placed. If omitted, the Go package will be derived from the following:
+ * - The basename of the package import path, if provided.
+ * - Otherwise, the package statement in the .proto file, if present.
+ * - Otherwise, the basename of the .proto file, without extension.
+ * @type bool $cc_generic_services
+ * Should generic services be generated in each language? "Generic" services
+ * are not specific to any particular RPC system. They are generated by the
+ * main code generators in each language (without additional plugins).
+ * Generic services were the only kind of service generation supported by
+ * early versions of google.protobuf.
+ * Generic services are now considered deprecated in favor of using plugins
+ * that generate code specific to your particular RPC system. Therefore,
+ * these default to false. Old code which depends on generic services should
+ * explicitly set them to true.
+ * @type bool $java_generic_services
+ * @type bool $py_generic_services
+ * @type bool $php_generic_services
+ * @type bool $deprecated
+ * Is this file deprecated?
+ * Depending on the target platform, this can emit Deprecated annotations
+ * for everything in the file, or it will be completely ignored; in the very
+ * least, this is a formalization for deprecating files.
+ * @type bool $cc_enable_arenas
+ * Enables the use of arenas for the proto messages in this file. This applies
+ * only to generated classes for C++.
+ * @type string $objc_class_prefix
+ * Sets the objective c class prefix which is prepended to all objective c
+ * generated classes from this .proto. There is no default.
+ * @type string $csharp_namespace
+ * Namespace for generated classes; defaults to the package.
+ * @type string $swift_prefix
+ * By default Swift generators will take the proto package and CamelCase it
+ * replacing '.' with underscore and use that to prefix the types/symbols
+ * defined. When this options is provided, they will use this value instead
+ * to prefix the types/symbols defined.
+ * @type string $php_class_prefix
+ * Sets the php class prefix which is prepended to all php generated classes
+ * from this .proto. Default is empty.
+ * @type string $php_namespace
+ * Use this option to change the namespace of php generated classes. Default
+ * is empty. When this option is empty, the package name will be used for
+ * determining the namespace.
+ * @type string $php_metadata_namespace
+ * Use this option to change the namespace of php generated metadata classes.
+ * Default is empty. When this option is empty, the proto file name will be used
+ * for determining the namespace.
+ * @type string $ruby_package
+ * Use this option to change the package of ruby generated classes. Default
+ * is empty. When this option is not set, the package name will be used for
+ * determining the ruby package.
+ * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option
+ * The parser stores options it doesn't recognize here.
+ * See the documentation for the "Options" section above.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
@@ -828,6 +937,78 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
+ * Use this option to change the namespace of php generated metadata classes.
+ * Default is empty. When this option is empty, the proto file name will be used
+ * for determining the namespace.
+ *
+ * Generated from protobuf field <code>optional string php_metadata_namespace = 44;</code>
+ * @return string
+ */
+ public function getPhpMetadataNamespace()
+ {
+ return $this->php_metadata_namespace;
+ }
+
+ /**
+ * Use this option to change the namespace of php generated metadata classes.
+ * Default is empty. When this option is empty, the proto file name will be used
+ * for determining the namespace.
+ *
+ * Generated from protobuf field <code>optional string php_metadata_namespace = 44;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setPhpMetadataNamespace($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->php_metadata_namespace = $var;
+ $this->has_php_metadata_namespace = true;
+
+ return $this;
+ }
+
+ public function hasPhpMetadataNamespace()
+ {
+ return $this->has_php_metadata_namespace;
+ }
+
+ /**
+ * Use this option to change the package of ruby generated classes. Default
+ * is empty. When this option is not set, the package name will be used for
+ * determining the ruby package.
+ *
+ * Generated from protobuf field <code>optional string ruby_package = 45;</code>
+ * @return string
+ */
+ public function getRubyPackage()
+ {
+ return $this->ruby_package;
+ }
+
+ /**
+ * Use this option to change the package of ruby generated classes. Default
+ * is empty. When this option is not set, the package name will be used for
+ * determining the ruby package.
+ *
+ * Generated from protobuf field <code>optional string ruby_package = 45;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setRubyPackage($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->ruby_package = $var;
+ $this->has_ruby_package = true;
+
+ return $this;
+ }
+
+ public function hasRubyPackage()
+ {
+ return $this->has_ruby_package;
+ }
+
+ /**
* The parser stores options it doesn't recognize here.
* See the documentation for the "Options" section above.
*
diff --git a/php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php b/php/src/Google/Protobuf/Internal/FileOptions/OptimizeMode.php
index 4dd56ef8..3dd60bf6 100644
--- a/php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php
+++ b/php/src/Google/Protobuf/Internal/FileOptions/OptimizeMode.php
@@ -2,14 +2,14 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-namespace Google\Protobuf\Internal;
+namespace Google\Protobuf\Internal\FileOptions;
/**
* Generated classes can be optimized for speed or code size.
*
- * Protobuf enum <code>Google\Protobuf\Internal</code>
+ * Protobuf type <code>google.protobuf.FileOptions.OptimizeMode</code>
*/
-class FileOptions_OptimizeMode
+class OptimizeMode
{
/**
* Generate complete code for parsing, serialization,
@@ -31,3 +31,6 @@ class FileOptions_OptimizeMode
const LITE_RUNTIME = 3;
}
+// Adding a class alias for backwards compatibility with the previous class name.
+class_alias(OptimizeMode::class, \Google\Protobuf\Internal\FileOptions_OptimizeMode::class);
+
diff --git a/php/src/Google/Protobuf/Internal/GPBUtil.php b/php/src/Google/Protobuf/Internal/GPBUtil.php
index 76f84cbd..b75d9bab 100644
--- a/php/src/Google/Protobuf/Internal/GPBUtil.php
+++ b/php/src/Google/Protobuf/Internal/GPBUtil.php
@@ -191,10 +191,10 @@ class GPBUtil
$var = boolval($var);
}
- public static function checkMessage(&$var, $klass)
+ public static function checkMessage(&$var, $klass, $newClass = null)
{
if (!$var instanceof $klass && !is_null($var)) {
- throw new \Exception("Expect message.");
+ throw new \Exception("Expect $klass.");
}
}
@@ -215,9 +215,10 @@ class GPBUtil
"Expect repeated field of different type.");
}
if ($var->getType() === GPBType::MESSAGE &&
- $var->getClass() !== $klass) {
+ $var->getClass() !== $klass &&
+ $var->getLegacyClass() !== $klass) {
throw new \Exception(
- "Expect repeated field of different message.");
+ "Expect repeated field of " . $klass . ".");
}
return $var;
}
@@ -242,9 +243,10 @@ class GPBUtil
throw new \Exception("Expect map field of value type.");
}
if ($var->getValueType() === GPBType::MESSAGE &&
- $var->getValueClass() !== $klass) {
+ $var->getValueClass() !== $klass &&
+ $var->getLegacyValueClass() !== $klass) {
throw new \Exception(
- "Expect map field of different value message.");
+ "Expect map field of " . $klass . ".");
}
return $var;
}
@@ -299,12 +301,26 @@ class GPBUtil
return "";
}
+ public static function getLegacyClassNameWithoutPackage(
+ $name,
+ $file_proto)
+ {
+ $parts = explode('.', $name);
+ foreach ($parts as $i => $part) {
+ $parts[$i] = static::getClassNamePrefix($parts[$i], $file_proto) . $parts[$i];
+ }
+ return implode('\\', $parts);
+ }
+
public static function getClassNameWithoutPackage(
$name,
$file_proto)
{
- $classname = implode('_', explode('.', $name));
- return static::getClassNamePrefix($classname, $file_proto) . $classname;
+ $parts = explode('.', $name);
+ foreach ($parts as $i => $part) {
+ $parts[$i] = static::getClassNamePrefix($parts[$i], $file_proto) . $parts[$i];
+ }
+ return implode('\\', $parts);
}
public static function getFullClassName(
@@ -313,6 +329,7 @@ class GPBUtil
$file_proto,
&$message_name_without_package,
&$classname,
+ &$legacy_classname,
&$fullname)
{
// Full name needs to start with '.'.
@@ -331,25 +348,40 @@ class GPBUtil
$class_name_without_package =
static::getClassNameWithoutPackage($message_name_without_package, $file_proto);
+ $legacy_class_name_without_package =
+ static::getLegacyClassNameWithoutPackage(
+ $message_name_without_package, $file_proto);
$option = $file_proto->getOptions();
if (!is_null($option) && $option->hasPhpNamespace()) {
$namespace = $option->getPhpNamespace();
if ($namespace !== "") {
$classname = $namespace . "\\" . $class_name_without_package;
+ $legacy_classname =
+ $namespace . "\\" . $legacy_class_name_without_package;
return;
} else {
$classname = $class_name_without_package;
+ $legacy_classname = $legacy_class_name_without_package;
return;
}
}
if ($package === "") {
$classname = $class_name_without_package;
+ $legacy_classname = $legacy_class_name_without_package;
} else {
+ $parts = array_map('ucwords', explode('.', $package));
+ foreach ($parts as $i => $part) {
+ $parts[$i] = self::getClassNamePrefix($part, $file_proto).$part;
+ }
$classname =
+ implode('\\', $parts) .
+ "\\".self::getClassNamePrefix($class_name_without_package,$file_proto).
+ $class_name_without_package;
+ $legacy_classname =
implode('\\', array_map('ucwords', explode('.', $package))).
- "\\".$class_name_without_package;
+ "\\".$legacy_class_name_without_package;
}
}
diff --git a/php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php b/php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php
index ae2ad745..f5a65bea 100644
--- a/php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php
+++ b/php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php
@@ -28,9 +28,20 @@ class GeneratedCodeInfo extends \Google\Protobuf\Internal\Message
private $annotation;
private $has_annotation = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type \Google\Protobuf\Internal\GeneratedCodeInfo\Annotation[]|\Google\Protobuf\Internal\RepeatedField $annotation
+ * An Annotation connects some span of text in generated code to an element
+ * of its generating .proto file.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
@@ -50,12 +61,12 @@ class GeneratedCodeInfo extends \Google\Protobuf\Internal\Message
* of its generating .proto file.
*
* Generated from protobuf field <code>repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;</code>
- * @param \Google\Protobuf\Internal\GeneratedCodeInfo_Annotation[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @param \Google\Protobuf\Internal\GeneratedCodeInfo\Annotation[]|\Google\Protobuf\Internal\RepeatedField $var
* @return $this
*/
public function setAnnotation($var)
{
- $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\GeneratedCodeInfo_Annotation::class);
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\GeneratedCodeInfo\Annotation::class);
$this->annotation = $arr;
$this->has_annotation = true;
diff --git a/php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php b/php/src/Google/Protobuf/Internal/GeneratedCodeInfo/Annotation.php
index 22ac2337..09f958d2 100644
--- a/php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php
+++ b/php/src/Google/Protobuf/Internal/GeneratedCodeInfo/Annotation.php
@@ -2,7 +2,7 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-namespace Google\Protobuf\Internal;
+namespace Google\Protobuf\Internal\GeneratedCodeInfo;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
@@ -13,7 +13,7 @@ use Google\Protobuf\Internal\GPBUtil;
/**
* Generated from protobuf message <code>google.protobuf.GeneratedCodeInfo.Annotation</code>
*/
-class GeneratedCodeInfo_Annotation extends \Google\Protobuf\Internal\Message
+class Annotation extends \Google\Protobuf\Internal\Message
{
/**
* Identifies the element in the original source .proto file. This field
@@ -48,9 +48,29 @@ class GeneratedCodeInfo_Annotation extends \Google\Protobuf\Internal\Message
private $end = 0;
private $has_end = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type int[]|\Google\Protobuf\Internal\RepeatedField $path
+ * Identifies the element in the original source .proto file. This field
+ * is formatted the same as SourceCodeInfo.Location.path.
+ * @type string $source_file
+ * Identifies the filesystem path to the original source .proto.
+ * @type int $begin
+ * Identifies the starting offset in bytes in the generated code
+ * that relates to the identified object.
+ * @type int $end
+ * Identifies the ending offset in bytes in the generated code that
+ * relates to the identified offset. The end offset should be one past
+ * the last relevant byte (so the length of the text = end - begin).
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
@@ -191,3 +211,6 @@ class GeneratedCodeInfo_Annotation extends \Google\Protobuf\Internal\Message
}
+// Adding a class alias for backwards compatibility with the previous class name.
+class_alias(Annotation::class, \Google\Protobuf\Internal\GeneratedCodeInfo_Annotation::class);
+
diff --git a/php/src/Google/Protobuf/Internal/MapField.php b/php/src/Google/Protobuf/Internal/MapField.php
index 38736dad..f7d7b710 100644
--- a/php/src/Google/Protobuf/Internal/MapField.php
+++ b/php/src/Google/Protobuf/Internal/MapField.php
@@ -58,7 +58,11 @@ class MapField implements \ArrayAccess, \IteratorAggregate, \Countable
/**
* @ignore
*/
- private $value_klass;
+ private $klass;
+ /**
+ * @ignore
+ */
+ private $legacy_klass;
/**
* Constructs an instance of MapField.
@@ -75,6 +79,17 @@ class MapField implements \ArrayAccess, \IteratorAggregate, \Countable
$this->key_type = $key_type;
$this->value_type = $value_type;
$this->klass = $klass;
+
+ if ($this->value_type == GPBType::MESSAGE) {
+ $pool = DescriptorPool::getGeneratedPool();
+ $desc = $pool->getDescriptorByClassName($klass);
+ if ($desc == NULL) {
+ new $klass; // No msg class instance has been created before.
+ $desc = $pool->getDescriptorByClassName($klass);
+ }
+ $this->klass = $desc->getClass();
+ $this->legacy_klass = $desc->getLegacyClass();
+ }
}
/**
@@ -102,6 +117,14 @@ class MapField implements \ArrayAccess, \IteratorAggregate, \Countable
}
/**
+ * @ignore
+ */
+ public function getLegacyValueClass()
+ {
+ return $this->legacy_klass;
+ }
+
+ /**
* Return the element at the given key.
*
* This will also be called for: $ele = $arr[$key]
diff --git a/php/src/Google/Protobuf/Internal/Message.php b/php/src/Google/Protobuf/Internal/Message.php
index b7f83c57..73ac375e 100644
--- a/php/src/Google/Protobuf/Internal/Message.php
+++ b/php/src/Google/Protobuf/Internal/Message.php
@@ -66,23 +66,34 @@ class Message
/**
* @ignore
*/
- public function __construct($desc = NULL)
+ public function __construct($data = NULL)
{
// MapEntry message is shared by all types of map fields, whose
// descriptors are different from each other. Thus, we cannot find a
// specific descriptor from the descriptor pool.
- if (get_class($this) === 'Google\Protobuf\Internal\MapEntry') {
- $this->desc = $desc;
- foreach ($desc->getField() as $field) {
- $setter = $field->getSetter();
- $this->$setter($this->defaultValue($field));
+ if ($this instanceof MapEntry) {
+ $this->initWithDescriptor($data);
+ } else {
+ $this->initWithGeneratedPool();
+ if (is_array($data)) {
+ $this->mergeFromArray($data);
+ } else if (!empty($data)) {
+ throw new \InvalidArgumentException(
+ 'Message constructor must be an array or null.'
+ );
}
- return;
}
+ }
+
+ /**
+ * @ignore
+ */
+ private function initWithGeneratedPool()
+ {
$pool = DescriptorPool::getGeneratedPool();
$this->desc = $pool->getDescriptorByClassName(get_class($this));
if (is_null($this->desc)) {
- user_error(get_class($this) . "is not found in descriptor pool.");
+ user_error(get_class($this) . " is not found in descriptor pool.");
}
foreach ($this->desc->getField() as $field) {
$setter = $field->getSetter();
@@ -151,6 +162,19 @@ class Message
}
}
+ /**
+ * @ignore
+ */
+ private function initWithDescriptor(Descriptor $desc)
+ {
+ $this->desc = $desc;
+ foreach ($desc->getField() as $field) {
+ $setter = $field->getSetter();
+ $defaultValue = $this->defaultValue($field);
+ $this->$setter($defaultValue);
+ }
+ }
+
protected function readOneof($number)
{
$field = $this->desc->getFieldByNumber($number);
@@ -628,58 +652,58 @@ class Message
*/
public function mergeFrom($msg)
{
- if (get_class($this) !== get_class($msg)) {
- user_error("Cannot merge messages with different class.");
- return;
- }
-
- foreach ($this->desc->getField() as $field) {
- $setter = $field->getSetter();
- $getter = $field->getGetter();
- if ($field->isMap()) {
- if (count($msg->$getter()) != 0) {
- $value_field = $field->getMessageType()->getFieldByNumber(2);
- foreach ($msg->$getter() as $key => $value) {
- if ($value_field->getType() == GPBType::MESSAGE) {
- $klass = $value_field->getMessageType()->getClass();
- $copy = new $klass;
- $copy->mergeFrom($value);
-
- $this->kvUpdateHelper($field, $key, $copy);
- } else {
- $this->kvUpdateHelper($field, $key, $value);
- }
- }
- }
- } else if ($field->getLabel() === GPBLabel::REPEATED) {
- if (count($msg->$getter()) != 0) {
- foreach ($msg->$getter() as $tmp) {
- if ($field->getType() == GPBType::MESSAGE) {
- $klass = $field->getMessageType()->getClass();
- $copy = new $klass;
- $copy->mergeFrom($tmp);
- $this->appendHelper($field, $copy);
- } else {
- $this->appendHelper($field, $tmp);
- }
- }
- }
- } else if ($field->getLabel() === GPBLabel::OPTIONAL) {
- if($msg->$getter() !== $this->defaultValue($field)) {
- $tmp = $msg->$getter();
- if ($field->getType() == GPBType::MESSAGE) {
- if (is_null($this->$getter())) {
- $klass = $field->getMessageType()->getClass();
- $new_msg = new $klass;
- $this->$setter($new_msg);
- }
- $this->$getter()->mergeFrom($tmp);
- } else {
- $this->$setter($tmp);
- }
- }
- }
- }
+ if (get_class($this) !== get_class($msg)) {
+ user_error("Cannot merge messages with different class.");
+ return;
+ }
+
+ foreach ($this->desc->getField() as $field) {
+ $setter = $field->getSetter();
+ $getter = $field->getGetter();
+ if ($field->isMap()) {
+ if (count($msg->$getter()) != 0) {
+ $value_field = $field->getMessageType()->getFieldByNumber(2);
+ foreach ($msg->$getter() as $key => $value) {
+ if ($value_field->getType() == GPBType::MESSAGE) {
+ $klass = $value_field->getMessageType()->getClass();
+ $copy = new $klass;
+ $copy->mergeFrom($value);
+
+ $this->kvUpdateHelper($field, $key, $copy);
+ } else {
+ $this->kvUpdateHelper($field, $key, $value);
+ }
+ }
+ }
+ } else if ($field->getLabel() === GPBLabel::REPEATED) {
+ if (count($msg->$getter()) != 0) {
+ foreach ($msg->$getter() as $tmp) {
+ if ($field->getType() == GPBType::MESSAGE) {
+ $klass = $field->getMessageType()->getClass();
+ $copy = new $klass;
+ $copy->mergeFrom($tmp);
+ $this->appendHelper($field, $copy);
+ } else {
+ $this->appendHelper($field, $tmp);
+ }
+ }
+ }
+ } else if ($field->getLabel() === GPBLabel::OPTIONAL) {
+ if($msg->$getter() !== $this->defaultValue($field)) {
+ $tmp = $msg->$getter();
+ if ($field->getType() == GPBType::MESSAGE) {
+ if (is_null($this->$getter())) {
+ $klass = $field->getMessageType()->getClass();
+ $new_msg = new $klass;
+ $this->$setter($new_msg);
+ }
+ $this->$getter()->mergeFrom($tmp);
+ } else {
+ $this->$setter($tmp);
+ }
+ }
+ }
+ }
}
/**
@@ -763,7 +787,8 @@ class Message
try {
$timestamp = GPBUtil::parseTimestamp($value);
} catch (\Exception $e) {
- throw new GPBDecodeException("Invalid RFC 3339 timestamp: ".$e->getMessage());
+ throw new GPBDecodeException(
+ "Invalid RFC 3339 timestamp: ".$e->getMessage());
}
$submsg->setSeconds($timestamp->getSeconds());
@@ -775,7 +800,8 @@ class Message
try {
return GPBUtil::parseFieldMask($value);
} catch (\Exception $e) {
- throw new GPBDecodeException("Invalid FieldMask: ".$e->getMessage());
+ throw new GPBDecodeException(
+ "Invalid FieldMask: ".$e->getMessage());
}
} else {
if (is_null($value) &&
@@ -792,21 +818,23 @@ class Message
case GPBType::ENUM:
if (is_null($value)) {
return $this->defaultValue($field);
- } else if (is_integer($value)) {
+ }
+ if (is_integer($value)) {
return $value;
- } else {
- $enum_value =
- $field->getEnumType()->getValueByName($value);
}
+ $enum_value = $field->getEnumType()->getValueByName($value);
if (!is_null($enum_value)) {
return $enum_value->getNumber();
}
+ throw new GPBDecodeException(
+ "Enum field only accepts integer or enum value name");
case GPBType::STRING:
if (is_null($value)) {
return $this->defaultValue($field);
}
if (!is_string($value)) {
- throw new GPBDecodeException("Expect string");
+ throw new GPBDecodeException(
+ "String field only accepts string value");
}
return $value;
case GPBType::BYTES:
@@ -814,12 +842,12 @@ class Message
return $this->defaultValue($field);
}
if (!is_string($value)) {
- throw new GPBDecodeException("Expect string");
+ throw new GPBDecodeException(
+ "Byte field only accepts string value");
}
$proto_value = base64_decode($value, true);
if ($proto_value === false) {
- throw new GPBDecodeException(
- "Invalid base64 characters");
+ throw new GPBDecodeException("Invalid base64 characters");
}
return $proto_value;
case GPBType::BOOL:
@@ -834,27 +862,14 @@ class Message
return false;
}
throw new GPBDecodeException(
- "Bool field only accept bool value");
+ "Bool field only accepts bool value");
}
if (!is_bool($value)) {
throw new GPBDecodeException(
- "Bool field only accept bool value");
+ "Bool field only accepts bool value");
}
return $value;
case GPBType::FLOAT:
- if (is_null($value)) {
- return $this->defaultValue($field);
- }
- if ($value === "Infinity") {
- return INF;
- }
- if ($value === "-Infinity") {
- return -INF;
- }
- if ($value === "NaN") {
- return NAN;
- }
- return $value;
case GPBType::DOUBLE:
if (is_null($value)) {
return $this->defaultValue($field);
@@ -943,6 +958,39 @@ class Message
}
}
+ /**
+ * Populates the message from a user-supplied PHP array. Array keys
+ * correspond to Message properties and nested message properties.
+ *
+ * Example:
+ * ```
+ * $message->mergeFromArray([
+ * 'name' => 'This is a message name',
+ * 'interval' => [
+ * 'startTime' => time() - 60,
+ * 'endTime' => time(),
+ * ]
+ * ]);
+ * ```
+ *
+ * @param array $array An array containing message properties and values.
+ * @return null.
+ * @throws Exception Invalid data.
+ */
+ protected function mergeFromArray(array $array)
+ {
+ // Just call the setters for the field names
+ foreach ($array as $key => $value) {
+ $field = $this->desc->getFieldByName($key);
+ if (is_null($field)) {
+ throw new \UnexpectedValueException(
+ 'Invalid message property: ' . $key);
+ }
+ $setter = $field->getSetter();
+ $this->$setter($value);
+ }
+ }
+
protected function mergeFromJsonArray($array)
{
if (is_a($this, "Google\Protobuf\Any")) {
@@ -1035,6 +1083,11 @@ class Message
}
return;
}
+ $this->mergeFromArrayJsonImpl($array);
+ }
+
+ private function mergeFromArrayJsonImpl($array)
+ {
foreach ($array as $key => $value) {
$field = $this->desc->getFieldByJsonName($key);
if (is_null($field)) {
@@ -1043,7 +1096,6 @@ class Message
continue;
}
}
- $setter = $field->getSetter();
if ($field->isMap()) {
if (is_null($value)) {
continue;
@@ -1055,15 +1107,13 @@ class Message
throw new \Exception(
"Map value field element cannot be null.");
}
- $proto_key =
- $this->convertJsonValueToProtoValue(
- $tmp_key,
- $key_field,
- true);
- $proto_value =
- $this->convertJsonValueToProtoValue(
- $tmp_value,
- $value_field);
+ $proto_key = $this->convertJsonValueToProtoValue(
+ $tmp_key,
+ $key_field,
+ true);
+ $proto_value = $this->convertJsonValueToProtoValue(
+ $tmp_value,
+ $value_field);
self::kvUpdateHelper($field, $proto_key, $proto_value);
}
} else if ($field->isRepeated()) {
@@ -1075,14 +1125,16 @@ class Message
throw new \Exception(
"Repeated field elements cannot be null.");
}
- $proto_value =
- $this->convertJsonValueToProtoValue($tmp, $field);
+ $proto_value = $this->convertJsonValueToProtoValue(
+ $tmp,
+ $field);
self::appendHelper($field, $proto_value);
}
} else {
$setter = $field->getSetter();
- $proto_value =
- $this->convertJsonValueToProtoValue($value, $field);
+ $proto_value = $this->convertJsonValueToProtoValue(
+ $value,
+ $field);
if ($field->getType() === GPBType::MESSAGE) {
if (is_null($proto_value)) {
continue;
@@ -1104,7 +1156,7 @@ class Message
*/
public function parseFromJsonStream($input)
{
- $array = json_decode($input->getData(), JSON_BIGINT_AS_STRING);
+ $array = json_decode($input->getData(), true, 512, JSON_BIGINT_AS_STRING);
if (is_null($array)) {
throw new GPBDecodeException(
"Cannot decode json string.");
diff --git a/php/src/Google/Protobuf/Internal/MessageOptions.php b/php/src/Google/Protobuf/Internal/MessageOptions.php
index 99ff3d0e..bf490de6 100644
--- a/php/src/Google/Protobuf/Internal/MessageOptions.php
+++ b/php/src/Google/Protobuf/Internal/MessageOptions.php
@@ -87,9 +87,63 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
private $uninterpreted_option;
private $has_uninterpreted_option = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type bool $message_set_wire_format
+ * Set true to use the old proto1 MessageSet wire format for extensions.
+ * This is provided for backwards-compatibility with the MessageSet wire
+ * format. You should not use this for any other reason: It's less
+ * efficient, has fewer features, and is more complicated.
+ * The message must be defined exactly as follows:
+ * message Foo {
+ * option message_set_wire_format = true;
+ * extensions 4 to max;
+ * }
+ * Note that the message cannot have any defined fields; MessageSets only
+ * have extensions.
+ * All extensions of your type must be singular messages; e.g. they cannot
+ * be int32s, enums, or repeated messages.
+ * Because this is an option, the above two restrictions are not enforced by
+ * the protocol compiler.
+ * @type bool $no_standard_descriptor_accessor
+ * Disables the generation of the standard "descriptor()" accessor, which can
+ * conflict with a field of the same name. This is meant to make migration
+ * from proto1 easier; new code should avoid fields named "descriptor".
+ * @type bool $deprecated
+ * Is this message deprecated?
+ * Depending on the target platform, this can emit Deprecated annotations
+ * for the message, or it will be completely ignored; in the very least,
+ * this is a formalization for deprecating messages.
+ * @type bool $map_entry
+ * Whether the message is an automatically generated map entry type for the
+ * maps field.
+ * For maps fields:
+ * map<KeyType, ValueType> map_field = 1;
+ * The parsed descriptor looks like:
+ * message MapFieldEntry {
+ * option map_entry = true;
+ * optional KeyType key = 1;
+ * optional ValueType value = 2;
+ * }
+ * repeated MapFieldEntry map_field = 1;
+ * Implementations may choose not to generate the map_entry=true message, but
+ * use a native map in the target language to hold the keys and values.
+ * The reflection APIs in such implementions still need to work as
+ * if the field is a repeated message field.
+ * NOTE: Do not set the option in .proto files. Always use the maps syntax
+ * instead. The option should only be implicitly set by the proto compiler
+ * parser.
+ * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option
+ * The parser stores options it doesn't recognize here. See above.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/MethodDescriptorProto.php b/php/src/Google/Protobuf/Internal/MethodDescriptorProto.php
index ccfce2db..1bd5dd3e 100644
--- a/php/src/Google/Protobuf/Internal/MethodDescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/MethodDescriptorProto.php
@@ -55,9 +55,27 @@ class MethodDescriptorProto extends \Google\Protobuf\Internal\Message
private $server_streaming = false;
private $has_server_streaming = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name
+ * @type string $input_type
+ * Input and output type names. These are resolved in the same way as
+ * FieldDescriptorProto.type_name, but must refer to a message type.
+ * @type string $output_type
+ * @type \Google\Protobuf\Internal\MethodOptions $options
+ * @type bool $client_streaming
+ * Identifies if client streams multiple client messages
+ * @type bool $server_streaming
+ * Identifies if server streams multiple server messages
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/MethodOptions.php b/php/src/Google/Protobuf/Internal/MethodOptions.php
index baa806b7..a2c729a9 100644
--- a/php/src/Google/Protobuf/Internal/MethodOptions.php
+++ b/php/src/Google/Protobuf/Internal/MethodOptions.php
@@ -38,9 +38,25 @@ class MethodOptions extends \Google\Protobuf\Internal\Message
private $uninterpreted_option;
private $has_uninterpreted_option = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type bool $deprecated
+ * Is this method deprecated?
+ * Depending on the target platform, this can emit Deprecated annotations
+ * for the method, or it will be completely ignored; in the very least,
+ * this is a formalization for deprecating methods.
+ * @type int $idempotency_level
+ * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option
+ * The parser stores options it doesn't recognize here. See above.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php b/php/src/Google/Protobuf/Internal/MethodOptions/IdempotencyLevel.php
index 9e06d8ee..dcc30e27 100644
--- a/php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php
+++ b/php/src/Google/Protobuf/Internal/MethodOptions/IdempotencyLevel.php
@@ -2,16 +2,16 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-namespace Google\Protobuf\Internal;
+namespace Google\Protobuf\Internal\MethodOptions;
/**
* Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
* or neither? HTTP based RPC implementation may choose GET verb for safe
* methods, and PUT verb for idempotent methods instead of the default POST.
*
- * Protobuf enum <code>Google\Protobuf\Internal</code>
+ * Protobuf type <code>google.protobuf.MethodOptions.IdempotencyLevel</code>
*/
-class MethodOptions_IdempotencyLevel
+class IdempotencyLevel
{
/**
* Generated from protobuf enum <code>IDEMPOTENCY_UNKNOWN = 0;</code>
@@ -31,3 +31,6 @@ class MethodOptions_IdempotencyLevel
const IDEMPOTENT = 2;
}
+// Adding a class alias for backwards compatibility with the previous class name.
+class_alias(IdempotencyLevel::class, \Google\Protobuf\Internal\MethodOptions_IdempotencyLevel::class);
+
diff --git a/php/src/Google/Protobuf/Internal/OneofDescriptorProto.php b/php/src/Google/Protobuf/Internal/OneofDescriptorProto.php
index 15ff0610..9ecfe5cb 100644
--- a/php/src/Google/Protobuf/Internal/OneofDescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/OneofDescriptorProto.php
@@ -28,9 +28,19 @@ class OneofDescriptorProto extends \Google\Protobuf\Internal\Message
private $options = null;
private $has_options = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name
+ * @type \Google\Protobuf\Internal\OneofOptions $options
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/OneofOptions.php b/php/src/Google/Protobuf/Internal/OneofOptions.php
index e5b4633d..46b516f3 100644
--- a/php/src/Google/Protobuf/Internal/OneofOptions.php
+++ b/php/src/Google/Protobuf/Internal/OneofOptions.php
@@ -23,9 +23,19 @@ class OneofOptions extends \Google\Protobuf\Internal\Message
private $uninterpreted_option;
private $has_uninterpreted_option = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option
+ * The parser stores options it doesn't recognize here. See above.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/RepeatedField.php b/php/src/Google/Protobuf/Internal/RepeatedField.php
index 797b3b3a..e0ddef50 100644
--- a/php/src/Google/Protobuf/Internal/RepeatedField.php
+++ b/php/src/Google/Protobuf/Internal/RepeatedField.php
@@ -59,6 +59,10 @@ class RepeatedField implements \ArrayAccess, \IteratorAggregate, \Countable
* @ignore
*/
private $klass;
+ /**
+ * @ignore
+ */
+ private $legacy_klass;
/**
* Constructs an instance of RepeatedField.
@@ -71,7 +75,16 @@ class RepeatedField implements \ArrayAccess, \IteratorAggregate, \Countable
{
$this->container = [];
$this->type = $type;
- $this->klass = $klass;
+ if ($this->type == GPBType::MESSAGE) {
+ $pool = DescriptorPool::getGeneratedPool();
+ $desc = $pool->getDescriptorByClassName($klass);
+ if ($desc == NULL) {
+ new $klass; // No msg class instance has been created before.
+ $desc = $pool->getDescriptorByClassName($klass);
+ }
+ $this->klass = $desc->getClass();
+ $this->legacy_klass = $desc->getLegacyClass();
+ }
}
/**
@@ -91,6 +104,14 @@ class RepeatedField implements \ArrayAccess, \IteratorAggregate, \Countable
}
/**
+ * @ignore
+ */
+ public function getLegacyClass()
+ {
+ return $this->legacy_klass;
+ }
+
+ /**
* Return the element at the given index.
*
* This will also be called for: $ele = $arr[0]
diff --git a/php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php b/php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php
index da88e9c4..8de7afd0 100644
--- a/php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php
@@ -33,9 +33,20 @@ class ServiceDescriptorProto extends \Google\Protobuf\Internal\Message
private $options = null;
private $has_options = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name
+ * @type \Google\Protobuf\Internal\MethodDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $method
+ * @type \Google\Protobuf\Internal\ServiceOptions $options
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/ServiceOptions.php b/php/src/Google/Protobuf/Internal/ServiceOptions.php
index 3e7214a1..67162f37 100644
--- a/php/src/Google/Protobuf/Internal/ServiceOptions.php
+++ b/php/src/Google/Protobuf/Internal/ServiceOptions.php
@@ -33,9 +33,24 @@ class ServiceOptions extends \Google\Protobuf\Internal\Message
private $uninterpreted_option;
private $has_uninterpreted_option = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type bool $deprecated
+ * Is this service deprecated?
+ * Depending on the target platform, this can emit Deprecated annotations
+ * for the service, or it will be completely ignored; in the very least,
+ * this is a formalization for deprecating services.
+ * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option
+ * The parser stores options it doesn't recognize here. See above.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Internal/SourceCodeInfo.php b/php/src/Google/Protobuf/Internal/SourceCodeInfo.php
index 6ce05ed4..6e413f77 100644
--- a/php/src/Google/Protobuf/Internal/SourceCodeInfo.php
+++ b/php/src/Google/Protobuf/Internal/SourceCodeInfo.php
@@ -66,9 +66,59 @@ class SourceCodeInfo extends \Google\Protobuf\Internal\Message
private $location;
private $has_location = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type \Google\Protobuf\Internal\SourceCodeInfo\Location[]|\Google\Protobuf\Internal\RepeatedField $location
+ * A Location identifies a piece of source code in a .proto file which
+ * corresponds to a particular definition. This information is intended
+ * to be useful to IDEs, code indexers, documentation generators, and similar
+ * tools.
+ * For example, say we have a file like:
+ * message Foo {
+ * optional string foo = 1;
+ * }
+ * Let's look at just the field definition:
+ * optional string foo = 1;
+ * ^ ^^ ^^ ^ ^^^
+ * a bc de f ghi
+ * We have the following locations:
+ * span path represents
+ * [a,i) [ 4, 0, 2, 0 ] The whole field definition.
+ * [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
+ * [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
+ * [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
+ * [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
+ * Notes:
+ * - A location may refer to a repeated field itself (i.e. not to any
+ * particular index within it). This is used whenever a set of elements are
+ * logically enclosed in a single code segment. For example, an entire
+ * extend block (possibly containing multiple extension definitions) will
+ * have an outer location whose path refers to the "extensions" repeated
+ * field without an index.
+ * - Multiple locations may have the same path. This happens when a single
+ * logical declaration is spread out across multiple places. The most
+ * obvious example is the "extend" block again -- there may be multiple
+ * extend blocks in the same scope, each of which will have the same path.
+ * - A location's span is not always a subset of its parent's span. For
+ * example, the "extendee" of an extension declaration appears at the
+ * beginning of the "extend" block and is shared by all extensions within
+ * the block.
+ * - Just because a location's span is a subset of some other location's span
+ * does not mean that it is a descendent. For example, a "group" defines
+ * both a type and a field in a single declaration. Thus, the locations
+ * corresponding to the type and field and their components will overlap.
+ * - Code which tries to interpret locations should probably be designed to
+ * ignore those that it doesn't understand, as more types of locations could
+ * be recorded in the future.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
@@ -166,12 +216,12 @@ class SourceCodeInfo extends \Google\Protobuf\Internal\Message
* be recorded in the future.
*
* Generated from protobuf field <code>repeated .google.protobuf.SourceCodeInfo.Location location = 1;</code>
- * @param \Google\Protobuf\Internal\SourceCodeInfo_Location[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @param \Google\Protobuf\Internal\SourceCodeInfo\Location[]|\Google\Protobuf\Internal\RepeatedField $var
* @return $this
*/
public function setLocation($var)
{
- $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\SourceCodeInfo_Location::class);
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\SourceCodeInfo\Location::class);
$this->location = $arr;
$this->has_location = true;
diff --git a/php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php b/php/src/Google/Protobuf/Internal/SourceCodeInfo/Location.php
index 19ed2bc2..bad247a1 100644
--- a/php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php
+++ b/php/src/Google/Protobuf/Internal/SourceCodeInfo/Location.php
@@ -2,7 +2,7 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-namespace Google\Protobuf\Internal;
+namespace Google\Protobuf\Internal\SourceCodeInfo;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
@@ -13,7 +13,7 @@ use Google\Protobuf\Internal\GPBUtil;
/**
* Generated from protobuf message <code>google.protobuf.SourceCodeInfo.Location</code>
*/
-class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
+class Location extends \Google\Protobuf\Internal\Message
{
/**
* Identifies which part of the FileDescriptorProto was defined at this
@@ -106,9 +106,84 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
private $leading_detached_comments;
private $has_leading_detached_comments = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type int[]|\Google\Protobuf\Internal\RepeatedField $path
+ * Identifies which part of the FileDescriptorProto was defined at this
+ * location.
+ * Each element is a field number or an index. They form a path from
+ * the root FileDescriptorProto to the place where the definition. For
+ * example, this path:
+ * [ 4, 3, 2, 7, 1 ]
+ * refers to:
+ * file.message_type(3) // 4, 3
+ * .field(7) // 2, 7
+ * .name() // 1
+ * This is because FileDescriptorProto.message_type has field number 4:
+ * repeated DescriptorProto message_type = 4;
+ * and DescriptorProto.field has field number 2:
+ * repeated FieldDescriptorProto field = 2;
+ * and FieldDescriptorProto.name has field number 1:
+ * optional string name = 1;
+ * Thus, the above path gives the location of a field name. If we removed
+ * the last element:
+ * [ 4, 3, 2, 7 ]
+ * this path refers to the whole field declaration (from the beginning
+ * of the label to the terminating semicolon).
+ * @type int[]|\Google\Protobuf\Internal\RepeatedField $span
+ * Always has exactly three or four elements: start line, start column,
+ * end line (optional, otherwise assumed same as start line), end column.
+ * These are packed into a single field for efficiency. Note that line
+ * and column numbers are zero-based -- typically you will want to add
+ * 1 to each before displaying to a user.
+ * @type string $leading_comments
+ * If this SourceCodeInfo represents a complete declaration, these are any
+ * comments appearing before and after the declaration which appear to be
+ * attached to the declaration.
+ * A series of line comments appearing on consecutive lines, with no other
+ * tokens appearing on those lines, will be treated as a single comment.
+ * leading_detached_comments will keep paragraphs of comments that appear
+ * before (but not connected to) the current element. Each paragraph,
+ * separated by empty lines, will be one comment element in the repeated
+ * field.
+ * Only the comment content is provided; comment markers (e.g. //) are
+ * stripped out. For block comments, leading whitespace and an asterisk
+ * will be stripped from the beginning of each line other than the first.
+ * Newlines are included in the output.
+ * Examples:
+ * optional int32 foo = 1; // Comment attached to foo.
+ * // Comment attached to bar.
+ * optional int32 bar = 2;
+ * optional string baz = 3;
+ * // Comment attached to baz.
+ * // Another line attached to baz.
+ * // Comment attached to qux.
+ * //
+ * // Another line attached to qux.
+ * optional double qux = 4;
+ * // Detached comment for corge. This is not leading or trailing comments
+ * // to qux or corge because there are blank lines separating it from
+ * // both.
+ * // Detached comment for corge paragraph 2.
+ * optional string corge = 5;
+ * /&#42; Block comment attached
+ * * to corge. Leading asterisks
+ * * will be removed. *&#47;
+ * /&#42; Block comment attached to
+ * * grault. *&#47;
+ * optional int32 grault = 6;
+ * // ignored detached comments.
+ * @type string $trailing_comments
+ * @type string[]|\Google\Protobuf\Internal\RepeatedField $leading_detached_comments
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
@@ -383,3 +458,6 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
}
+// Adding a class alias for backwards compatibility with the previous class name.
+class_alias(Location::class, \Google\Protobuf\Internal\SourceCodeInfo_Location::class);
+
diff --git a/php/src/Google/Protobuf/Internal/UninterpretedOption.php b/php/src/Google/Protobuf/Internal/UninterpretedOption.php
index 4d342eb3..3b517ec5 100644
--- a/php/src/Google/Protobuf/Internal/UninterpretedOption.php
+++ b/php/src/Google/Protobuf/Internal/UninterpretedOption.php
@@ -61,9 +61,26 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
private $aggregate_value = '';
private $has_aggregate_value = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type \Google\Protobuf\Internal\UninterpretedOption\NamePart[]|\Google\Protobuf\Internal\RepeatedField $name
+ * @type string $identifier_value
+ * The value of the uninterpreted option, in whatever type the tokenizer
+ * identified it as during parsing. Exactly one of these should be set.
+ * @type int|string $positive_int_value
+ * @type int|string $negative_int_value
+ * @type float $double_value
+ * @type string $string_value
+ * @type string $aggregate_value
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
@@ -77,12 +94,12 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
/**
* Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption.NamePart name = 2;</code>
- * @param \Google\Protobuf\Internal\UninterpretedOption_NamePart[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @param \Google\Protobuf\Internal\UninterpretedOption\NamePart[]|\Google\Protobuf\Internal\RepeatedField $var
* @return $this
*/
public function setName($var)
{
- $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption_NamePart::class);
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption\NamePart::class);
$this->name = $arr;
$this->has_name = true;
diff --git a/php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php b/php/src/Google/Protobuf/Internal/UninterpretedOption/NamePart.php
index c9a6fc3c..92ee4b44 100644
--- a/php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php
+++ b/php/src/Google/Protobuf/Internal/UninterpretedOption/NamePart.php
@@ -2,7 +2,7 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-namespace Google\Protobuf\Internal;
+namespace Google\Protobuf\Internal\UninterpretedOption;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
@@ -19,7 +19,7 @@ use Google\Protobuf\Internal\GPBUtil;
*
* Generated from protobuf message <code>google.protobuf.UninterpretedOption.NamePart</code>
*/
-class UninterpretedOption_NamePart extends \Google\Protobuf\Internal\Message
+class NamePart extends \Google\Protobuf\Internal\Message
{
/**
* Generated from protobuf field <code>required string name_part = 1;</code>
@@ -32,9 +32,19 @@ class UninterpretedOption_NamePart extends \Google\Protobuf\Internal\Message
private $is_extension = false;
private $has_is_extension = false;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name_part
+ * @type bool $is_extension
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
@@ -95,3 +105,6 @@ class UninterpretedOption_NamePart extends \Google\Protobuf\Internal\Message
}
+// Adding a class alias for backwards compatibility with the previous class name.
+class_alias(NamePart::class, \Google\Protobuf\Internal\UninterpretedOption_NamePart::class);
+
diff --git a/php/src/Google/Protobuf/ListValue.php b/php/src/Google/Protobuf/ListValue.php
index 12552ef4..70f54232 100644
--- a/php/src/Google/Protobuf/ListValue.php
+++ b/php/src/Google/Protobuf/ListValue.php
@@ -23,9 +23,19 @@ class ListValue extends \Google\Protobuf\Internal\Message
*/
private $values;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type \Google\Protobuf\Value[]|\Google\Protobuf\Internal\RepeatedField $values
+ * Repeated field of dynamically typed values.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Struct::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Method.php b/php/src/Google/Protobuf/Method.php
index f55cb764..8e803506 100644
--- a/php/src/Google/Protobuf/Method.php
+++ b/php/src/Google/Protobuf/Method.php
@@ -58,9 +58,31 @@ class Method extends \Google\Protobuf\Internal\Message
*/
private $syntax = 0;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name
+ * The simple name of this method.
+ * @type string $request_type_url
+ * A URL of the input message type.
+ * @type bool $request_streaming
+ * If true, the request is streamed.
+ * @type string $response_type_url
+ * The URL of the output message type.
+ * @type bool $response_streaming
+ * If true, the response is streamed.
+ * @type \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $options
+ * Any metadata attached to the method.
+ * @type int $syntax
+ * The source syntax of this method.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Api::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Mixin.php b/php/src/Google/Protobuf/Mixin.php
index eb5117e0..a2ea59c7 100644
--- a/php/src/Google/Protobuf/Mixin.php
+++ b/php/src/Google/Protobuf/Mixin.php
@@ -90,9 +90,22 @@ class Mixin extends \Google\Protobuf\Internal\Message
*/
private $root = '';
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name
+ * The fully qualified name of the interface which is included.
+ * @type string $root
+ * If non-empty specifies a path under which inherited HTTP paths
+ * are rooted.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Api::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/NullValue.php b/php/src/Google/Protobuf/NullValue.php
index d4022ccc..482b80dd 100644
--- a/php/src/Google/Protobuf/NullValue.php
+++ b/php/src/Google/Protobuf/NullValue.php
@@ -9,7 +9,7 @@ namespace Google\Protobuf;
* `Value` type union.
* The JSON representation for `NullValue` is JSON `null`.
*
- * Protobuf enum <code>Google\Protobuf\NullValue</code>
+ * Protobuf type <code>google.protobuf.NullValue</code>
*/
class NullValue
{
diff --git a/php/src/Google/Protobuf/Option.php b/php/src/Google/Protobuf/Option.php
index f8038681..22ecfc5f 100644
--- a/php/src/Google/Protobuf/Option.php
+++ b/php/src/Google/Protobuf/Option.php
@@ -35,9 +35,27 @@ class Option extends \Google\Protobuf\Internal\Message
*/
private $value = null;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name
+ * The option's name. For protobuf built-in options (options defined in
+ * descriptor.proto), this is the short name. For example, `"map_entry"`.
+ * For custom options, it should be the fully-qualified name. For example,
+ * `"google.api.http"`.
+ * @type \Google\Protobuf\Any $value
+ * The option's value packed in an Any message. If the value is a primitive,
+ * the corresponding wrapper type defined in google/protobuf/wrappers.proto
+ * should be used. If the value is an enum, it should be stored as an int32
+ * value using the google.protobuf.Int32Value type.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Type::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/SourceContext.php b/php/src/Google/Protobuf/SourceContext.php
index 07d90c68..cbc50c68 100644
--- a/php/src/Google/Protobuf/SourceContext.php
+++ b/php/src/Google/Protobuf/SourceContext.php
@@ -24,9 +24,20 @@ class SourceContext extends \Google\Protobuf\Internal\Message
*/
private $file_name = '';
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $file_name
+ * The path-qualified name of the .proto file that contained the associated
+ * protobuf element. For example: `"google/protobuf/source_context.proto"`.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\SourceContext::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/StringValue.php b/php/src/Google/Protobuf/StringValue.php
index f6bcc48a..8fb354f3 100644
--- a/php/src/Google/Protobuf/StringValue.php
+++ b/php/src/Google/Protobuf/StringValue.php
@@ -23,9 +23,19 @@ class StringValue extends \Google\Protobuf\Internal\Message
*/
private $value = '';
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $value
+ * The string value.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Wrappers::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Struct.php b/php/src/Google/Protobuf/Struct.php
index 721e991c..0456541c 100644
--- a/php/src/Google/Protobuf/Struct.php
+++ b/php/src/Google/Protobuf/Struct.php
@@ -28,9 +28,19 @@ class Struct extends \Google\Protobuf\Internal\Message
*/
private $fields;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type array|\Google\Protobuf\Internal\MapField $fields
+ * Unordered map of dynamically typed values.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Struct::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Syntax.php b/php/src/Google/Protobuf/Syntax.php
index bb7b7896..3a52dc9e 100644
--- a/php/src/Google/Protobuf/Syntax.php
+++ b/php/src/Google/Protobuf/Syntax.php
@@ -7,7 +7,7 @@ namespace Google\Protobuf;
/**
* The syntax in which a protocol buffer element is defined.
*
- * Protobuf enum <code>Google\Protobuf\Syntax</code>
+ * Protobuf type <code>google.protobuf.Syntax</code>
*/
class Syntax
{
diff --git a/php/src/Google/Protobuf/Timestamp.php b/php/src/Google/Protobuf/Timestamp.php
index 7da8e956..a793c7e3 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>
*/
@@ -89,9 +91,26 @@ class Timestamp extends \Google\Protobuf\Internal\Message
*/
private $nanos = 0;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type int|string $seconds
+ * Represents seconds of UTC time since Unix epoch
+ * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
+ * 9999-12-31T23:59:59Z inclusive.
+ * @type int $nanos
+ * Non-negative fractions of a second at nanosecond resolution. Negative
+ * second values with fractions must still have non-negative nanos values
+ * that count forward in time. Must be from 0 to 999,999,999
+ * inclusive.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Timestamp::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
@@ -156,17 +175,13 @@ class Timestamp extends \Google\Protobuf\Internal\Message
return $this;
}
- /**
+ /*
* Converts PHP DateTime to Timestamp.
*
- * @param DateTime $datetime
+ * @param \DateTime $datetime
*/
- public function fromDateTime($datetime)
+ public function fromDateTime(\DateTime $datetime)
{
- if (get_class($datetime) !== \DateTime::class) {
- trigger_error("Given parameter is not a DateTime.",
- E_USER_ERROR);
- }
$this->seconds = $datetime->format('U');
$this->nanos = 0;
}
@@ -174,7 +189,7 @@ class Timestamp extends \Google\Protobuf\Internal\Message
/**
* Converts Timestamp to PHP DateTime. Nano second is ignored.
*
- * @return DateTime $datetime
+ * @return \DateTime $datetime
*/
public function toDateTime()
{
diff --git a/php/src/Google/Protobuf/Type.php b/php/src/Google/Protobuf/Type.php
index 7dbe2cab..1b478110 100644
--- a/php/src/Google/Protobuf/Type.php
+++ b/php/src/Google/Protobuf/Type.php
@@ -52,9 +52,29 @@ class Type extends \Google\Protobuf\Internal\Message
*/
private $syntax = 0;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type string $name
+ * The fully qualified message name.
+ * @type \Google\Protobuf\Field[]|\Google\Protobuf\Internal\RepeatedField $fields
+ * The list of fields.
+ * @type string[]|\Google\Protobuf\Internal\RepeatedField $oneofs
+ * The list of types appearing in `oneof` definitions in this type.
+ * @type \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $options
+ * The protocol buffer options.
+ * @type \Google\Protobuf\SourceContext $source_context
+ * The source context.
+ * @type int $syntax
+ * The source syntax.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Type::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/UInt32Value.php b/php/src/Google/Protobuf/UInt32Value.php
index 61a3ddf1..f5a522d2 100644
--- a/php/src/Google/Protobuf/UInt32Value.php
+++ b/php/src/Google/Protobuf/UInt32Value.php
@@ -23,9 +23,19 @@ class UInt32Value extends \Google\Protobuf\Internal\Message
*/
private $value = 0;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type int $value
+ * The uint32 value.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Wrappers::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/UInt64Value.php b/php/src/Google/Protobuf/UInt64Value.php
index 69f7eb8e..89e69cd8 100644
--- a/php/src/Google/Protobuf/UInt64Value.php
+++ b/php/src/Google/Protobuf/UInt64Value.php
@@ -23,9 +23,19 @@ class UInt64Value extends \Google\Protobuf\Internal\Message
*/
private $value = 0;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type int|string $value
+ * The uint64 value.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Wrappers::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/src/Google/Protobuf/Value.php b/php/src/Google/Protobuf/Value.php
index 052a3779..5c1e864c 100644
--- a/php/src/Google/Protobuf/Value.php
+++ b/php/src/Google/Protobuf/Value.php
@@ -21,9 +21,29 @@ class Value extends \Google\Protobuf\Internal\Message
{
protected $kind;
- public function __construct() {
+ /**
+ * Constructor.
+ *
+ * @param array $data {
+ * Optional. Data for populating the Message object.
+ *
+ * @type int $null_value
+ * Represents a null value.
+ * @type float $number_value
+ * Represents a double value.
+ * @type string $string_value
+ * Represents a string value.
+ * @type bool $bool_value
+ * Represents a boolean value.
+ * @type \Google\Protobuf\Struct $struct_value
+ * Represents a structured value.
+ * @type \Google\Protobuf\ListValue $list_value
+ * Represents a repeated `Value`.
+ * }
+ */
+ public function __construct($data = NULL) {
\GPBMetadata\Google\Protobuf\Struct::initOnce();
- parent::__construct();
+ parent::__construct($data);
}
/**
diff --git a/php/tests/array_test.php b/php/tests/array_test.php
index 1a26d72a..36a649ed 100644
--- a/php/tests/array_test.php
+++ b/php/tests/array_test.php
@@ -5,7 +5,7 @@ require_once('test_util.php');
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBType;
use Foo\TestMessage;
-use Foo\TestMessage_Sub;
+use Foo\TestMessage\Sub;
class RepeatedFieldTest extends PHPUnit_Framework_TestCase
{
@@ -456,10 +456,10 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
public function testMessage()
{
- $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr = new RepeatedField(GPBType::MESSAGE, Sub::class);
// Test append.
- $sub_m = new TestMessage_Sub();
+ $sub_m = new Sub();
$sub_m->setA(1);
$arr[] = $sub_m;
$this->assertSame(1, $arr[0]->getA());
@@ -467,15 +467,15 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
$this->assertEquals(1, count($arr));
// Test set.
- $sub_m = new TestMessage_Sub();
+ $sub_m = new Sub();
$sub_m->setA(2);
$arr[0] = $sub_m;
$this->assertSame(2, $arr[0]->getA());
// Test foreach.
- $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr = new RepeatedField(GPBType::MESSAGE, Sub::class);
for ($i = 0; $i < 3; $i++) {
- $arr[] = new TestMessage_Sub();
+ $arr[] = new Sub();
$arr[$i]->setA($i);
}
$i = 0;
diff --git a/php/tests/compatibility_test.sh b/php/tests/compatibility_test.sh
index 7caa46e7..b5b255ea 100755
--- a/php/tests/compatibility_test.sh
+++ b/php/tests/compatibility_test.sh
@@ -2,12 +2,14 @@
function use_php() {
VERSION=$1
- PHP=`which php`
- PHP_CONFIG=`which php-config`
- PHPIZE=`which phpize`
- ln -sfn "/usr/local/php-${VERSION}/bin/php" $PHP
- ln -sfn "/usr/local/php-${VERSION}/bin/php-config" $PHP_CONFIG
- ln -sfn "/usr/local/php-${VERSION}/bin/phpize" $PHPIZE
+
+ OLD_PATH=$PATH
+ OLD_CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH
+ OLD_C_INCLUDE_PATH=$C_INCLUDE_PATH
+
+ export PATH=/usr/local/php-${VERSION}/bin:$OLD_PATH
+ export CPLUS_INCLUDE_PATH=/usr/local/php-${VERSION}/include/php/main:/usr/local/php-${VERSION}/include/php/:$OLD_CPLUS_INCLUDE_PATH
+ export C_INCLUDE_PATH=/usr/local/php-${VERSION}/include/php/main:/usr/local/php-${VERSION}/include/php/:$OLD_C_INCLUDE_PATH
}
function generate_proto() {
@@ -18,7 +20,22 @@ function generate_proto() {
mkdir generated
$PROTOC1 --php_out=generated proto/test_include.proto
- $PROTOC2 --php_out=generated proto/test.proto proto/test_no_namespace.proto proto/test_prefix.proto
+ $PROTOC2 --php_out=generated \
+ proto/test.proto \
+ proto/test_no_namespace.proto \
+ proto/test_prefix.proto \
+ proto/test_php_namespace.proto \
+ proto/test_empty_php_namespace.proto \
+ proto/test_reserved_enum_lower.proto \
+ proto/test_reserved_enum_upper.proto \
+ proto/test_reserved_enum_value_lower.proto \
+ proto/test_reserved_enum_value_upper.proto \
+ proto/test_reserved_message_lower.proto \
+ proto/test_reserved_message_upper.proto \
+ proto/test_service.proto \
+ proto/test_service_namespace.proto \
+ proto/test_descriptors.proto
+
pushd ../../src
$PROTOC2 --php_out=../php/tests/generated -I../php/tests -I. ../php/tests/proto/test_import_descriptor_proto.proto
popd
@@ -52,9 +69,9 @@ cd $(dirname $0)
# The old version of protobuf that we are testing compatibility against.
case "$1" in
- ""|3.3.0)
- OLD_VERSION=3.3.0
- OLD_VERSION_PROTOC=http://repo1.maven.org/maven2/com/google/protobuf/protoc/3.3.0/protoc-3.3.0-linux-x86_64.exe
+ ""|3.5.0)
+ OLD_VERSION=3.5.0
+ OLD_VERSION_PROTOC=http://repo1.maven.org/maven2/com/google/protobuf/protoc/$OLD_VERSION/protoc-$OLD_VERSION-linux-x86_64.exe
;;
*)
echo "[ERROR]: Unknown version number: $1"
@@ -81,7 +98,7 @@ git checkout v$OLD_VERSION
popd
# Build and copy the new runtime
-use_php 5.5
+use_php 7.1
pushd ../ext/google/protobuf
make clean || true
phpize && ./configure && make
@@ -99,12 +116,12 @@ chmod +x old_protoc
NEW_PROTOC=`pwd`/../../src/protoc
OLD_PROTOC=`pwd`/old_protoc
cd protobuf/php
-cp -r /usr/local/vendor-5.5 vendor
-wget https://phar.phpunit.de/phpunit-4.8.0.phar -O /usr/bin/phpunit
+composer install
# Remove implementation detail tests.
tests=( array_test.php encode_decode_test.php generated_class_test.php map_field_test.php well_known_test.php )
sed -i.bak '/php_implementation_test.php/d' phpunit.xml
+sed -i.bak '/generated_phpdoc_test.php/d' phpunit.xml
for t in "${tests[@]}"
do
remove_error_test tests/$t
@@ -118,7 +135,7 @@ cd tests
generate_proto $OLD_PROTOC $OLD_PROTOC
./test.sh
pushd ..
-phpunit
+./vendor/bin/phpunit
popd
# Test A.2:
@@ -127,7 +144,7 @@ popd
generate_proto $NEW_PROTOC $OLD_PROTOC
./test.sh
pushd ..
-phpunit
+./vendor/bin/phpunit
popd
# Test A.3:
@@ -136,5 +153,5 @@ popd
generate_proto $OLD_PROTOC $NEW_PROTOC
./test.sh
pushd ..
-phpunit
+./vendor/bin/phpunit
popd
diff --git a/php/tests/descriptors_test.php b/php/tests/descriptors_test.php
index 17e8a4f2..93683b82 100644
--- a/php/tests/descriptors_test.php
+++ b/php/tests/descriptors_test.php
@@ -10,7 +10,7 @@ use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\MapField;
use Descriptors\TestDescriptorsEnum;
use Descriptors\TestDescriptorsMessage;
-use Descriptors\TestDescriptorsMessage_Sub;
+use Descriptors\TestDescriptorsMessage\Sub;
class DescriptorsTest extends TestBase
{
diff --git a/php/tests/encode_decode_test.php b/php/tests/encode_decode_test.php
index 74d5526d..d36b883e 100644
--- a/php/tests/encode_decode_test.php
+++ b/php/tests/encode_decode_test.php
@@ -7,7 +7,7 @@ use Google\Protobuf\RepeatedField;
use Google\Protobuf\GPBType;
use Foo\TestEnum;
use Foo\TestMessage;
-use Foo\TestMessage_Sub;
+use Foo\TestMessage\Sub;
use Foo\TestPackedMessage;
use Foo\TestRandomFieldOrder;
use Foo\TestUnpackedMessage;
@@ -82,7 +82,7 @@ class EncodeDecodeTest extends TestBase
$n->mergeFromString($data);
$this->assertSame('abc', $n->getOneofString());
- $sub_m = new TestMessage_Sub();
+ $sub_m = new Sub();
$sub_m->setA(1);
$m->setOneofMessage($sub_m);
$data = $m->serializeToString();
@@ -105,7 +105,7 @@ class EncodeDecodeTest extends TestBase
$this->assertSame("oneof_string", $n->getMyOneof());
$this->assertSame("", $n->getOneofString());
- $sub_m = new TestMessage_Sub();
+ $sub_m = new Sub();
$m->setOneofMessage($sub_m);
$data = $m->serializeToString();
$n = new TestMessage();
diff --git a/php/tests/gdb_test.sh b/php/tests/gdb_test.sh
index 484e2edf..36fa31bb 100755
--- a/php/tests/gdb_test.sh
+++ b/php/tests/gdb_test.sh
@@ -1,9 +1,17 @@
#!/bin/bash
+VERSION=$1
+
+export PATH=/usr/local/php-$VERSION/bin:$PATH
+export C_INCLUDE_PATH=/usr/local/php-$VERSION/include/php/main:/usr/local/php-$VERSION/include/php:$C_INCLUDE_PATH
+export CPLUS_INCLUDE_PATH=/usr/local/php-$VERSION/include/php/main:/usr/local/php-$VERSION/include/php:$CPLUS_INCLUDE_PATH
+
+php -i | grep "Configuration"
+
# gdb --args php -dextension=../ext/google/protobuf/modules/protobuf.so `which
# phpunit` --bootstrap autoload.php tmp_test.php
#
-gdb --args php -dextension=../ext/google/protobuf/modules/protobuf.so `which phpunit` --bootstrap autoload.php encode_decode_test.php
+gdb --args php -dextension=../ext/google/protobuf/modules/protobuf.so `which phpunit` --bootstrap autoload.php generated_class_test.php
#
# gdb --args php -dextension=../ext/google/protobuf/modules/protobuf.so memory_leak_test.php
#
diff --git a/php/tests/generated_class_test.php b/php/tests/generated_class_test.php
index 53d18ee7..9f20bddc 100644
--- a/php/tests/generated_class_test.php
+++ b/php/tests/generated_class_test.php
@@ -8,14 +8,20 @@ require_once('test_util.php');
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\MapField;
use Google\Protobuf\Internal\GPBType;
+use Bar\TestLegacyMessage;
+use Bar\TestLegacyMessage_NestedEnum;
+use Bar\TestLegacyMessage_NestedMessage;
use Foo\TestEnum;
use Foo\TestIncludeNamespaceMessage;
use Foo\TestIncludePrefixMessage;
use Foo\TestMessage;
+use Foo\TestMessage\Sub;
use Foo\TestMessage_Sub;
+use Foo\TestMessage\NestedEnum;
use Foo\TestReverseFieldOrder;
use Foo\testLowerCaseMessage;
use Foo\testLowerCaseEnum;
+use PBEmpty\PBEcho\TestEmptyPackage;
use Php\Test\TestNamespace;
class GeneratedClassTest extends TestBase
@@ -231,9 +237,26 @@ class GeneratedClassTest extends TestBase
public function testNestedEnum()
{
$m = new TestMessage();
+ $m->setOptionalNestedEnum(NestedEnum::ZERO);
+ }
+
+ public function testLegacyNestedEnum()
+ {
+ $m = new TestMessage();
$m->setOptionalNestedEnum(\Foo\TestMessage_NestedEnum::ZERO);
}
+ public function testLegacyTypehintWithNestedEnums()
+ {
+ $this->legacyEnum(new TestLegacyMessage\NestedEnum);
+ }
+
+ private function legacyEnum(TestLegacyMessage_NestedEnum $enum)
+ {
+ // If we made it here without a PHP Fatal error, the typehint worked
+ $this->assertTrue(true);
+ }
+
#########################################################
# Test float field.
#########################################################
@@ -370,6 +393,20 @@ class GeneratedClassTest extends TestBase
{
$m = new TestMessage();
+ $sub_m = new Sub();
+ $sub_m->setA(1);
+ $m->setOptionalMessage($sub_m);
+ $this->assertSame(1, $m->getOptionalMessage()->getA());
+
+ $null = null;
+ $m->setOptionalMessage($null);
+ $this->assertNull($m->getOptionalMessage());
+ }
+
+ public function testLegacyMessageField()
+ {
+ $m = new TestMessage();
+
$sub_m = new TestMessage_Sub();
$sub_m->setA(1);
$m->setOptionalMessage($sub_m);
@@ -380,6 +417,17 @@ class GeneratedClassTest extends TestBase
$this->assertNull($m->getOptionalMessage());
}
+ public function testLegacyTypehintWithNestedMessages()
+ {
+ $this->legacyMessage(new TestLegacyMessage\NestedMessage);
+ }
+
+ private function legacyMessage(TestLegacyMessage_NestedMessage $sub)
+ {
+ // If we made it here without a PHP Fatal error, the typehint worked
+ $this->assertTrue(true);
+ }
+
#########################################################
# Test repeated field.
#########################################################
@@ -474,7 +522,7 @@ class GeneratedClassTest extends TestBase
$this->assertSame(NULL, $m->getOneofMessage());
$this->assertSame("oneof_string", $m->getMyOneof());
- $sub_m = new TestMessage_Sub();
+ $sub_m = new Sub();
$sub_m->setA(1);
$m->setOneofMessage($sub_m);
$this->assertSame(0, $m->getOneofInt32());
@@ -513,7 +561,7 @@ class GeneratedClassTest extends TestBase
// Singular
$n->setOptionalInt32(100);
- $sub1 = new TestMessage_Sub();
+ $sub1 = new Sub();
$sub1->setA(101);
$b = $sub1->getB();
@@ -531,7 +579,7 @@ class GeneratedClassTest extends TestBase
$repeatedString[] = 'abc';
$n->setRepeatedString($repeatedString);
- $sub2 = new TestMessage_Sub();
+ $sub2 = new Sub();
$sub2->setA(201);
$repeatedMessage = $n->getRepeatedMessage();
$repeatedMessage[] = $sub2;
@@ -548,9 +596,9 @@ class GeneratedClassTest extends TestBase
$n->setMapStringString($mapStringString);
$mapInt32Message = $n->getMapInt32Message();
- $mapInt32Message[1] = new TestMessage_Sub();
+ $mapInt32Message[1] = new Sub();
$mapInt32Message[1]->setA(302);
- $mapInt32Message[2] = new TestMessage_Sub();
+ $mapInt32Message[2] = new Sub();
$mapInt32Message[2]->setA(303);
$n->setMapInt32Message($mapInt32Message);
@@ -607,7 +655,7 @@ class GeneratedClassTest extends TestBase
$m->mergeFrom($n);
$this->assertSame(1, $m->getOneofInt32());
- $sub = new TestMessage_Sub();
+ $sub = new Sub();
$n->setOneofMessage($sub);
$n->getOneofMessage()->setA(400);
$m->mergeFrom($n);
@@ -630,14 +678,15 @@ class GeneratedClassTest extends TestBase
public function testMessageWithoutNamespace()
{
$m = new TestMessage();
- $sub = new NoNameSpaceMessage();
- $m->setOptionalNoNamespaceMessage($sub);
+ $n = new NoNameSpaceMessage();
+ $m->setOptionalNoNamespaceMessage($n);
$repeatedNoNamespaceMessage = $m->getRepeatedNoNamespaceMessage();
$repeatedNoNamespaceMessage[] = new NoNameSpaceMessage();
$m->setRepeatedNoNamespaceMessage($repeatedNoNamespaceMessage);
- $n = new NoNamespaceMessage();
- $n->setB(NoNamespaceMessage_NestedEnum::ZERO);
+ // test nested messages
+ $sub = new NoNamespaceMessage\NestedMessage();
+ $n->setNestedMessage($sub);
}
public function testEnumWithoutNamespace()
@@ -650,35 +699,91 @@ class GeneratedClassTest extends TestBase
}
#########################################################
- # Test message with given prefix.
+ # Test message with given namespace.
#########################################################
- public function testPrefixMessage()
+ public function testNestedMessagesAndEnums()
{
+ $m = new TestMessage();
+ $n = new TestMessage\Sub();
+ $m->setOptionalMessage($n);
+ $m->setOptionalNestedEnum(TestMessage\NestedEnum::ZERO);
+ $this->assertSame($n, $m->getOptionalMessage());
+ $this->assertSame(TestMessage\NestedEnum::ZERO, $m->getOptionalNestedEnum());
+ }
+
+ public function testMessagesAndEnumsWithPrefix()
+ {
+ // Test message prefix
$m = new TestIncludePrefixMessage();
$n = new PrefixTestPrefix();
$n->setA(1);
$m->setPrefixMessage($n);
$this->assertSame(1, $m->getPrefixMessage()->getA());
+
+ // Test nested message prefix
+ $o = new PrefixTestPrefix();
+ $p = new PrefixTestPrefix\PrefixNestedMessage();
+ $o->setNestedMessage($p);
+ $o->setNestedEnum(PrefixTestPrefix\PrefixNestedEnum::ZERO);
+ $this->assertSame($p, $o->getNestedMessage());
+ $this->assertSame(PrefixTestPrefix\PrefixNestedEnum::ZERO, $o->getNestedEnum());
}
- #########################################################
- # Test message with given namespace.
- #########################################################
+ public function testMessagesAndEnumsWithPhpNamespace()
+ {
+ $m = new TestNamespace();
+ $n = new TestNamespace\NestedMessage();
+ $m->setNestedMessage($n);
+ $m->setNestedEnum(TestNamespace\NestedEnum::ZERO);
+ $this->assertSame($n, $m->getNestedMessage());
+ $this->assertSame(TestNamespace\NestedEnum::ZERO, $m->getNestedEnum());
+ }
- public function testNamespaceMessage()
+ public function testMesssagesAndEnumsWithEmptyPhpNamespace()
{
- $m = new TestIncludeNamespaceMessage();
+ $m = new TestEmptyNamespace();
+ $n = new TestEmptyNamespace\NestedMessage();
+ $m->setNestedMessage($n);
+ $m->setNestedEnum(TestEmptyNamespace\NestedEnum::ZERO);
+ $this->assertSame($n, $m->getNestedMessage());
+ $this->assertSame(TestEmptyNamespace\NestedEnum::ZERO, $m->getNestedEnum());
+ }
- $n = new TestNamespace();
- $n->setA(1);
- $m->setNamespaceMessage($n);
- $this->assertSame(1, $m->getNamespaceMessage()->getA());
+ public function testMessagesAndEnumsWithNoNamespace()
+ {
+ $m = new NoNamespaceMessage();
+ $n = new NoNamespaceMessage\NestedMessage();
+ $m->setNestedMessage($n);
+ $m->setNestedEnum(NoNamespaceMessage\NestedEnum::ZERO);
+ $this->assertSame($n, $m->getNestedMessage());
+ $this->assertSame(NoNamespaceMessage\NestedEnum::ZERO, $m->getNestedEnum());
+ }
- $n = new TestEmptyNamespace();
- $n->setA(1);
- $m->setEmptyNamespaceMessage($n);
- $this->assertSame(1, $m->getEmptyNamespaceMessage()->getA());
+ public function testReservedWordsInPackageName()
+ {
+ $m = new TestEmptyPackage();
+ $n = new TestEmptyPackage\NestedMessage();
+ $m->setNestedMessage($n);
+ $m->setNestedEnum(TestEmptyPackage\NestedEnum::ZERO);
+ $this->assertSame($n, $m->getNestedMessage());
+ $this->assertSame(TestEmptyPackage\NestedEnum::ZERO, $m->getNestedEnum());
+ }
+
+ public function testReservedWordsInNamespace()
+ {
+ $m = new TestNamespace();
+ $n = new TestNamespace\PBEmpty();
+ $o = new TestNamespace\PBEmpty\NestedMessage();
+ $n->setNestedMessage($o);
+ $n->setNestedEnum(TestNamespace\PBEmpty\NestedEnum::ZERO);
+ $m->setReservedName($n);
+ $this->assertSame($n, $m->getReservedName());
+ $this->assertSame($o, $n->getNestedMessage());
+ $this->assertSame(
+ TestNamespace\PBEmpty\NestedEnum::ZERO,
+ $n->getNestedEnum()
+ );
}
#########################################################
@@ -687,7 +792,7 @@ class GeneratedClassTest extends TestBase
public function testPrefixForReservedWords()
{
- $m = new \Foo\TestMessage_Empty();
+ $m = new \Foo\TestMessage\PBEmpty();
$m = new \Foo\PBEmpty();
$m = new \PrefixEmpty();
$m = new \Foo\PBARRAY();
@@ -1171,4 +1276,70 @@ class GeneratedClassTest extends TestBase
$m = new testLowerCaseMessage();
$n = testLowerCaseEnum::VALUE;
}
+
+ #########################################################
+ # Test Array Constructor.
+ #########################################################
+
+ public function testArrayConstructor()
+ {
+ $m = new TestMessage([
+ 'optional_int32' => -42,
+ 'optional_int64' => -43,
+ 'optional_uint32' => 42,
+ 'optional_uint64' => 43,
+ 'optional_sint32' => -44,
+ 'optional_sint64' => -45,
+ 'optional_fixed32' => 46,
+ 'optional_fixed64' => 47,
+ 'optional_sfixed32' => -46,
+ 'optional_sfixed64' => -47,
+ 'optional_float' => 1.5,
+ 'optional_double' => 1.6,
+ 'optional_bool' => true,
+ 'optional_string' => 'a',
+ 'optional_bytes' => 'b',
+ 'optional_enum' => TestEnum::ONE,
+ 'optional_message' => new Sub([
+ 'a' => 33
+ ]),
+ 'repeated_int32' => [-42, -52],
+ 'repeated_int64' => [-43, -53],
+ 'repeated_uint32' => [42, 52],
+ 'repeated_uint64' => [43, 53],
+ 'repeated_sint32' => [-44, -54],
+ 'repeated_sint64' => [-45, -55],
+ 'repeated_fixed32' => [46, 56],
+ 'repeated_fixed64' => [47, 57],
+ 'repeated_sfixed32' => [-46, -56],
+ 'repeated_sfixed64' => [-47, -57],
+ 'repeated_float' => [1.5, 2.5],
+ 'repeated_double' => [1.6, 2.6],
+ 'repeated_bool' => [true, false],
+ 'repeated_string' => ['a', 'c'],
+ 'repeated_bytes' => ['b', 'd'],
+ 'repeated_enum' => [TestEnum::ZERO, TestEnum::ONE],
+ 'repeated_message' => [new Sub(['a' => 34]),
+ new Sub(['a' => 35])],
+ 'map_int32_int32' => [-62 => -62],
+ 'map_int64_int64' => [-63 => -63],
+ 'map_uint32_uint32' => [62 => 62],
+ 'map_uint64_uint64' => [63 => 63],
+ 'map_sint32_sint32' => [-64 => -64],
+ 'map_sint64_sint64' => [-65 => -65],
+ 'map_fixed32_fixed32' => [66 => 66],
+ 'map_fixed64_fixed64' => [67 => 67],
+ 'map_sfixed32_sfixed32' => [-68 => -68],
+ 'map_sfixed64_sfixed64' => [-69 => -69],
+ 'map_int32_float' => [1 => 3.5],
+ 'map_int32_double' => [1 => 3.6],
+ 'map_bool_bool' => [true => true],
+ 'map_string_string' => ['e' => 'e'],
+ 'map_int32_bytes' => [1 => 'f'],
+ 'map_int32_enum' => [1 => TestEnum::ONE],
+ 'map_int32_message' => [1 => new Sub(['a' => 36])],
+ ]);
+
+ TestUtil::assertTestMessage($m);
+ }
}
diff --git a/php/tests/generated_phpdoc_test.php b/php/tests/generated_phpdoc_test.php
index 6c1a26f7..526927fc 100644
--- a/php/tests/generated_phpdoc_test.php
+++ b/php/tests/generated_phpdoc_test.php
@@ -16,6 +16,14 @@ class GeneratedPhpdocTest extends TestBase
$this->assertContains('foo.TestMessage', $doc);
}
+ public function testPhpDocForConstructor()
+ {
+ $class = new ReflectionClass('Foo\TestMessage');
+ $doc = $class->getMethod('__construct')->getDocComment();
+ $this->assertContains('@param array $data', $doc);
+ $this->assertContains('@type int $optional_int32', $doc);
+ }
+
/**
* @dataProvider providePhpDocForGettersAndSetters
*/
@@ -193,7 +201,7 @@ class GeneratedPhpdocTest extends TestBase
[
'setRepeatedMessage',
],
- '@param \Foo\TestMessage_Sub[]|\Google\Protobuf\Internal\RepeatedField $var'
+ '@param \Foo\TestMessage\Sub[]|\Google\Protobuf\Internal\RepeatedField $var'
],
[
[
@@ -286,14 +294,14 @@ class GeneratedPhpdocTest extends TestBase
'getOptionalMessage',
'getOneofMessage'
],
- '@return \Foo\TestMessage_Sub'
+ '@return \Foo\TestMessage\Sub'
],
[
[
'setOptionalMessage',
'setOneofMessage'
],
- '@param \Foo\TestMessage_Sub $var'
+ '@param \Foo\TestMessage\Sub $var'
],
[
[
diff --git a/php/tests/map_field_test.php b/php/tests/map_field_test.php
index cffa2526..447bdd9b 100644
--- a/php/tests/map_field_test.php
+++ b/php/tests/map_field_test.php
@@ -5,7 +5,7 @@ require_once('test_util.php');
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\MapField;
use Foo\TestMessage;
-use Foo\TestMessage_Sub;
+use Foo\TestMessage\Sub;
class MapFieldTest extends PHPUnit_Framework_TestCase {
@@ -408,10 +408,10 @@ class MapFieldTest extends PHPUnit_Framework_TestCase {
public function testMessage() {
$arr = new MapField(GPBType::INT32,
- GPBType::MESSAGE, TestMessage_Sub::class);
+ GPBType::MESSAGE, Sub::class);
// Test append.
- $sub_m = new TestMessage_Sub();
+ $sub_m = new Sub();
$sub_m->setA(1);
$arr[0] = $sub_m;
$this->assertSame(1, $arr[0]->getA());
@@ -420,9 +420,9 @@ class MapFieldTest extends PHPUnit_Framework_TestCase {
// Test foreach.
$arr = new MapField(GPBType::INT32,
- GPBType::MESSAGE, TestMessage_Sub::class);
+ GPBType::MESSAGE, Sub::class);
for ($i = 0; $i < 3; $i++) {
- $arr[$i] = new TestMessage_Sub();;
+ $arr[$i] = new Sub();;
$arr[$i]->setA($i);
}
$i = 0;
diff --git a/php/tests/memory_leak_test.php b/php/tests/memory_leak_test.php
index 507635e7..4e3874b7 100644
--- a/php/tests/memory_leak_test.php
+++ b/php/tests/memory_leak_test.php
@@ -4,20 +4,28 @@
require_once('generated/NoNamespaceEnum.php');
require_once('generated/NoNamespaceMessage.php');
-require_once('generated/NoNamespaceMessage_NestedEnum.php');
+require_once('generated/NoNamespaceMessage/NestedEnum.php');
+require_once('generated/NoNamespaceMessage/NestedMessage.php');
require_once('generated/PrefixEmpty.php');
require_once('generated/PrefixTestPrefix.php');
+require_once('generated/PrefixTestPrefix/PrefixNestedEnum.php');
+require_once('generated/PrefixTestPrefix/PrefixNestedMessage.php');
require_once('generated/TestEmptyNamespace.php');
+require_once('generated/TestEmptyNamespace/NestedEnum.php');
+require_once('generated/TestEmptyNamespace/NestedMessage.php');
require_once('generated/Bar/TestInclude.php');
+require_once('generated/Bar/TestLegacyMessage.php');
+require_once('generated/Bar/TestLegacyMessage/NestedEnum.php');
+require_once('generated/Bar/TestLegacyMessage/NestedMessage.php');
require_once('generated/Foo/PBARRAY.php');
require_once('generated/Foo/PBEmpty.php');
require_once('generated/Foo/TestEnum.php');
require_once('generated/Foo/TestIncludeNamespaceMessage.php');
require_once('generated/Foo/TestIncludePrefixMessage.php');
require_once('generated/Foo/TestMessage.php');
-require_once('generated/Foo/TestMessage_Empty.php');
-require_once('generated/Foo/TestMessage_NestedEnum.php');
-require_once('generated/Foo/TestMessage_Sub.php');
+require_once('generated/Foo/TestMessage/PBEmpty.php');
+require_once('generated/Foo/TestMessage/NestedEnum.php');
+require_once('generated/Foo/TestMessage/Sub.php');
require_once('generated/Foo/TestPackedMessage.php');
require_once('generated/Foo/TestPhpDoc.php');
require_once('generated/Foo/TestRandomFieldOrder.php');
@@ -26,18 +34,23 @@ require_once('generated/Foo/TestUnpackedMessage.php');
require_once('generated/Foo/testLowerCaseMessage.php');
require_once('generated/Foo/testLowerCaseEnum.php');
require_once('generated/GPBMetadata/Proto/Test.php');
-require_once('generated/GPBMetadata/Proto/TestEmptyPhpNamespace.php');
+require_once('generated/TestEmptyPhpNamespace.php');
require_once('generated/GPBMetadata/Proto/TestInclude.php');
-require_once('generated/GPBMetadata/Proto/TestNoNamespace.php');
-require_once('generated/GPBMetadata/Proto/TestPhpNamespace.php');
+require_once('generated/TestNoNamespace.php');
+require_once('generated/Metadata/Php/Test/TestPhpNamespace.php');
require_once('generated/GPBMetadata/Proto/TestPrefix.php');
require_once('generated/Php/Test/TestNamespace.php');
+require_once('generated/Php/Test/TestNamespace/PBEmpty.php');
+require_once('generated/Php/Test/TestNamespace/PBEmpty/NestedEnum.php');
+require_once('generated/Php/Test/TestNamespace/PBEmpty/NestedMessage.php');
+require_once('generated/Php/Test/TestNamespace/NestedEnum.php');
+require_once('generated/Php/Test/TestNamespace/NestedMessage.php');
require_once('test_util.php');
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBType;
use Foo\TestMessage;
-use Foo\TestMessage_Sub;
+use Foo\TestMessage\Sub;
$from = new TestMessage();
TestUtil::setTestMessage($from);
@@ -50,6 +63,13 @@ $to->mergeFromString($data);
TestUtil::assertTestMessage($to);
+$from = new TestMessage();
+TestUtil::setTestMessage2($from);
+
+$data = $from->serializeToString();
+
+$to->mergeFromString($data);
+
// TODO(teboring): This causes following tests fail in php7.
# $from->setRecursive($from);
@@ -90,7 +110,7 @@ $n = new TestMessage();
$n->mergeFromString($data);
assert('abc' === $n->getOneofString());
-$sub_m = new TestMessage_Sub();
+$sub_m = new Sub();
$sub_m->setA(1);
$m->setOneofMessage($sub_m);
assert(0 === $m->getOneofInt32());
@@ -104,7 +124,7 @@ assert(1 === $n->getOneofMessage()->getA());
$m = new TestMessage();
$m->mergeFromString(hex2bin('F80601'));
-assert('F80601', bin2hex($m->serializeToString()));
+assert('f80601' === bin2hex($m->serializeToString()));
// Test create repeated field via array.
$str_arr = array("abc");
@@ -142,13 +162,32 @@ $from = new \Google\Protobuf\Value();
$from->setNumberValue(1);
assert(1, $from->getNumberValue());
+// Test discard unknown in message.
+$m = new TestMessage();
+$from = hex2bin('F80601');
+$m->mergeFromString($from);
+$m->discardUnknownFields();
+$to = $m->serializeToString();
+assert("" === bin2hex($to));
+
+// Test clear
+$m = new TestMessage();
+TestUtil::setTestMessage($m);
+$m->clear();
+
+// Test unset map element
+$m = new TestMessage();
+$map = $m->getMapStringString();
+$map[1] = 1;
+unset($map[1]);
+
// Test descriptor
$pool = \Google\Protobuf\DescriptorPool::getGeneratedPool();
$desc = $pool->getDescriptorByClassName("\Foo\TestMessage");
$field = $desc->getField(1);
-# $from = new TestMessage();
-# $to = new TestMessage();
-# TestUtil::setTestMessage($from);
-# $to->mergeFrom($from);
-# TestUtil::assertTestMessage($to);
+$from = new TestMessage();
+$to = new TestMessage();
+TestUtil::setTestMessage($from);
+$to->mergeFrom($from);
+TestUtil::assertTestMessage($to);
diff --git a/php/tests/php_implementation_test.php b/php/tests/php_implementation_test.php
index 5dbc9233..323a36ff 100644
--- a/php/tests/php_implementation_test.php
+++ b/php/tests/php_implementation_test.php
@@ -3,8 +3,9 @@
require_once('test_base.php');
require_once('test_util.php');
+use Foo\TestEnum;
use Foo\TestMessage;
-use Foo\TestMessage_Sub;
+use Foo\TestMessage\Sub;
use Foo\TestPackedMessage;
use Google\Protobuf\Internal\CodedInputStream;
use Google\Protobuf\Internal\FileDescriptorSet;
@@ -15,7 +16,6 @@ use Google\Protobuf\Internal\CodedOutputStream;
class ImplementationTest extends TestBase
{
-
public function testReadInt32()
{
$value = null;
@@ -513,4 +513,75 @@ class ImplementationTest extends TestBase
TestUtil::setTestPackedMessage($m);
$this->assertSame(166, $m->byteSize());
}
+
+ /**
+ * @expectedException UnexpectedValueException
+ * @expectedExceptionMessage Invalid message property: optionalInt32
+ */
+ public function testArrayConstructorJsonCaseThrowsException()
+ {
+ $m = new TestMessage([
+ 'optionalInt32' => -42,
+ ]);
+ }
+
+ /**
+ * @expectedException Exception
+ * @expectedExceptionMessage Expect Foo\TestMessage_Sub.
+ */
+ public function testArraysForMessagesThrowsException()
+ {
+ $m = new TestMessage([
+ 'optional_message' => [
+ 'a' => 33
+ ]
+ ]);
+ }
+
+ public function testArrayConstructorWithNullValues()
+ {
+ $requestData = [
+ 'optional_bool' => null,
+ 'optional_string' => null,
+ 'optional_bytes' => null,
+ 'optional_message' => null,
+ ];
+
+ $m = new TestMessage($requestData);
+
+ $this->assertSame(false, $m->getOptionalBool());
+ $this->assertSame('', $m->getOptionalString());
+ $this->assertSame('', $m->getOptionalBytes());
+ $this->assertSame(null, $m->getOptionalMessage());
+ }
+
+ /**
+ * @dataProvider provideArrayConstructorWithNullValuesThrowsException
+ * @expectedException Exception
+ */
+ public function testArrayConstructorWithNullValuesThrowsException($requestData)
+ {
+ $m = new TestMessage($requestData);
+ }
+
+ public function provideArrayConstructorWithNullValuesThrowsException()
+ {
+ return [
+ [['optional_int32' => null]],
+ [['optional_int64' => null]],
+ [['optional_uint32' => null]],
+ [['optional_uint64' => null]],
+ [['optional_sint32' => null]],
+ [['optional_sint64' => null]],
+ [['optional_fixed32' => null]],
+ [['optional_fixed64' => null]],
+ [['optional_sfixed32' => null]],
+ [['optional_sfixed64' => null]],
+ [['optional_float' => null]],
+ [['optional_double' => null]],
+ [['optional_enum' => null]],
+ [['repeated_int32' => null]],
+ [['map_int32_int32' => null]],
+ ];
+ }
}
diff --git a/php/tests/proto/empty/echo.proto b/php/tests/proto/empty/echo.proto
new file mode 100644
index 00000000..1817018d
--- /dev/null
+++ b/php/tests/proto/empty/echo.proto
@@ -0,0 +1,17 @@
+syntax = "proto3";
+
+package empty.echo;
+
+message TestEmptyPackage {
+ int32 a = 1;
+
+ // Test nested messages, enums, and reserved names
+ NestedMessage nested_message = 2;
+ NestedEnum nested_enum = 3;
+ message NestedMessage {
+ int32 a = 1;
+ }
+ enum NestedEnum {
+ ZERO = 0;
+ };
+}
diff --git a/php/tests/proto/test_empty_php_namespace.proto b/php/tests/proto/test_empty_php_namespace.proto
index 7b4bc74d..c7ed1657 100644
--- a/php/tests/proto/test_empty_php_namespace.proto
+++ b/php/tests/proto/test_empty_php_namespace.proto
@@ -2,7 +2,18 @@ syntax = "proto3";
package foo;
option php_namespace = "";
+option php_metadata_namespace = "";
message TestEmptyNamespace {
int32 a = 1;
+
+ // Test nested messages, enums, and reserved names
+ NestedMessage nested_message = 2;
+ NestedEnum nested_enum = 3;
+ message NestedMessage {
+ int32 a = 1;
+ }
+ enum NestedEnum {
+ ZERO = 0;
+ };
}
diff --git a/php/tests/proto/test_include.proto b/php/tests/proto/test_include.proto
index 9844617f..a9072fe3 100644
--- a/php/tests/proto/test_include.proto
+++ b/php/tests/proto/test_include.proto
@@ -5,3 +5,14 @@ package bar;
message TestInclude {
int32 a = 1;
}
+
+message TestLegacyMessage {
+ NestedMessage message = 1;
+ NestedEnum enum = 2;
+ message NestedMessage {
+ int32 a = 1;
+ }
+ enum NestedEnum {
+ ZERO = 0;
+ }
+}
diff --git a/php/tests/proto/test_no_namespace.proto b/php/tests/proto/test_no_namespace.proto
index 58f13d47..cce42ea2 100644
--- a/php/tests/proto/test_no_namespace.proto
+++ b/php/tests/proto/test_no_namespace.proto
@@ -1,13 +1,19 @@
syntax = "proto3";
+option php_metadata_namespace = "\\";
+
message NoNamespaceMessage {
int32 a = 1;
- enum NestedEnum {
- ZERO = 0;
+ // Test nested messages, enums, and reserved names
+ NestedMessage nested_message = 2;
+ NestedEnum nested_enum = 3;
+ message NestedMessage {
+ int32 a = 1;
}
- NestedEnum b = 2;
- repeated NestedEnum c = 3;
+ enum NestedEnum {
+ ZERO = 0;
+ };
}
enum NoNamespaceEnum {
diff --git a/php/tests/proto/test_php_namespace.proto b/php/tests/proto/test_php_namespace.proto
index 713187b9..61085bf7 100644
--- a/php/tests/proto/test_php_namespace.proto
+++ b/php/tests/proto/test_php_namespace.proto
@@ -2,7 +2,30 @@ syntax = "proto3";
package foo;
option php_namespace = "Php\\Test";
+option php_metadata_namespace = "Metadata\\Php\\Test";
message TestNamespace {
int32 a = 1;
+
+ // Test nested messages, enums, and reserved names
+ NestedMessage nested_message = 2;
+ NestedEnum nested_enum = 3;
+ Empty reserved_name = 4;
+ message NestedMessage {
+ int32 a = 1;
+ }
+ enum NestedEnum {
+ ZERO = 0;
+ };
+ // Test reserved name
+ message Empty {
+ NestedMessage nested_message = 1;
+ NestedEnum nested_enum = 2;
+ message NestedMessage {
+ int32 a = 1;
+ }
+ enum NestedEnum {
+ ZERO = 0;
+ };
+ }
}
diff --git a/php/tests/proto/test_prefix.proto b/php/tests/proto/test_prefix.proto
index 9bfbad7f..3fa11381 100644
--- a/php/tests/proto/test_prefix.proto
+++ b/php/tests/proto/test_prefix.proto
@@ -4,6 +4,14 @@ option php_class_prefix = "Prefix";
message TestPrefix {
int32 a = 1;
+ NestedMessage nested_message = 2;
+ NestedEnum nested_enum = 3;
+ message NestedMessage {
+ int32 a = 1;
+ }
+ enum NestedEnum {
+ ZERO = 0;
+ };
}
// Test prefix for reserved words.
diff --git a/php/tests/test.sh b/php/tests/test.sh
index c35372d3..6e70eb2a 100755
--- a/php/tests/test.sh
+++ b/php/tests/test.sh
@@ -1,5 +1,11 @@
#!/bin/bash
+VERSION=$1
+
+export PATH=/usr/local/php-$VERSION/bin:$PATH
+export C_INCLUDE_PATH=/usr/local/php-$VERSION/include/php/main:/usr/local/php-$VERSION/include/php:$C_INCLUDE_PATH
+export CPLUS_INCLUDE_PATH=/usr/local/php-$VERSION/include/php/main:/usr/local/php-$VERSION/include/php:$CPLUS_INCLUDE_PATH
+
# Compile c extension
pushd ../ext/google/protobuf/
make clean || true
@@ -25,3 +31,15 @@ done
export ZEND_DONT_UNLOAD_MODULES=1
export USE_ZEND_ALLOC=0
valgrind --leak-check=yes php -dextension=../ext/google/protobuf/modules/protobuf.so memory_leak_test.php
+
+# TODO(teboring): Only for debug (phpunit has memory leak which blocks this beging used by
+# regresssion test.)
+
+# for t in "${tests[@]}"
+# do
+# echo "****************************"
+# echo "* $t (memory leak)"
+# echo "****************************"
+# valgrind --leak-check=yes php -dextension=../ext/google/protobuf/modules/protobuf.so `which phpunit` --bootstrap autoload.php $t
+# echo ""
+# done
diff --git a/php/tests/test_base.php b/php/tests/test_base.php
index dc5e73f5..80f603c7 100644
--- a/php/tests/test_base.php
+++ b/php/tests/test_base.php
@@ -2,7 +2,7 @@
use Foo\TestMessage;
use Foo\TestEnum;
-use Foo\TestMessage_Sub;
+use Foo\TestMessage\Sub;
class TestBase extends PHPUnit_Framework_TestCase
{
diff --git a/php/tests/test_util.php b/php/tests/test_util.php
index c8afdd3e..a676d097 100644
--- a/php/tests/test_util.php
+++ b/php/tests/test_util.php
@@ -2,7 +2,7 @@
use Foo\TestEnum;
use Foo\TestMessage;
-use Foo\TestMessage_Sub;
+use Foo\TestMessage\Sub;
use Foo\TestPackedMessage;
use Foo\TestUnpackedMessage;
@@ -67,7 +67,7 @@ class TestUtil
$m->setOptionalString('a');
$m->setOptionalBytes('b');
$m->setOptionalEnum(TestEnum::ONE);
- $sub = new TestMessage_Sub();
+ $sub = new Sub();
$m->setOptionalMessage($sub);
$m->getOptionalMessage()->SetA(33);
@@ -87,7 +87,7 @@ class TestUtil
self::appendHelper($m, 'RepeatedString', 'a');
self::appendHelper($m, 'RepeatedBytes', 'b');
self::appendHelper($m, 'RepeatedEnum', TestEnum::ZERO);
- self::appendHelper($m, 'RepeatedMessage', new TestMessage_Sub());
+ self::appendHelper($m, 'RepeatedMessage', new Sub());
$m->getRepeatedMessage()[0]->setA(34);
self::appendHelper($m, 'RepeatedInt32', -52);
@@ -106,7 +106,7 @@ class TestUtil
self::appendHelper($m, 'RepeatedString', 'c');
self::appendHelper($m, 'RepeatedBytes', 'd');
self::appendHelper($m, 'RepeatedEnum', TestEnum::ONE);
- self::appendHelper($m, 'RepeatedMessage', new TestMessage_Sub());
+ self::appendHelper($m, 'RepeatedMessage', new Sub());
$m->getRepeatedMessage()[1]->SetA(35);
self::kvUpdateHelper($m, 'MapInt32Int32', -62, -62);
@@ -125,13 +125,13 @@ class TestUtil
self::kvUpdateHelper($m, 'MapStringString', 'e', 'e');
self::kvUpdateHelper($m, 'MapInt32Bytes', 1, 'f');
self::kvUpdateHelper($m, 'MapInt32Enum', 1, TestEnum::ONE);
- self::kvUpdateHelper($m, 'MapInt32Message', 1, new TestMessage_Sub());
+ self::kvUpdateHelper($m, 'MapInt32Message', 1, new Sub());
$m->getMapInt32Message()[1]->SetA(36);
}
public static function setTestMessage2(TestMessage $m)
{
- $sub = new TestMessage_Sub();
+ $sub = new Sub();
$m->setOptionalInt32(-142);
$m->setOptionalInt64(-143);
@@ -168,7 +168,7 @@ class TestUtil
self::appendHelper($m, 'RepeatedString', 'aa');
self::appendHelper($m, 'RepeatedBytes', 'bb');
self::appendHelper($m, 'RepeatedEnum', TestEnum::TWO);
- self::appendHelper($m, 'RepeatedMessage', new TestMessage_Sub());
+ self::appendHelper($m, 'RepeatedMessage', new Sub());
$m->getRepeatedMessage()[0]->setA(134);
self::kvUpdateHelper($m, 'MapInt32Int32', -62, -162);
@@ -187,7 +187,7 @@ class TestUtil
self::kvUpdateHelper($m, 'MapStringString', 'e', 'ee');
self::kvUpdateHelper($m, 'MapInt32Bytes', 1, 'ff');
self::kvUpdateHelper($m, 'MapInt32Enum', 1, TestEnum::TWO);
- self::kvUpdateHelper($m, 'MapInt32Message', 1, new TestMessage_Sub());
+ self::kvUpdateHelper($m, 'MapInt32Message', 1, new Sub());
$m->getMapInt32Message()[1]->SetA(136);
self::kvUpdateHelper($m, 'MapInt32Int32', -162, -162);
@@ -206,7 +206,7 @@ class TestUtil
self::kvUpdateHelper($m, 'MapStringString', 'ee', 'ee');
self::kvUpdateHelper($m, 'MapInt32Bytes', 2, 'ff');
self::kvUpdateHelper($m, 'MapInt32Enum', 2, TestEnum::TWO);
- self::kvUpdateHelper($m, 'MapInt32Message', 2, new TestMessage_Sub());
+ self::kvUpdateHelper($m, 'MapInt32Message', 2, new Sub());
$m->getMapInt32Message()[2]->SetA(136);
}
diff --git a/php/tests/undefined_test.php b/php/tests/undefined_test.php
index dc6b7086..935d8be7 100644
--- a/php/tests/undefined_test.php
+++ b/php/tests/undefined_test.php
@@ -5,7 +5,7 @@ require_once('test_util.php');
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBType;
use Foo\TestMessage;
-use Foo\TestMessage_Sub;
+use Foo\TestMessage\Sub;
class UndefinedTest extends PHPUnit_Framework_TestCase
{
@@ -35,7 +35,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testInt32AppendMessageFail()
{
$arr = new RepeatedField(GPBType::INT32);
- $arr[] = new TestMessage_Sub();
+ $arr[] = new Sub();
}
/**
@@ -45,7 +45,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
{
$arr = new RepeatedField(GPBType::INT32);
$arr[] = 0;
- $arr[0] = new TestMessage_Sub();
+ $arr[0] = new Sub();
}
/**
@@ -73,7 +73,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testUint32AppendMessageFail()
{
$arr = new RepeatedField(GPBType::UINT32);
- $arr[] = new TestMessage_Sub();
+ $arr[] = new Sub();
}
/**
@@ -83,7 +83,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
{
$arr = new RepeatedField(GPBType::UINT32);
$arr[] = 0;
- $arr[0] = new TestMessage_Sub();
+ $arr[0] = new Sub();
}
/**
@@ -111,7 +111,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testInt64AppendMessageFail()
{
$arr = new RepeatedField(GPBType::INT64);
- $arr[] = new TestMessage_Sub();
+ $arr[] = new Sub();
}
/**
@@ -121,7 +121,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
{
$arr = new RepeatedField(GPBType::INT64);
$arr[] = 0;
- $arr[0] = new TestMessage_Sub();
+ $arr[0] = new Sub();
}
/**
@@ -149,7 +149,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testUint64AppendMessageFail()
{
$arr = new RepeatedField(GPBType::UINT64);
- $arr[] = new TestMessage_Sub();
+ $arr[] = new Sub();
}
/**
@@ -159,7 +159,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
{
$arr = new RepeatedField(GPBType::UINT64);
$arr[] = 0;
- $arr[0] = new TestMessage_Sub();
+ $arr[0] = new Sub();
}
/**
@@ -187,7 +187,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testFloatAppendMessageFail()
{
$arr = new RepeatedField(GPBType::FLOAT);
- $arr[] = new TestMessage_Sub();
+ $arr[] = new Sub();
}
/**
@@ -197,7 +197,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
{
$arr = new RepeatedField(GPBType::FLOAT);
$arr[] = 0.0;
- $arr[0] = new TestMessage_Sub();
+ $arr[0] = new Sub();
}
/**
@@ -225,7 +225,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testDoubleAppendMessageFail()
{
$arr = new RepeatedField(GPBType::DOUBLE);
- $arr[] = new TestMessage_Sub();
+ $arr[] = new Sub();
}
/**
@@ -235,7 +235,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
{
$arr = new RepeatedField(GPBType::DOUBLE);
$arr[] = 0.0;
- $arr[0] = new TestMessage_Sub();
+ $arr[0] = new Sub();
}
/**
@@ -244,7 +244,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testBoolAppendMessageFail()
{
$arr = new RepeatedField(GPBType::BOOL);
- $arr[] = new TestMessage_Sub();
+ $arr[] = new Sub();
}
/**
@@ -254,7 +254,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
{
$arr = new RepeatedField(GPBType::BOOL);
$arr[] = true;
- $arr[0] = new TestMessage_Sub();
+ $arr[0] = new Sub();
}
/**
@@ -263,7 +263,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testStringAppendMessageFail()
{
$arr = new RepeatedField(GPBType::STRING);
- $arr[] = new TestMessage_Sub();
+ $arr[] = new Sub();
}
/**
@@ -273,7 +273,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
{
$arr = new RepeatedField(GPBType::STRING);
$arr[] = 'abc';
- $arr[0] = new TestMessage_Sub();
+ $arr[0] = new Sub();
}
/**
@@ -302,7 +302,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
*/
public function testMessageAppendIntFail()
{
- $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr = new RepeatedField(GPBType::MESSAGE, Sub::class);
$arr[] = 1;
}
@@ -311,8 +311,8 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
*/
public function testMessageSetIntFail()
{
- $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
- $arr[] = new TestMessage_Sub;
+ $arr = new RepeatedField(GPBType::MESSAGE, Sub::class);
+ $arr[] = new Sub;
$arr[0] = 'abc';
}
@@ -321,7 +321,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
*/
public function testMessageAppendStringFail()
{
- $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr = new RepeatedField(GPBType::MESSAGE, Sub::class);
$arr[] = 'abc';
}
@@ -330,8 +330,8 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
*/
public function testMessageSetStringFail()
{
- $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
- $arr[] = new TestMessage_Sub;
+ $arr = new RepeatedField(GPBType::MESSAGE, Sub::class);
+ $arr[] = new Sub;
$arr[0] = 'abc';
}
@@ -340,7 +340,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
*/
public function testMessageAppendOtherMessageFail()
{
- $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr = new RepeatedField(GPBType::MESSAGE, Sub::class);
$arr[] = new TestMessage;
}
@@ -349,7 +349,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
*/
public function testMessageAppendNullFail()
{
- $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr = new RepeatedField(GPBType::MESSAGE, Sub::class);
$null = null;
$arr[] = $null;
}
@@ -359,8 +359,8 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
*/
public function testMessageSetNullFail()
{
- $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
- $arr[] = new TestMessage_Sub();
+ $arr = new RepeatedField(GPBType::MESSAGE, Sub::class);
+ $arr[] = new Sub();
$null = null;
$arr[0] = $null;
}
@@ -397,7 +397,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
{
$arr = new RepeatedField(GPBType::INT32);
$arr[] = 0;
- $arr[new TestMessage_Sub()] = 0;
+ $arr[new Sub()] = 0;
}
/**
@@ -656,7 +656,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testMessageMergeFromInvalidTypeFail()
{
$m = new TestMessage();
- $n = new TestMessage_Sub();
+ $n = new Sub();
$m->mergeFrom($n);
}
@@ -684,7 +684,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testInt32SetMessageKeyFail()
{
$arr = new MapField(GPBType::INT32, GPBType::INT32);
- $arr[new TestMessage_Sub()] = 0;
+ $arr[new Sub()] = 0;
}
/**
@@ -693,7 +693,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testInt32SetMessageValueFail()
{
$arr = new MapField(GPBType::INT32, GPBType::INT32);
- $arr[0] = new TestMessage_Sub();
+ $arr[0] = new Sub();
}
/**
@@ -720,7 +720,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testUint32SetMessageKeyFail()
{
$arr = new MapField(GPBType::UINT32, GPBType::UINT32);
- $arr[new TestMessage_Sub()] = 0;
+ $arr[new Sub()] = 0;
}
/**
@@ -729,7 +729,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testUint32SetMessageValueFail()
{
$arr = new MapField(GPBType::UINT32, GPBType::UINT32);
- $arr[0] = new TestMessage_Sub();
+ $arr[0] = new Sub();
}
/**
@@ -756,7 +756,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testInt64SetMessageKeyFail()
{
$arr = new MapField(GPBType::INT64, GPBType::INT64);
- $arr[new TestMessage_Sub()] = 0;
+ $arr[new Sub()] = 0;
}
/**
@@ -765,7 +765,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testInt64SetMessageValueFail()
{
$arr = new MapField(GPBType::INT64, GPBType::INT64);
- $arr[0] = new TestMessage_Sub();
+ $arr[0] = new Sub();
}
/**
@@ -792,7 +792,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testUint64SetMessageKeyFail()
{
$arr = new MapField(GPBType::UINT64, GPBType::UINT64);
- $arr[new TestMessage_Sub()] = 0;
+ $arr[new Sub()] = 0;
}
/**
@@ -801,7 +801,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testUint64SetMessageValueFail()
{
$arr = new MapField(GPBType::UINT64, GPBType::UINT64);
- $arr[0] = new TestMessage_Sub();
+ $arr[0] = new Sub();
}
/**
@@ -819,7 +819,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testDoubleSetMessageValueFail()
{
$arr = new MapField(GPBType::INT64, GPBType::DOUBLE);
- $arr[0] = new TestMessage_Sub();
+ $arr[0] = new Sub();
}
/**
@@ -828,7 +828,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testBoolSetMessageKeyFail()
{
$arr = new MapField(GPBType::BOOL, GPBType::BOOL);
- $arr[new TestMessage_Sub()] = true;
+ $arr[new Sub()] = true;
}
/**
@@ -837,7 +837,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testBoolSetMessageValueFail()
{
$arr = new MapField(GPBType::BOOL, GPBType::BOOL);
- $arr[true] = new TestMessage_Sub();
+ $arr[true] = new Sub();
}
/**
@@ -864,7 +864,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testStringSetMessageKeyFail()
{
$arr = new MapField(GPBType::STRING, GPBType::STRING);
- $arr[new TestMessage_Sub()] = 'abc';
+ $arr[new Sub()] = 'abc';
}
/**
@@ -873,7 +873,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
public function testStringSetMessageValueFail()
{
$arr = new MapField(GPBType::STRING, GPBType::STRING);
- $arr['abc'] = new TestMessage_Sub();
+ $arr['abc'] = new Sub();
}
/**
@@ -903,13 +903,13 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
{
$arr =
new MapField(GPBType::INT32, GPBType::MESSAGE, TestMessage::class);
- $arr[0] = new TestMessage_Sub();
+ $arr[0] = new Sub();
}
/**
* @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 a7760685..1e8c4f42 100644
--- a/php/tests/well_known_test.php
+++ b/php/tests/well_known_test.php
@@ -14,8 +14,8 @@ use Google\Protobuf\Enum;
use Google\Protobuf\EnumValue;
use Google\Protobuf\Field;
use Google\Protobuf\FieldMask;
-use Google\Protobuf\Field_Cardinality;
-use Google\Protobuf\Field_Kind;
+use Google\Protobuf\Field\Cardinality;
+use Google\Protobuf\Field\Kind;
use Google\Protobuf\FloatValue;
use Google\Protobuf\GPBEmpty;
use Google\Protobuf\Int32Value;
@@ -206,11 +206,11 @@ class WellKnownTest extends TestBase {
{
$m = new Field();
- $m->setKind(Field_Kind::TYPE_DOUBLE);
- $this->assertSame(Field_Kind::TYPE_DOUBLE, $m->getKind());
+ $m->setKind(Kind::TYPE_DOUBLE);
+ $this->assertSame(Kind::TYPE_DOUBLE, $m->getKind());
- $m->setCardinality(Field_Cardinality::CARDINALITY_OPTIONAL);
- $this->assertSame(Field_Cardinality::CARDINALITY_OPTIONAL, $m->getCardinality());
+ $m->setCardinality(Cardinality::CARDINALITY_OPTIONAL);
+ $this->assertSame(Cardinality::CARDINALITY_OPTIONAL, $m->getCardinality());
$m->setNumber(1);
$this->assertSame(1, $m->getNumber());
diff --git a/post_process_dist.sh b/post_process_dist.sh
index eb5f584d..5b14de67 100755
--- a/post_process_dist.sh
+++ b/post_process_dist.sh
@@ -27,7 +27,7 @@ fi
set -ex
-LANGUAGES="cpp csharp java javanano js objectivec python ruby php all"
+LANGUAGES="cpp csharp java js objectivec python ruby php all"
BASENAME=`basename $1 .tar.gz`
VERSION=${BASENAME:9}
diff --git a/protobuf.bzl b/protobuf.bzl
index 6aed44a4..8bbd0564 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
@@ -45,8 +47,11 @@ def _CcSrcs(srcs, use_grpc_plugin=False):
def _CcOuts(srcs, use_grpc_plugin=False):
return _CcHdrs(srcs, use_grpc_plugin) + _CcSrcs(srcs, use_grpc_plugin)
-def _PyOuts(srcs):
- return [s[:-len(".proto")] + "_pb2.py" for s in srcs]
+def _PyOuts(srcs, use_grpc_plugin=False):
+ ret = [s[:-len(".proto")] + "_pb2.py" for s in srcs]
+ if use_grpc_plugin:
+ ret += [s[:-len(".proto")] + "_pb2_grpc.py" for s in srcs]
+ return ret
def _RelativeOutputPath(path, include, dest=""):
if include == None:
@@ -171,10 +176,10 @@ def cc_proto_library(
deps=[],
cc_libs=[],
include=None,
- protoc="//:protoc",
+ protoc="@com_google_protobuf//:protoc",
internal_bootstrap_hack=False,
use_grpc_plugin=False,
- default_runtime="//:protobuf",
+ default_runtime="@com_google_protobuf//:protobuf",
**kargs):
"""Bazel rule to create a C++ protobuf library from proto source files
@@ -263,8 +268,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:
@@ -317,8 +322,8 @@ def py_proto_library(
py_libs=[],
py_extra_srcs=[],
include=None,
- default_runtime="//:protobuf_python",
- protoc="//:protoc",
+ default_runtime="@com_google_protobuf//:protobuf_python",
+ protoc="@com_google_protobuf//:protoc",
use_grpc_plugin=False,
**kargs):
"""Bazel rule to create a Python protobuf library from proto source files
@@ -344,7 +349,7 @@ def py_proto_library(
**kargs: other keyword arguments that are passed to cc_library.
"""
- outs = _PyOuts(srcs)
+ outs = _PyOuts(srcs, use_grpc_plugin)
includes = []
if include != None:
@@ -408,7 +413,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/Dockerfile b/protoc-artifacts/Dockerfile
index 43e6863c..c346586b 100644
--- a/protoc-artifacts/Dockerfile
+++ b/protoc-artifacts/Dockerfile
@@ -11,7 +11,9 @@ RUN yum install -y git \
libtool \
glibc-static.i686 \
glibc-devel \
- glibc-devel.i686
+ glibc-devel.i686 \
+ && \
+ yum clean all
# Install Java 8
RUN wget -q --no-cookies --no-check-certificate \
@@ -27,15 +29,17 @@ RUN wget -q http://apache.cs.utah.edu/maven/maven-3/3.3.9/binaries/apache-maven-
ENV PATH /var/local/apache-maven-3.3.9/bin:$PATH
# Install GCC 4.7 to support -static-libstdc++
-RUN wget http://people.centos.org/tru/devtools-1.1/devtools-1.1.repo -P /etc/yum.repos.d
-RUN bash -c 'echo "enabled=1" >> /etc/yum.repos.d/devtools-1.1.repo'
-RUN bash -c "sed -e 's/\$basearch/i386/g' /etc/yum.repos.d/devtools-1.1.repo > /etc/yum.repos.d/devtools-i386-1.1.repo"
-RUN sed -e 's/testing-/testing-i386-/g' -i /etc/yum.repos.d/devtools-i386-1.1.repo
-RUN rpm --rebuilddb && yum install -y devtoolset-1.1 \
+RUN wget http://people.centos.org/tru/devtools-1.1/devtools-1.1.repo -P /etc/yum.repos.d && \
+ bash -c 'echo "enabled=1" >> /etc/yum.repos.d/devtools-1.1.repo' && \
+ bash -c "sed -e 's/\$basearch/i386/g' /etc/yum.repos.d/devtools-1.1.repo > /etc/yum.repos.d/devtools-i386-1.1.repo" && \
+ sed -e 's/testing-/testing-i386-/g' -i /etc/yum.repos.d/devtools-i386-1.1.repo && \
+ rpm --rebuilddb && \
+ yum install -y devtoolset-1.1 \
devtoolset-1.1-libstdc++-devel \
- devtoolset-1.1-libstdc++-devel.i686
+ devtoolset-1.1-libstdc++-devel.i686 && \
+ yum clean all
-RUN git clone --depth 1 https://github.com/google/protobuf.git
+COPY scl-enable-devtoolset.sh /var/local/
# Start in devtoolset environment that uses GCC 4.7
-CMD ["scl", "enable", "devtoolset-1.1", "bash"]
+ENTRYPOINT ["/var/local/scl-enable-devtoolset.sh"]
diff --git a/protoc-artifacts/README.md b/protoc-artifacts/README.md
index ba3ca018..dcaec987 100644
--- a/protoc-artifacts/README.md
+++ b/protoc-artifacts/README.md
@@ -140,10 +140,14 @@ $ docker build -t protoc-artifacts .
To run the image:
```
-$ docker run -it --rm=true protoc-artifacts
+$ docker run -it --rm=true protoc-artifacts bash
```
-The Protobuf repository has been cloned into ``/protobuf``.
+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
+```
### Tips for deploying on Windows
Under Windows the following error may occur: ``gpg: cannot open tty `no tty':
diff --git a/protoc-artifacts/build-protoc.sh b/protoc-artifacts/build-protoc.sh
index fe1dec24..b78abbcf 100755
--- a/protoc-artifacts/build-protoc.sh
+++ b/protoc-artifacts/build-protoc.sh
@@ -81,6 +81,8 @@ checkArch ()
assertEq $format "elf64-x86-64" $LINENO
elif [[ "$ARCH" == aarch_64 ]]; then
assertEq $format "elf64-little" $LINENO
+ elif [[ "$ARCH" == ppcle_64 ]]; then
+ assertEq $format "elf64-powerpcle" $LINENO
else
fail "Unsupported arch: $ARCH"
fi
@@ -124,6 +126,8 @@ checkDependencies ()
white_list="linux-gate\.so\.1\|libpthread\.so\.0\|libm\.so\.6\|libc\.so\.6\|ld-linux\.so\.2"
elif [[ "$ARCH" == x86_64 ]]; then
white_list="linux-vdso\.so\.1\|libpthread\.so\.0\|libm\.so\.6\|libc\.so\.6\|ld-linux-x86-64\.so\.2"
+ elif [[ "$ARCH" == ppcle_64 ]]; then
+ white_list="linux-vdso64\.so\.1\|libpthread\.so\.0\|libm\.so\.6\|libc\.so\.6\|libz\.so\.1\|ld64\.so\.2"
elif [[ "$ARCH" == aarch_64 ]]; then
dump_cmd='objdump -p '"$1"' | grep NEEDED'
white_list="libpthread\.so\.0\|libc\.so\.6\|ld-linux-aarch64\.so\.1"
@@ -193,6 +197,8 @@ elif [[ "$(uname)" == Linux* ]]; then
CXXFLAGS="$CXXFLAGS -m32"
elif [[ "$ARCH" == aarch_64 ]]; then
CONFIGURE_ARGS="$CONFIGURE_ARGS --host=aarch64-linux-gnu"
+ elif [[ "$ARCH" == ppcle_64 ]]; then
+ CXXFLAGS="$CXXFLAGS -m64"
else
fail "Unsupported arch: $ARCH"
fi
diff --git a/protoc-artifacts/build-zip.sh b/protoc-artifacts/build-zip.sh
index f08e2758..26b6cc93 100755
--- a/protoc-artifacts/build-zip.sh
+++ b/protoc-artifacts/build-zip.sh
@@ -13,13 +13,14 @@ Example:
This script will download pre-built protoc or protoc plugin binaries from maven
repository and create .zip packages suitable to be included in the github
release page. If the target is protoc, well-known type .proto files will also be
-included. Each invocation will create 6 zip packages:
+included. Each invocation will create 7 zip packages:
dist/<TARGET>-<VERSION_NUMBER>-win32.zip
dist/<TARGET>-<VERSION_NUMBER>-osx-x86_32.zip
dist/<TARGET>-<VERSION_NUMBER>-osx-x86_64.zip
dist/<TARGET>-<VERSION_NUMBER>-linux-x86_32.zip
dist/<TARGET>-<VERSION_NUMBER>-linux-x86_64.zip
dist/<TARGET>-<VERSION_NUMBER>-linux-aarch_64.zip
+ dist/<TARGET>-<VERSION_NUMBER>-linux-ppcle_64.zip
EOF
exit 1
fi
@@ -35,6 +36,7 @@ declare -a FILE_NAMES=( \
linux-x86_32.zip linux-x86_32.exe \
linux-x86_64.zip linux-x86_64.exe \
linux-aarch_64.zip linux-aarch_64.exe \
+ linux-ppcle_64.zip linux-ppcle_64.exe \
)
# List of all well-known types to be included.
diff --git a/protoc-artifacts/pom.xml b/protoc-artifacts/pom.xml
index 0f9dd9f8..667a0215 100644
--- a/protoc-artifacts/pom.xml
+++ b/protoc-artifacts/pom.xml
@@ -10,7 +10,7 @@
</parent>
<groupId>com.google.protobuf</groupId>
<artifactId>protoc</artifactId>
- <version>3.5.1</version>
+ <version>3.6.0</version>
<packaging>pom</packaging>
<name>Protobuf Compiler</name>
<description>
@@ -37,7 +37,7 @@
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
- <version>1.2.3.Final</version>
+ <version>1.5.0.Final</version>
</extension>
</extensions>
<plugins>
diff --git a/protoc-artifacts/scl-enable-devtoolset.sh b/protoc-artifacts/scl-enable-devtoolset.sh
new file mode 100755
index 00000000..8d9585ea
--- /dev/null
+++ b/protoc-artifacts/scl-enable-devtoolset.sh
@@ -0,0 +1,13 @@
+#!/bin/bash
+set -eu -o pipefail
+
+quote() {
+ local arg
+ for arg in "$@"; do
+ printf "'"
+ printf "%s" "$arg" | sed -e "s/'/'\\\\''/g"
+ printf "' "
+ done
+}
+
+exec scl enable devtoolset-1.1 "$(quote "$@")"
diff --git a/python/README.md b/python/README.md
index 4c194297..4b48225a 100644
--- a/python/README.md
+++ b/python/README.md
@@ -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/google/protobuf/__init__.py b/python/google/protobuf/__init__.py
index 950f9b2d..58a3f040 100755
--- a/python/google/protobuf/__init__.py
+++ b/python/google/protobuf/__init__.py
@@ -30,7 +30,7 @@
# Copyright 2007 Google Inc. All Rights Reserved.
-__version__ = '3.5.1'
+__version__ = '3.6.0'
if __name__ != '__main__':
try:
diff --git a/python/google/protobuf/compiler/__init__.py b/python/google/protobuf/compiler/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/python/google/protobuf/compiler/__init__.py
diff --git a/python/google/protobuf/descriptor.py b/python/google/protobuf/descriptor.py
index 0d35425f..8a9ba3da 100755
--- a/python/google/protobuf/descriptor.py
+++ b/python/google/protobuf/descriptor.py
@@ -34,6 +34,7 @@ file, in types that make this information accessible in Python.
__author__ = 'robinson@google.com (Will Robinson)'
+import threading
import six
from google.protobuf.internal import api_implementation
@@ -72,6 +73,24 @@ else:
DescriptorMetaclass = type
+class _Lock(object):
+ """Wrapper class of threading.Lock(), which is allowed by 'with'."""
+
+ def __new__(cls):
+ self = object.__new__(cls)
+ self._lock = threading.Lock() # pylint: disable=protected-access
+ return self
+
+ def __enter__(self):
+ self._lock.acquire()
+
+ def __exit__(self, exc_type, exc_value, exc_tb):
+ self._lock.release()
+
+
+_lock = threading.Lock()
+
+
class DescriptorBase(six.with_metaclass(DescriptorMetaclass)):
"""Descriptors base class.
@@ -92,16 +111,17 @@ class DescriptorBase(six.with_metaclass(DescriptorMetaclass)):
# subclasses" of this descriptor class.
_C_DESCRIPTOR_CLASS = ()
- def __init__(self, options, options_class_name):
+ def __init__(self, options, serialized_options, options_class_name):
"""Initialize the descriptor given its options message and the name of the
class of the options message. The name of the class is required in case
the options message is None and has to be created.
"""
self._options = options
self._options_class_name = options_class_name
+ self._serialized_options = serialized_options
# Does this descriptor have non-default options?
- self.has_options = options is not None
+ self.has_options = (options is not None) or (serialized_options is not None)
def _SetOptions(self, options, options_class_name):
"""Sets the descriptor's options
@@ -123,14 +143,23 @@ class DescriptorBase(six.with_metaclass(DescriptorMetaclass)):
"""
if self._options:
return self._options
+
from google.protobuf import descriptor_pb2
try:
- options_class = getattr(descriptor_pb2, self._options_class_name)
+ options_class = getattr(descriptor_pb2,
+ self._options_class_name)
except AttributeError:
raise RuntimeError('Unknown options class name %s!' %
(self._options_class_name))
- self._options = options_class()
- return self._options
+
+ with _lock:
+ if self._serialized_options is None:
+ self._options = options_class()
+ else:
+ self._options = _ParseOptions(options_class(),
+ self._serialized_options)
+
+ return self._options
class _NestedDescriptorBase(DescriptorBase):
@@ -138,7 +167,7 @@ class _NestedDescriptorBase(DescriptorBase):
def __init__(self, options, options_class_name, name, full_name,
file, containing_type, serialized_start=None,
- serialized_end=None):
+ serialized_end=None, serialized_options=None):
"""Constructor.
Args:
@@ -157,9 +186,10 @@ class _NestedDescriptorBase(DescriptorBase):
file.serialized_pb that describes this descriptor.
serialized_end: The end index (exclusive) in block in the
file.serialized_pb that describes this descriptor.
+ serialized_options: Protocol message serilized options or None.
"""
super(_NestedDescriptorBase, self).__init__(
- options, options_class_name)
+ options, serialized_options, options_class_name)
self.name = name
# TODO(falk): Add function to calculate full_name instead of having it in
@@ -250,6 +280,7 @@ class Descriptor(_NestedDescriptorBase):
def __new__(cls, name, full_name, filename, containing_type, fields,
nested_types, enum_types, extensions, options=None,
+ serialized_options=None,
is_extendable=True, extension_ranges=None, oneofs=None,
file=None, serialized_start=None, serialized_end=None, # pylint: disable=redefined-builtin
syntax=None):
@@ -261,6 +292,7 @@ class Descriptor(_NestedDescriptorBase):
# name of the argument.
def __init__(self, name, full_name, filename, containing_type, fields,
nested_types, enum_types, extensions, options=None,
+ serialized_options=None,
is_extendable=True, extension_ranges=None, oneofs=None,
file=None, serialized_start=None, serialized_end=None, # pylint: disable=redefined-builtin
syntax=None):
@@ -273,7 +305,7 @@ class Descriptor(_NestedDescriptorBase):
super(Descriptor, self).__init__(
options, 'MessageOptions', name, full_name, file,
containing_type, serialized_start=serialized_start,
- serialized_end=serialized_end)
+ serialized_end=serialized_end, serialized_options=serialized_options)
# We have fields in addition to fields_by_name and fields_by_number,
# so that:
@@ -492,8 +524,9 @@ class FieldDescriptor(DescriptorBase):
def __new__(cls, name, full_name, index, number, type, cpp_type, label,
default_value, message_type, enum_type, containing_type,
is_extension, extension_scope, options=None,
+ serialized_options=None,
has_default_value=True, containing_oneof=None, json_name=None,
- file=None):
+ file=None): # pylint: disable=redefined-builtin
_message.Message._CheckCalledFromGeneratedFile()
if is_extension:
return _message.default_pool.FindExtensionByName(full_name)
@@ -503,8 +536,9 @@ class FieldDescriptor(DescriptorBase):
def __init__(self, name, full_name, index, number, type, cpp_type, label,
default_value, message_type, enum_type, containing_type,
is_extension, extension_scope, options=None,
+ serialized_options=None,
has_default_value=True, containing_oneof=None, json_name=None,
- file=None):
+ file=None): # pylint: disable=redefined-builtin
"""The arguments are as described in the description of FieldDescriptor
attributes above.
@@ -512,7 +546,8 @@ class FieldDescriptor(DescriptorBase):
(to deal with circular references between message types, for example).
Likewise for extension_scope.
"""
- super(FieldDescriptor, self).__init__(options, 'FieldOptions')
+ super(FieldDescriptor, self).__init__(
+ options, serialized_options, 'FieldOptions')
self.name = name
self.full_name = full_name
self.file = file
@@ -598,13 +633,15 @@ class EnumDescriptor(_NestedDescriptorBase):
_C_DESCRIPTOR_CLASS = _message.EnumDescriptor
def __new__(cls, name, full_name, filename, values,
- containing_type=None, options=None, file=None,
+ containing_type=None, options=None,
+ serialized_options=None, file=None, # pylint: disable=redefined-builtin
serialized_start=None, serialized_end=None):
_message.Message._CheckCalledFromGeneratedFile()
return _message.default_pool.FindEnumTypeByName(full_name)
def __init__(self, name, full_name, filename, values,
- containing_type=None, options=None, file=None,
+ containing_type=None, options=None,
+ serialized_options=None, file=None, # pylint: disable=redefined-builtin
serialized_start=None, serialized_end=None):
"""Arguments are as described in the attribute description above.
@@ -614,7 +651,7 @@ class EnumDescriptor(_NestedDescriptorBase):
super(EnumDescriptor, self).__init__(
options, 'EnumOptions', name, full_name, file,
containing_type, serialized_start=serialized_start,
- serialized_end=serialized_end)
+ serialized_end=serialized_end, serialized_options=serialized_options)
self.values = values
for value in self.values:
@@ -650,7 +687,9 @@ class EnumValueDescriptor(DescriptorBase):
if _USE_C_DESCRIPTORS:
_C_DESCRIPTOR_CLASS = _message.EnumValueDescriptor
- def __new__(cls, name, index, number, type=None, options=None):
+ def __new__(cls, name, index, number,
+ type=None, # pylint: disable=redefined-builtin
+ options=None, serialized_options=None):
_message.Message._CheckCalledFromGeneratedFile()
# There is no way we can build a complete EnumValueDescriptor with the
# given parameters (the name of the Enum is not known, for example).
@@ -658,9 +697,12 @@ class EnumValueDescriptor(DescriptorBase):
# constructor, which will ignore it, so returning None is good enough.
return None
- def __init__(self, name, index, number, type=None, options=None):
+ def __init__(self, name, index, number,
+ type=None, # pylint: disable=redefined-builtin
+ options=None, serialized_options=None):
"""Arguments are as described in the attribute description above."""
- super(EnumValueDescriptor, self).__init__(options, 'EnumValueOptions')
+ super(EnumValueDescriptor, self).__init__(
+ options, serialized_options, 'EnumValueOptions')
self.name = name
self.index = index
self.number = number
@@ -685,14 +727,17 @@ class OneofDescriptor(DescriptorBase):
_C_DESCRIPTOR_CLASS = _message.OneofDescriptor
def __new__(
- cls, name, full_name, index, containing_type, fields, options=None):
+ cls, name, full_name, index, containing_type, fields, options=None,
+ serialized_options=None):
_message.Message._CheckCalledFromGeneratedFile()
return _message.default_pool.FindOneofByName(full_name)
def __init__(
- self, name, full_name, index, containing_type, fields, options=None):
+ self, name, full_name, index, containing_type, fields, options=None,
+ serialized_options=None):
"""Arguments are as described in the attribute description above."""
- super(OneofDescriptor, self).__init__(options, 'OneofOptions')
+ super(OneofDescriptor, self).__init__(
+ options, serialized_options, 'OneofOptions')
self.name = name
self.full_name = full_name
self.index = index
@@ -721,17 +766,19 @@ class ServiceDescriptor(_NestedDescriptorBase):
if _USE_C_DESCRIPTORS:
_C_DESCRIPTOR_CLASS = _message.ServiceDescriptor
- def __new__(cls, name, full_name, index, methods, options=None, file=None, # pylint: disable=redefined-builtin
+ def __new__(cls, name, full_name, index, methods, options=None,
+ serialized_options=None, file=None, # pylint: disable=redefined-builtin
serialized_start=None, serialized_end=None):
_message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
return _message.default_pool.FindServiceByName(full_name)
- def __init__(self, name, full_name, index, methods, options=None, file=None,
+ def __init__(self, name, full_name, index, methods, options=None,
+ serialized_options=None, file=None, # pylint: disable=redefined-builtin
serialized_start=None, serialized_end=None):
super(ServiceDescriptor, self).__init__(
options, 'ServiceOptions', name, full_name, file,
None, serialized_start=serialized_start,
- serialized_end=serialized_end)
+ serialized_end=serialized_end, serialized_options=serialized_options)
self.index = index
self.methods = methods
self.methods_by_name = dict((m.name, m) for m in methods)
@@ -772,18 +819,19 @@ class MethodDescriptor(DescriptorBase):
_C_DESCRIPTOR_CLASS = _message.MethodDescriptor
def __new__(cls, name, full_name, index, containing_service,
- input_type, output_type, options=None):
+ input_type, output_type, options=None, serialized_options=None):
_message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
return _message.default_pool.FindMethodByName(full_name)
def __init__(self, name, full_name, index, containing_service,
- input_type, output_type, options=None):
+ input_type, output_type, options=None, serialized_options=None):
"""The arguments are as described in the description of MethodDescriptor
attributes above.
Note that containing_service may be None, and may be set later if necessary.
"""
- super(MethodDescriptor, self).__init__(options, 'MethodOptions')
+ super(MethodDescriptor, self).__init__(
+ options, serialized_options, 'MethodOptions')
self.name = name
self.full_name = full_name
self.index = index
@@ -818,7 +866,8 @@ class FileDescriptor(DescriptorBase):
if _USE_C_DESCRIPTORS:
_C_DESCRIPTOR_CLASS = _message.FileDescriptor
- def __new__(cls, name, package, options=None, serialized_pb=None,
+ def __new__(cls, name, package, options=None,
+ serialized_options=None, serialized_pb=None,
dependencies=None, public_dependencies=None,
syntax=None, pool=None):
# FileDescriptor() is called from various places, not only from generated
@@ -830,11 +879,13 @@ class FileDescriptor(DescriptorBase):
else:
return super(FileDescriptor, cls).__new__(cls)
- def __init__(self, name, package, options=None, serialized_pb=None,
+ def __init__(self, name, package, options=None,
+ serialized_options=None, serialized_pb=None,
dependencies=None, public_dependencies=None,
syntax=None, pool=None):
"""Constructor."""
- super(FileDescriptor, self).__init__(options, 'FileOptions')
+ super(FileDescriptor, self).__init__(
+ options, serialized_options, 'FileOptions')
if pool is None:
from google.protobuf import descriptor_pool
diff --git a/python/google/protobuf/internal/_parameterized.py b/python/google/protobuf/internal/_parameterized.py
index 23a78f03..f2c0b305 100755
--- a/python/google/protobuf/internal/_parameterized.py
+++ b/python/google/protobuf/internal/_parameterized.py
@@ -37,8 +37,8 @@ argument tuples.
A simple example:
- class AdditionExample(parameterized.ParameterizedTestCase):
- @parameterized.Parameters(
+ class AdditionExample(parameterized.TestCase):
+ @parameterized.parameters(
(1, 2, 3),
(4, 5, 9),
(1, 1, 3))
@@ -54,8 +54,8 @@ fail due to an assertion error (1 + 1 != 3).
Parameters for invididual test cases can be tuples (with positional parameters)
or dictionaries (with named parameters):
- class AdditionExample(parameterized.ParameterizedTestCase):
- @parameterized.Parameters(
+ class AdditionExample(parameterized.TestCase):
+ @parameterized.parameters(
{'op1': 1, 'op2': 2, 'result': 3},
{'op1': 4, 'op2': 5, 'result': 9},
)
@@ -77,13 +77,13 @@ stay the same across several invocations, object representations like
'<__main__.Foo object at 0x23d8610>'
are turned into '<__main__.Foo>'. For even more descriptive names,
-especially in test logs, you can use the NamedParameters decorator. In
+especially in test logs, you can use the named_parameters decorator. In
this case, only tuples are supported, and the first parameters has to
be a string (or an object that returns an apt name when converted via
str()):
- class NamedExample(parameterized.ParameterizedTestCase):
- @parameterized.NamedParameters(
+ class NamedExample(parameterized.TestCase):
+ @parameterized.named_parameters(
('Normal', 'aa', 'aaa', True),
('EmptyPrefix', '', 'abc', True),
('BothEmpty', '', '', True))
@@ -103,13 +103,13 @@ from the command line:
Parameterized Classes
=====================
If invocation arguments are shared across test methods in a single
-ParameterizedTestCase class, instead of decorating all test methods
+TestCase class, instead of decorating all test methods
individually, the class itself can be decorated:
- @parameterized.Parameters(
+ @parameterized.parameters(
(1, 2, 3)
(4, 5, 9))
- class ArithmeticTest(parameterized.ParameterizedTestCase):
+ class ArithmeticTest(parameterized.TestCase):
def testAdd(self, arg1, arg2, result):
self.assertEqual(arg1 + arg2, result)
@@ -122,8 +122,8 @@ If parameters should be shared across several test cases, or are dynamically
created from other sources, a single non-tuple iterable can be passed into
the decorator. This iterable will be used to obtain the test cases:
- class AdditionExample(parameterized.ParameterizedTestCase):
- @parameterized.Parameters(
+ class AdditionExample(parameterized.TestCase):
+ @parameterized.parameters(
c.op1, c.op2, c.result for c in testcases
)
def testAddition(self, op1, op2, result):
@@ -135,8 +135,8 @@ Single-Argument Test Methods
If a test method takes only one argument, the single argument does not need to
be wrapped into a tuple:
- class NegativeNumberExample(parameterized.ParameterizedTestCase):
- @parameterized.Parameters(
+ class NegativeNumberExample(parameterized.TestCase):
+ @parameterized.parameters(
-1, -3, -4, -5
)
def testIsNegative(self, arg):
@@ -212,7 +212,7 @@ class _ParameterizedTestIter(object):
def __call__(self, *args, **kwargs):
raise RuntimeError('You appear to be running a parameterized test case '
'without having inherited from parameterized.'
- 'ParameterizedTestCase. This is bad because none of '
+ 'TestCase. This is bad because none of '
'your test cases are actually being run.')
def __iter__(self):
@@ -306,7 +306,7 @@ def _ParameterDecorator(naming_type, testcases):
return _Apply
-def Parameters(*testcases):
+def parameters(*testcases): # pylint: disable=invalid-name
"""A decorator for creating parameterized tests.
See the module docstring for a usage example.
@@ -321,7 +321,7 @@ def Parameters(*testcases):
return _ParameterDecorator(_ARGUMENT_REPR, testcases)
-def NamedParameters(*testcases):
+def named_parameters(*testcases): # pylint: disable=invalid-name
"""A decorator for creating parameterized tests.
See the module docstring for a usage example. The first element of
@@ -348,7 +348,7 @@ class TestGeneratorMetaclass(type):
up as tests by the unittest framework.
In general, it is supposed to be used in conjunction with the
- Parameters decorator.
+ parameters decorator.
"""
def __new__(mcs, class_name, bases, dct):
@@ -385,8 +385,8 @@ def _UpdateClassDictForParamTestCase(dct, id_suffix, name, iterator):
id_suffix[new_name] = getattr(func, '__x_extra_id__', '')
-class ParameterizedTestCase(unittest.TestCase):
- """Base class for test cases using the Parameters decorator."""
+class TestCase(unittest.TestCase):
+ """Base class for test cases using the parameters decorator."""
__metaclass__ = TestGeneratorMetaclass
def _OriginalName(self):
@@ -409,10 +409,10 @@ class ParameterizedTestCase(unittest.TestCase):
self._id_suffix.get(self._testMethodName, ''))
-def CoopParameterizedTestCase(other_base_class):
+def CoopTestCase(other_base_class):
"""Returns a new base class with a cooperative metaclass base.
- This enables the ParameterizedTestCase to be used in combination
+ This enables the TestCase to be used in combination
with other base classes that have custom metaclasses, such as
mox.MoxTestBase.
@@ -425,7 +425,7 @@ def CoopParameterizedTestCase(other_base_class):
from google3.testing.pybase import parameterized
- class ExampleTest(parameterized.CoopParameterizedTestCase(mox.MoxTestBase)):
+ class ExampleTest(parameterized.CoopTestCase(mox.MoxTestBase)):
...
Args:
@@ -439,5 +439,5 @@ def CoopParameterizedTestCase(other_base_class):
(other_base_class.__metaclass__,
TestGeneratorMetaclass), {})
return metaclass(
- 'CoopParameterizedTestCase',
- (other_base_class, ParameterizedTestCase), {})
+ 'CoopTestCase',
+ (other_base_class, TestCase), {})
diff --git a/python/google/protobuf/internal/api_implementation.py b/python/google/protobuf/internal/api_implementation.py
index 553fcdb6..ab9e7812 100755
--- a/python/google/protobuf/internal/api_implementation.py
+++ b/python/google/protobuf/internal/api_implementation.py
@@ -66,10 +66,13 @@ if _api_version < 0: # Still unspecified?
from google.protobuf.internal import use_pure_python
del use_pure_python # Avoids a pylint error and namespace pollution.
except ImportError:
- if _proto_extension_modules_exist_in_build:
- if sys.version_info[0] >= 3: # Python 3 defaults to C++ impl v2.
- _api_version = 2
- # TODO(b/17427486): Make Python 2 default to C++ impl v2.
+ # TODO(b/74017912): It's unsafe to enable :use_fast_cpp_protos by default;
+ # it can cause data loss if you have any Python-only extensions to any
+ # message passed back and forth with C++ code.
+ #
+ # TODO(b/17427486): Once that bug is fixed, we want to make both Python 2
+ # and Python 3 default to `_api_version = 2` (C++ implementation V2).
+ pass
_default_implementation_type = (
'python' if _api_version <= 0 else 'cpp')
diff --git a/python/google/protobuf/internal/encoder.py b/python/google/protobuf/internal/encoder.py
index dc7a8ce8..0d1f49dd 100755
--- a/python/google/protobuf/internal/encoder.py
+++ b/python/google/protobuf/internal/encoder.py
@@ -372,7 +372,7 @@ def MapSizer(field_descriptor, is_message_map):
def _VarintEncoder():
"""Return an encoder for a basic varint value (does not include tag)."""
- def EncodeVarint(write, value, unused_deterministic):
+ def EncodeVarint(write, value, unused_deterministic=None):
bits = value & 0x7f
value >>= 7
while value:
@@ -388,7 +388,7 @@ def _SignedVarintEncoder():
"""Return an encoder for a basic signed varint value (does not include
tag)."""
- def EncodeSignedVarint(write, value, unused_deterministic):
+ def EncodeSignedVarint(write, value, unused_deterministic=None):
if value < 0:
value += (1 << 64)
bits = value & 0x7f
@@ -524,14 +524,14 @@ def _StructPackEncoder(wire_type, format):
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_type)
- def EncodeRepeatedField(write, value, unused_deterministic):
+ def EncodeRepeatedField(write, value, unused_deterministic=None):
for element in value:
write(tag_bytes)
write(local_struct_pack(format, element))
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_type)
- def EncodeField(write, value, unused_deterministic):
+ def EncodeField(write, value, unused_deterministic=None):
write(tag_bytes)
return write(local_struct_pack(format, value))
return EncodeField
@@ -595,7 +595,7 @@ def _FloatingPointEncoder(wire_type, format):
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_type)
- def EncodeRepeatedField(write, value, unused_deterministic):
+ def EncodeRepeatedField(write, value, unused_deterministic=None):
for element in value:
write(tag_bytes)
try:
@@ -605,7 +605,7 @@ def _FloatingPointEncoder(wire_type, format):
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_type)
- def EncodeField(write, value, unused_deterministic):
+ def EncodeField(write, value, unused_deterministic=None):
write(tag_bytes)
try:
write(local_struct_pack(format, value))
@@ -662,7 +662,7 @@ def BoolEncoder(field_number, is_repeated, is_packed):
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT)
- def EncodeRepeatedField(write, value, unused_deterministic):
+ def EncodeRepeatedField(write, value, unused_deterministic=None):
for element in value:
write(tag_bytes)
if element:
@@ -672,7 +672,7 @@ def BoolEncoder(field_number, is_repeated, is_packed):
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT)
- def EncodeField(write, value, unused_deterministic):
+ def EncodeField(write, value, unused_deterministic=None):
write(tag_bytes)
if value:
return write(true_byte)
diff --git a/python/google/protobuf/internal/json_format_test.py b/python/google/protobuf/internal/json_format_test.py
index 19182b7f..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.')
@@ -983,6 +980,18 @@ class JsonFormatTest(JsonFormatBase):
self.assertEqual('{\n"int32Value": 12345\n}',
json_format.MessageToJson(message, indent=0))
+ def testFormatEnumsAsInts(self):
+ message = json_format_proto3_pb2.TestMessage()
+ message.enum_value = json_format_proto3_pb2.BAR
+ message.repeated_enum_value.append(json_format_proto3_pb2.FOO)
+ message.repeated_enum_value.append(json_format_proto3_pb2.BAR)
+ self.assertEqual(json.loads('{\n'
+ ' "enumValue": 1,\n'
+ ' "repeatedEnumValue": [0, 1]\n'
+ '}\n'),
+ json.loads(json_format.MessageToJson(
+ message, use_integers_for_enums=True)))
+
def testParseDict(self):
expected = 12345
js_dict = {'int32Value': expected}
diff --git a/python/google/protobuf/internal/message_test.py b/python/google/protobuf/internal/message_test.py
index 8dae6377..61a56a67 100755
--- a/python/google/protobuf/internal/message_test.py
+++ b/python/google/protobuf/internal/message_test.py
@@ -99,7 +99,7 @@ def IsNegInf(val):
BaseTestCase = testing_refleaks.BaseTestCase
-@_parameterized.NamedParameters(
+@_parameterized.named_parameters(
('_proto2', unittest_pb2),
('_proto3', unittest_proto3_arena_pb2))
class MessageTest(BaseTestCase):
@@ -1694,6 +1694,33 @@ class Proto3Test(BaseTestCase):
with self.assertRaises(TypeError):
del msg2.map_int32_foreign_message['']
+ def testMapMergeFrom(self):
+ msg = map_unittest_pb2.TestMap()
+ msg.map_int32_int32[12] = 34
+ msg.map_int32_int32[56] = 78
+ msg.map_int64_int64[22] = 33
+ msg.map_int32_foreign_message[111].c = 5
+ msg.map_int32_foreign_message[222].c = 10
+
+ msg2 = map_unittest_pb2.TestMap()
+ msg2.map_int32_int32[12] = 55
+ msg2.map_int64_int64[88] = 99
+ msg2.map_int32_foreign_message[222].c = 15
+ msg2.map_int32_foreign_message[222].d = 20
+
+ msg2.map_int32_int32.MergeFrom(msg.map_int32_int32)
+ self.assertEqual(34, msg2.map_int32_int32[12])
+ self.assertEqual(78, msg2.map_int32_int32[56])
+
+ msg2.map_int64_int64.MergeFrom(msg.map_int64_int64)
+ self.assertEqual(33, msg2.map_int64_int64[22])
+ self.assertEqual(99, msg2.map_int64_int64[88])
+
+ msg2.map_int32_foreign_message.MergeFrom(msg.map_int32_foreign_message)
+ self.assertEqual(5, msg2.map_int32_foreign_message[111].c)
+ self.assertEqual(10, msg2.map_int32_foreign_message[222].c)
+ self.assertFalse(msg2.map_int32_foreign_message[222].HasField('d'))
+
def testMergeFromBadType(self):
msg = map_unittest_pb2.TestMap()
with self.assertRaisesRegexp(
diff --git a/python/google/protobuf/internal/no_package.proto b/python/google/protobuf/internal/no_package.proto
new file mode 100644
index 00000000..3546dcc3
--- /dev/null
+++ b/python/google/protobuf/internal/no_package.proto
@@ -0,0 +1,10 @@
+syntax = "proto2";
+
+enum NoPackageEnum {
+ NO_PACKAGE_VALUE_0 = 0;
+ NO_PACKAGE_VALUE_1 = 1;
+}
+
+message NoPackageMessage {
+ optional NoPackageEnum no_package_enum = 1;
+}
diff --git a/python/google/protobuf/internal/text_format_test.py b/python/google/protobuf/internal/text_format_test.py
index ed3445f2..237a2d50 100755
--- a/python/google/protobuf/internal/text_format_test.py
+++ b/python/google/protobuf/internal/text_format_test.py
@@ -48,6 +48,7 @@ except ImportError:
from google.protobuf.internal import _parameterized
+from google.protobuf import any_pb2
from google.protobuf import any_test_pb2
from google.protobuf import map_unittest_pb2
from google.protobuf import unittest_mset_pb2
@@ -99,7 +100,7 @@ class TextFormatBase(unittest.TestCase):
return text
-@_parameterized.Parameters((unittest_pb2), (unittest_proto3_arena_pb2))
+@_parameterized.parameters((unittest_pb2), (unittest_proto3_arena_pb2))
class TextFormatTest(TextFormatBase):
def testPrintExotic(self, message_module):
@@ -369,6 +370,7 @@ class TextFormatTest(TextFormatBase):
def testParseRepeatedScalarShortFormat(self, message_module):
message = message_module.TestAllTypes()
text = ('repeated_int64: [100, 200];\n'
+ 'repeated_int64: []\n'
'repeated_int64: 300,\n'
'repeated_string: ["one", "two"];\n')
text_format.Parse(text, message)
@@ -524,20 +526,68 @@ class OnlyWorksWithProto2RightNowTests(TextFormatBase):
def testPrintInIndexOrder(self):
message = unittest_pb2.TestFieldOrderings()
- message.my_string = '115'
+ # Fields are listed in index order instead of field number.
+ message.my_string = 'str'
message.my_int = 101
message.my_float = 111
message.optional_nested_message.oo = 0
message.optional_nested_message.bb = 1
+ message.Extensions[unittest_pb2.my_extension_string] = 'ext_str0'
+ # Extensions are listed based on the order of extension number.
+ # Extension number 12.
+ message.Extensions[unittest_pb2.TestExtensionOrderings2.
+ test_ext_orderings2].my_string = 'ext_str2'
+ # Extension number 13.
+ message.Extensions[unittest_pb2.TestExtensionOrderings1.
+ test_ext_orderings1].my_string = 'ext_str1'
+ # Extension number 14.
+ message.Extensions[
+ unittest_pb2.TestExtensionOrderings2.TestExtensionOrderings3.
+ test_ext_orderings3].my_string = 'ext_str3'
+
+ # Print in index order.
self.CompareToGoldenText(
- self.RemoveRedundantZeros(text_format.MessageToString(
- message, use_index_order=True)),
- 'my_string: \"115\"\nmy_int: 101\nmy_float: 111\n'
- 'optional_nested_message {\n oo: 0\n bb: 1\n}\n')
+ self.RemoveRedundantZeros(
+ text_format.MessageToString(message, use_index_order=True)),
+ 'my_string: "str"\n'
+ 'my_int: 101\n'
+ 'my_float: 111\n'
+ 'optional_nested_message {\n'
+ ' oo: 0\n'
+ ' bb: 1\n'
+ '}\n'
+ '[protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] {\n'
+ ' my_string: "ext_str2"\n'
+ '}\n'
+ '[protobuf_unittest.TestExtensionOrderings1.test_ext_orderings1] {\n'
+ ' my_string: "ext_str1"\n'
+ '}\n'
+ '[protobuf_unittest.TestExtensionOrderings2.TestExtensionOrderings3'
+ '.test_ext_orderings3] {\n'
+ ' my_string: "ext_str3"\n'
+ '}\n'
+ '[protobuf_unittest.my_extension_string]: "ext_str0"\n')
+ # By default, print in field number order.
self.CompareToGoldenText(
self.RemoveRedundantZeros(text_format.MessageToString(message)),
- 'my_int: 101\nmy_string: \"115\"\nmy_float: 111\n'
- 'optional_nested_message {\n bb: 1\n oo: 0\n}\n')
+ 'my_int: 101\n'
+ 'my_string: "str"\n'
+ '[protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] {\n'
+ ' my_string: "ext_str2"\n'
+ '}\n'
+ '[protobuf_unittest.TestExtensionOrderings1.test_ext_orderings1] {\n'
+ ' my_string: "ext_str1"\n'
+ '}\n'
+ '[protobuf_unittest.TestExtensionOrderings2.TestExtensionOrderings3'
+ '.test_ext_orderings3] {\n'
+ ' my_string: "ext_str3"\n'
+ '}\n'
+ '[protobuf_unittest.my_extension_string]: "ext_str0"\n'
+ 'my_float: 111\n'
+ 'optional_nested_message {\n'
+ ' bb: 1\n'
+ ' oo: 0\n'
+ '}\n')
def testMergeLinesGolden(self):
opened = self.ReadGolden('text_format_unittest_data_oneof_implemented.txt')
@@ -970,15 +1020,26 @@ class Proto2Tests(TextFormatBase):
'"protobuf_unittest.optional_int32_extension" extensions.'),
text_format.Parse, text, message)
- def testParseDuplicateNestedMessageScalars(self):
+ def testParseDuplicateMessages(self):
message = unittest_pb2.TestAllTypes()
text = ('optional_nested_message { bb: 1 } '
'optional_nested_message { bb: 2 }')
six.assertRaisesRegex(self, text_format.ParseError, (
- '1:65 : Message type "protobuf_unittest.TestAllTypes.NestedMessage" '
- 'should not have multiple "bb" fields.'), text_format.Parse, text,
+ '1:59 : Message type "protobuf_unittest.TestAllTypes" '
+ 'should not have multiple "optional_nested_message" fields.'),
+ text_format.Parse, text,
message)
+ def testParseDuplicateExtensionMessages(self):
+ message = unittest_pb2.TestAllExtensions()
+ text = ('[protobuf_unittest.optional_nested_message_extension]: {} '
+ '[protobuf_unittest.optional_nested_message_extension]: {}')
+ six.assertRaisesRegex(self, text_format.ParseError, (
+ '1:114 : Message type "protobuf_unittest.TestAllExtensions" '
+ 'should not have multiple '
+ '"protobuf_unittest.optional_nested_message_extension" extensions.'),
+ text_format.Parse, text, message)
+
def testParseDuplicateScalars(self):
message = unittest_pb2.TestAllTypes()
text = ('optional_int32: 42 ' 'optional_int32: 67')
@@ -1065,6 +1126,14 @@ class Proto3Tests(unittest.TestCase):
' }\n'
'}\n')
+ def testTopAnyMessage(self):
+ packed_msg = unittest_pb2.OneString()
+ msg = any_pb2.Any()
+ msg.Pack(packed_msg)
+ text = text_format.MessageToString(msg)
+ other_msg = text_format.Parse(text, any_pb2.Any())
+ self.assertEqual(msg, other_msg)
+
def testPrintMessageExpandAnyRepeated(self):
packed_message = unittest_pb2.OneString()
message = any_test_pb2.TestAny()
@@ -1489,7 +1558,7 @@ class TokenizerTest(unittest.TestCase):
# Tests for pretty printer functionality.
-@_parameterized.Parameters((unittest_pb2), (unittest_proto3_arena_pb2))
+@_parameterized.parameters((unittest_pb2), (unittest_proto3_arena_pb2))
class PrettyPrinterTest(TextFormatBase):
def testPrettyPrintNoMatch(self, message_module):
diff --git a/python/google/protobuf/internal/well_known_types.py b/python/google/protobuf/internal/well_known_types.py
index 3573770b..37a65cfa 100644
--- a/python/google/protobuf/internal/well_known_types.py
+++ b/python/google/protobuf/internal/well_known_types.py
@@ -375,6 +375,9 @@ def _CheckDurationValid(seconds, nanos):
raise Error(
'Duration is not valid: Nanos {0} must be in range '
'[-999999999, 999999999].'.format(nanos))
+ if (nanos < 0 and seconds > 0) or (nanos > 0 and seconds < 0):
+ raise Error(
+ 'Duration is not valid: Sign mismatch.')
def _RoundTowardZero(value, divider):
@@ -649,9 +652,10 @@ def _MergeMessage(
raise ValueError('Error: Field {0} in message {1} is not a singular '
'message field and cannot have sub-fields.'.format(
name, source_descriptor.full_name))
- _MergeMessage(
- child, getattr(source, name), getattr(destination, name),
- replace_message, replace_repeated)
+ if source.HasField(name):
+ _MergeMessage(
+ child, getattr(source, name), getattr(destination, name),
+ replace_message, replace_repeated)
continue
if field.label == FieldDescriptor.LABEL_REPEATED:
if replace_repeated:
diff --git a/python/google/protobuf/internal/well_known_types_test.py b/python/google/protobuf/internal/well_known_types_test.py
index 573bc37d..965940b2 100644
--- a/python/google/protobuf/internal/well_known_types_test.py
+++ b/python/google/protobuf/internal/well_known_types_test.py
@@ -345,6 +345,12 @@ class TimeUtilTest(TimeUtilTestBase):
r'Duration is not valid\: Nanos 1000000000 must be in range'
r' \[-999999999\, 999999999\].',
message.ToJsonString)
+ message.seconds = -1
+ message.nanos = 1
+ self.assertRaisesRegexp(
+ well_known_types.Error,
+ r'Duration is not valid\: Sign mismatch.',
+ message.ToJsonString)
class FieldMaskTest(unittest.TestCase):
@@ -599,6 +605,16 @@ class FieldMaskTest(unittest.TestCase):
self.assertEqual(1, len(nested_dst.payload.repeated_int32))
self.assertEqual(1234, nested_dst.payload.repeated_int32[0])
+ # Test Merge oneof field.
+ new_msg = unittest_pb2.TestOneof2()
+ dst = unittest_pb2.TestOneof2()
+ dst.foo_message.qux_int = 1
+ mask = field_mask_pb2.FieldMask()
+ mask.FromJsonString('fooMessage,fooLazyMessage.quxInt')
+ mask.MergeMessage(new_msg, dst)
+ self.assertTrue(dst.HasField('foo_message'))
+ self.assertFalse(dst.HasField('foo_lazy_message'))
+
def testMergeErrors(self):
src = unittest_pb2.TestAllTypes()
dst = unittest_pb2.TestAllTypes()
diff --git a/python/google/protobuf/json_format.py b/python/google/protobuf/json_format.py
index 878291db..58c94a47 100644
--- a/python/google/protobuf/json_format.py
+++ b/python/google/protobuf/json_format.py
@@ -42,21 +42,28 @@ Simple usage example:
__author__ = 'jieluo@google.com (Jie Luo)'
+# pylint: disable=g-statement-before-imports,g-import-not-at-top
try:
from collections import OrderedDict
except ImportError:
- from ordereddict import OrderedDict #PY26
+ from ordereddict import OrderedDict # PY26
+# pylint: enable=g-statement-before-imports,g-import-not-at-top
+
import base64
import json
import math
+
+from operator import methodcaller
+
import re
-import six
import sys
-from operator import methodcaller
+import six
+
from google.protobuf import descriptor
from google.protobuf import symbol_database
+
_TIMESTAMPFOMAT = '%Y-%m-%dT%H:%M:%S'
_INT_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_INT32,
descriptor.FieldDescriptor.CPPTYPE_UINT32,
@@ -93,7 +100,8 @@ def MessageToJson(message,
including_default_value_fields=False,
preserving_proto_field_name=False,
indent=2,
- sort_keys=False):
+ sort_keys=False,
+ use_integers_for_enums=False):
"""Converts protobuf message to JSON format.
Args:
@@ -108,18 +116,21 @@ def MessageToJson(message,
indent: The JSON object will be pretty-printed with this indent level.
An indent level of 0 or negative will only insert newlines.
sort_keys: If True, then the output will be sorted by field names.
+ use_integers_for_enums: If true, print integers instead of enum names.
Returns:
A string containing the JSON formatted protocol buffer message.
"""
printer = _Printer(including_default_value_fields,
- preserving_proto_field_name)
+ preserving_proto_field_name,
+ use_integers_for_enums)
return printer.ToJsonString(message, indent, sort_keys)
def MessageToDict(message,
including_default_value_fields=False,
- preserving_proto_field_name=False):
+ preserving_proto_field_name=False,
+ use_integers_for_enums=False):
"""Converts protobuf message to a dictionary.
When the dictionary is encoded to JSON, it conforms to proto3 JSON spec.
@@ -133,12 +144,14 @@ def MessageToDict(message,
preserving_proto_field_name: If True, use the original proto field
names as defined in the .proto file. If False, convert the field
names to lowerCamelCase.
+ use_integers_for_enums: If true, print integers instead of enum names.
Returns:
A dict representation of the protocol buffer message.
"""
printer = _Printer(including_default_value_fields,
- preserving_proto_field_name)
+ preserving_proto_field_name,
+ use_integers_for_enums)
# pylint: disable=protected-access
return printer._MessageToJsonObject(message)
@@ -154,9 +167,11 @@ class _Printer(object):
def __init__(self,
including_default_value_fields=False,
- preserving_proto_field_name=False):
+ preserving_proto_field_name=False,
+ use_integers_for_enums=False):
self.including_default_value_fields = including_default_value_fields
self.preserving_proto_field_name = preserving_proto_field_name
+ self.use_integers_for_enums = use_integers_for_enums
def ToJsonString(self, message, indent, sort_keys):
js = self._MessageToJsonObject(message)
@@ -247,6 +262,8 @@ class _Printer(object):
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
return self._MessageToJsonObject(value)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
+ if self.use_integers_for_enums:
+ return value
enum_value = field.enum_type.values_by_number.get(value, None)
if enum_value is not None:
return enum_value.name
@@ -379,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)
diff --git a/python/google/protobuf/proto_api.h b/python/google/protobuf/proto_api.h
new file mode 100644
index 00000000..5c076d23
--- /dev/null
+++ b/python/google/protobuf/proto_api.h
@@ -0,0 +1,92 @@
+// 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 PYTHON_GOOGLE_PROTOBUF_PROTO_API_H__
+#define PYTHON_GOOGLE_PROTOBUF_PROTO_API_H__
+
+#include <Python.h>
+
+namespace google {
+namespace protobuf {
+
+class Message;
+
+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 // PYTHON_GOOGLE_PROTOBUF_PROTO_API_H__
diff --git a/python/google/protobuf/pyext/descriptor.cc b/python/google/protobuf/pyext/descriptor.cc
index 6bbc92b9..8af0cb12 100644
--- a/python/google/protobuf/pyext/descriptor.cc
+++ b/python/google/protobuf/pyext/descriptor.cc
@@ -193,39 +193,36 @@ const FileDescriptor* GetFileDescriptor(const MethodDescriptor* descriptor) {
// Always returns a new reference.
template<class DescriptorClass>
static PyObject* GetOrBuildOptions(const DescriptorClass *descriptor) {
- // Options (and their extensions) are completely resolved in the proto file
- // containing the descriptor.
- PyDescriptorPool* pool = GetDescriptorPool_FromPool(
+ // Options are cached in the pool that owns the descriptor.
+ // First search in the cache.
+ PyDescriptorPool* caching_pool = GetDescriptorPool_FromPool(
GetFileDescriptor(descriptor)->pool());
-
hash_map<const void*, PyObject*>* descriptor_options =
- pool->descriptor_options;
- // First search in the cache.
+ caching_pool->descriptor_options;
if (descriptor_options->find(descriptor) != descriptor_options->end()) {
PyObject *value = (*descriptor_options)[descriptor];
Py_INCREF(value);
return value;
}
+ // Similar to the C++ implementation, we return an Options object from the
+ // default (generated) factory, so that client code know that they can use
+ // extensions from generated files:
+ // d.GetOptions().Extensions[some_pb2.extension]
+ //
+ // The consequence is that extensions not defined in the default pool won't
+ // be available. If needed, we could add an optional 'message_factory'
+ // parameter to the GetOptions() function.
+ PyMessageFactory* message_factory =
+ GetDefaultDescriptorPool()->py_message_factory;
+
// Build the Options object: get its Python class, and make a copy of the C++
// read-only instance.
const Message& options(descriptor->options());
const Descriptor *message_type = options.GetDescriptor();
- PyMessageFactory* message_factory = pool->py_message_factory;
- CMessageClass* message_class = message_factory::GetMessageClass(
+ CMessageClass* message_class = message_factory::GetOrCreateMessageClass(
message_factory, message_type);
if (message_class == NULL) {
- // The Options message was not found in the current DescriptorPool.
- // This means that the pool cannot contain any extensions to the Options
- // message either, so falling back to the basic pool we can only increase
- // the chances of successfully parsing the options.
- PyErr_Clear();
- pool = GetDefaultDescriptorPool();
- message_factory = pool->py_message_factory;
- message_class = message_factory::GetMessageClass(
- message_factory, message_type);
- }
- if (message_class == NULL) {
PyErr_Format(PyExc_TypeError, "Could not retrieve class for Options: %s",
message_type->full_name().c_str());
return NULL;
@@ -253,7 +250,8 @@ static PyObject* GetOrBuildOptions(const DescriptorClass *descriptor) {
options.SerializeToString(&serialized);
io::CodedInputStream input(
reinterpret_cast<const uint8*>(serialized.c_str()), serialized.size());
- input.SetExtensionRegistry(pool->pool, message_factory->message_factory);
+ input.SetExtensionRegistry(message_factory->pool->pool,
+ message_factory->message_factory);
bool success = cmsg->message->MergePartialFromCodedStream(&input);
if (!success) {
PyErr_Format(PyExc_ValueError, "Error parsing Options message");
@@ -569,6 +567,11 @@ static int SetOptions(PyBaseDescriptor *self, PyObject *value,
return CheckCalledFromGeneratedFile("_options");
}
+static int SetSerializedOptions(PyBaseDescriptor *self, PyObject *value,
+ void *closure) {
+ return CheckCalledFromGeneratedFile("_serialized_options");
+}
+
static PyObject* CopyToProto(PyBaseDescriptor *self, PyObject *target) {
return CopyToPythonProto<DescriptorProto>(_GetDescriptor(self), target);
}
@@ -628,6 +631,8 @@ static PyGetSetDef Getters[] = {
{ "is_extendable", (getter)IsExtendable, (setter)NULL},
{ "has_options", (getter)GetHasOptions, (setter)SetHasOptions, "Has Options"},
{ "_options", (getter)NULL, (setter)SetOptions, "Options"},
+ { "_serialized_options", (getter)NULL, (setter)SetSerializedOptions,
+ "Serialized Options"},
{ "syntax", (getter)GetSyntax, (setter)NULL, "Syntax"},
{NULL}
};
@@ -790,7 +795,7 @@ static PyObject* GetDefaultValue(PyBaseDescriptor *self, void *closure) {
break;
}
case FieldDescriptor::CPPTYPE_STRING: {
- string value = _GetDescriptor(self)->default_value_string();
+ const string& value = _GetDescriptor(self)->default_value_string();
result = ToStringObject(_GetDescriptor(self), value);
break;
}
@@ -902,6 +907,10 @@ static int SetOptions(PyBaseDescriptor *self, PyObject *value,
return CheckCalledFromGeneratedFile("_options");
}
+static int SetSerializedOptions(PyBaseDescriptor *self, PyObject *value,
+ void *closure) {
+ return CheckCalledFromGeneratedFile("_serialized_options");
+}
static PyGetSetDef Getters[] = {
{ "full_name", (getter)GetFullName, NULL, "Full name"},
@@ -931,6 +940,8 @@ static PyGetSetDef Getters[] = {
"Containing oneof"},
{ "has_options", (getter)GetHasOptions, (setter)SetHasOptions, "Has Options"},
{ "_options", (getter)NULL, (setter)SetOptions, "Options"},
+ { "_serialized_options", (getter)NULL, (setter)SetSerializedOptions,
+ "Serialized Options"},
{NULL}
};
@@ -1060,6 +1071,11 @@ static int SetOptions(PyBaseDescriptor *self, PyObject *value,
return CheckCalledFromGeneratedFile("_options");
}
+static int SetSerializedOptions(PyBaseDescriptor *self, PyObject *value,
+ void *closure) {
+ return CheckCalledFromGeneratedFile("_serialized_options");
+}
+
static PyObject* CopyToProto(PyBaseDescriptor *self, PyObject *target) {
return CopyToPythonProto<EnumDescriptorProto>(_GetDescriptor(self), target);
}
@@ -1084,6 +1100,8 @@ static PyGetSetDef Getters[] = {
"Containing type"},
{ "has_options", (getter)GetHasOptions, (setter)SetHasOptions, "Has Options"},
{ "_options", (getter)NULL, (setter)SetOptions, "Options"},
+ { "_serialized_options", (getter)NULL, (setter)SetSerializedOptions,
+ "Serialized Options"},
{NULL}
};
@@ -1184,6 +1202,10 @@ static int SetOptions(PyBaseDescriptor *self, PyObject *value,
return CheckCalledFromGeneratedFile("_options");
}
+static int SetSerializedOptions(PyBaseDescriptor *self, PyObject *value,
+ void *closure) {
+ return CheckCalledFromGeneratedFile("_serialized_options");
+}
static PyGetSetDef Getters[] = {
{ "name", (getter)GetName, NULL, "name"},
@@ -1193,6 +1215,8 @@ static PyGetSetDef Getters[] = {
{ "has_options", (getter)GetHasOptions, (setter)SetHasOptions, "Has Options"},
{ "_options", (getter)NULL, (setter)SetOptions, "Options"},
+ { "_serialized_options", (getter)NULL, (setter)SetSerializedOptions,
+ "Serialized Options"},
{NULL}
};
@@ -1335,6 +1359,11 @@ static int SetOptions(PyFileDescriptor *self, PyObject *value,
return CheckCalledFromGeneratedFile("_options");
}
+static int SetSerializedOptions(PyFileDescriptor *self, PyObject *value,
+ void *closure) {
+ return CheckCalledFromGeneratedFile("_serialized_options");
+}
+
static PyObject* GetSyntax(PyFileDescriptor *self, void *closure) {
return PyString_InternFromString(
FileDescriptor::SyntaxName(_GetDescriptor(self)->syntax()));
@@ -1360,6 +1389,8 @@ static PyGetSetDef Getters[] = {
{ "has_options", (getter)GetHasOptions, (setter)SetHasOptions, "Has Options"},
{ "_options", (getter)NULL, (setter)SetOptions, "Options"},
+ { "_serialized_options", (getter)NULL, (setter)SetSerializedOptions,
+ "Serialized Options"},
{ "syntax", (getter)GetSyntax, (setter)NULL, "Syntax"},
{NULL}
};
@@ -1505,6 +1536,11 @@ static int SetOptions(PyBaseDescriptor *self, PyObject *value,
return CheckCalledFromGeneratedFile("_options");
}
+static int SetSerializedOptions(PyBaseDescriptor *self, PyObject *value,
+ void *closure) {
+ return CheckCalledFromGeneratedFile("_serialized_options");
+}
+
static PyGetSetDef Getters[] = {
{ "name", (getter)GetName, NULL, "Name"},
{ "full_name", (getter)GetFullName, NULL, "Full name"},
@@ -1513,6 +1549,8 @@ static PyGetSetDef Getters[] = {
{ "containing_type", (getter)GetContainingType, NULL, "Containing type"},
{ "has_options", (getter)GetHasOptions, (setter)SetHasOptions, "Has Options"},
{ "_options", (getter)NULL, (setter)SetOptions, "Options"},
+ { "_serialized_options", (getter)NULL, (setter)SetSerializedOptions,
+ "Serialized Options"},
{ "fields", (getter)GetFields, NULL, "Fields"},
{NULL}
};
diff --git a/python/google/protobuf/pyext/descriptor_pool.cc b/python/google/protobuf/pyext/descriptor_pool.cc
index 16f4d49d..95882aeb 100644
--- a/python/google/protobuf/pyext/descriptor_pool.cc
+++ b/python/google/protobuf/pyext/descriptor_pool.cc
@@ -149,7 +149,8 @@ static PyObject* New(PyTypeObject* type,
PyDescriptorPool_NewWithDatabase(database));
}
-static void Dealloc(PyDescriptorPool* self) {
+static void Dealloc(PyObject* pself) {
+ PyDescriptorPool* self = reinterpret_cast<PyDescriptorPool*>(pself);
descriptor_pool_map.erase(self->pool);
Py_CLEAR(self->py_message_factory);
for (hash_map<const void*, PyObject*>::iterator it =
@@ -163,7 +164,7 @@ static void Dealloc(PyDescriptorPool* self) {
Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
-PyObject* FindMessageByName(PyDescriptorPool* self, PyObject* arg) {
+static PyObject* FindMessageByName(PyObject* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
@@ -171,7 +172,8 @@ PyObject* FindMessageByName(PyDescriptorPool* self, PyObject* arg) {
}
const Descriptor* message_descriptor =
- self->pool->FindMessageTypeByName(string(name, name_size));
+ reinterpret_cast<PyDescriptorPool*>(self)->pool->FindMessageTypeByName(
+ string(name, name_size));
if (message_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find message %.200s", name);
@@ -184,7 +186,7 @@ PyObject* FindMessageByName(PyDescriptorPool* self, PyObject* arg) {
-PyObject* FindFileByName(PyDescriptorPool* self, PyObject* arg) {
+static PyObject* FindFileByName(PyObject* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
@@ -192,7 +194,8 @@ PyObject* FindFileByName(PyDescriptorPool* self, PyObject* arg) {
}
const FileDescriptor* file_descriptor =
- self->pool->FindFileByName(string(name, name_size));
+ reinterpret_cast<PyDescriptorPool*>(self)->pool->FindFileByName(
+ string(name, name_size));
if (file_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find file %.200s", name);
return NULL;
@@ -218,6 +221,10 @@ PyObject* FindFieldByName(PyDescriptorPool* self, PyObject* arg) {
return PyFieldDescriptor_FromDescriptor(field_descriptor);
}
+static PyObject* FindFieldByNameMethod(PyObject* self, PyObject* arg) {
+ return FindFieldByName(reinterpret_cast<PyDescriptorPool*>(self), arg);
+}
+
PyObject* FindExtensionByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
@@ -235,6 +242,10 @@ PyObject* FindExtensionByName(PyDescriptorPool* self, PyObject* arg) {
return PyFieldDescriptor_FromDescriptor(field_descriptor);
}
+static PyObject* FindExtensionByNameMethod(PyObject* self, PyObject* arg) {
+ return FindExtensionByName(reinterpret_cast<PyDescriptorPool*>(self), arg);
+}
+
PyObject* FindEnumTypeByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
@@ -252,6 +263,10 @@ PyObject* FindEnumTypeByName(PyDescriptorPool* self, PyObject* arg) {
return PyEnumDescriptor_FromDescriptor(enum_descriptor);
}
+static PyObject* FindEnumTypeByNameMethod(PyObject* self, PyObject* arg) {
+ return FindEnumTypeByName(reinterpret_cast<PyDescriptorPool*>(self), arg);
+}
+
PyObject* FindOneofByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
@@ -269,7 +284,11 @@ PyObject* FindOneofByName(PyDescriptorPool* self, PyObject* arg) {
return PyOneofDescriptor_FromDescriptor(oneof_descriptor);
}
-PyObject* FindServiceByName(PyDescriptorPool* self, PyObject* arg) {
+static PyObject* FindOneofByNameMethod(PyObject* self, PyObject* arg) {
+ return FindOneofByName(reinterpret_cast<PyDescriptorPool*>(self), arg);
+}
+
+static PyObject* FindServiceByName(PyObject* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
@@ -277,7 +296,8 @@ PyObject* FindServiceByName(PyDescriptorPool* self, PyObject* arg) {
}
const ServiceDescriptor* service_descriptor =
- self->pool->FindServiceByName(string(name, name_size));
+ reinterpret_cast<PyDescriptorPool*>(self)->pool->FindServiceByName(
+ string(name, name_size));
if (service_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find service %.200s", name);
return NULL;
@@ -286,7 +306,7 @@ PyObject* FindServiceByName(PyDescriptorPool* self, PyObject* arg) {
return PyServiceDescriptor_FromDescriptor(service_descriptor);
}
-PyObject* FindMethodByName(PyDescriptorPool* self, PyObject* arg) {
+static PyObject* FindMethodByName(PyObject* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
@@ -294,7 +314,8 @@ PyObject* FindMethodByName(PyDescriptorPool* self, PyObject* arg) {
}
const MethodDescriptor* method_descriptor =
- self->pool->FindMethodByName(string(name, name_size));
+ reinterpret_cast<PyDescriptorPool*>(self)->pool->FindMethodByName(
+ string(name, name_size));
if (method_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find method %.200s", name);
return NULL;
@@ -303,7 +324,7 @@ PyObject* FindMethodByName(PyDescriptorPool* self, PyObject* arg) {
return PyMethodDescriptor_FromDescriptor(method_descriptor);
}
-PyObject* FindFileContainingSymbol(PyDescriptorPool* self, PyObject* arg) {
+static PyObject* FindFileContainingSymbol(PyObject* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
@@ -311,7 +332,8 @@ PyObject* FindFileContainingSymbol(PyDescriptorPool* self, PyObject* arg) {
}
const FileDescriptor* file_descriptor =
- self->pool->FindFileContainingSymbol(string(name, name_size));
+ reinterpret_cast<PyDescriptorPool*>(self)->pool->FindFileContainingSymbol(
+ string(name, name_size));
if (file_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find symbol %.200s", name);
return NULL;
@@ -320,7 +342,7 @@ PyObject* FindFileContainingSymbol(PyDescriptorPool* self, PyObject* arg) {
return PyFileDescriptor_FromDescriptor(file_descriptor);
}
-PyObject* FindExtensionByNumber(PyDescriptorPool* self, PyObject* args) {
+static PyObject* FindExtensionByNumber(PyObject* self, PyObject* args) {
PyObject* message_descriptor;
int number;
if (!PyArg_ParseTuple(args, "Oi", &message_descriptor, &number)) {
@@ -333,7 +355,8 @@ PyObject* FindExtensionByNumber(PyDescriptorPool* self, PyObject* args) {
}
const FieldDescriptor* extension_descriptor =
- self->pool->FindExtensionByNumber(descriptor, number);
+ reinterpret_cast<PyDescriptorPool*>(self)->pool->FindExtensionByNumber(
+ descriptor, number);
if (extension_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find extension %d", number);
return NULL;
@@ -342,14 +365,15 @@ PyObject* FindExtensionByNumber(PyDescriptorPool* self, PyObject* args) {
return PyFieldDescriptor_FromDescriptor(extension_descriptor);
}
-PyObject* FindAllExtensions(PyDescriptorPool* self, PyObject* arg) {
+static PyObject* FindAllExtensions(PyObject* self, PyObject* arg) {
const Descriptor* descriptor = PyMessageDescriptor_AsDescriptor(arg);
if (descriptor == NULL) {
return NULL;
}
std::vector<const FieldDescriptor*> extensions;
- self->pool->FindAllExtensions(descriptor, &extensions);
+ reinterpret_cast<PyDescriptorPool*>(self)->pool->FindAllExtensions(
+ descriptor, &extensions);
ScopedPyObjectPtr result(PyList_New(extensions.size()));
if (result == NULL) {
@@ -374,14 +398,15 @@ PyObject* FindAllExtensions(PyDescriptorPool* self, PyObject* arg) {
// call a function that will just be a no-op?
// TODO(amauryfa): Need to investigate further.
-PyObject* AddFileDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
+static PyObject* AddFileDescriptor(PyObject* self, PyObject* descriptor) {
const FileDescriptor* file_descriptor =
PyFileDescriptor_AsDescriptor(descriptor);
if (!file_descriptor) {
return NULL;
}
if (file_descriptor !=
- self->pool->FindFileByName(file_descriptor->name())) {
+ reinterpret_cast<PyDescriptorPool*>(self)->pool->FindFileByName(
+ file_descriptor->name())) {
PyErr_Format(PyExc_ValueError,
"The file descriptor %s does not belong to this pool",
file_descriptor->name().c_str());
@@ -390,14 +415,15 @@ PyObject* AddFileDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
Py_RETURN_NONE;
}
-PyObject* AddDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
+static PyObject* AddDescriptor(PyObject* self, PyObject* descriptor) {
const Descriptor* message_descriptor =
PyMessageDescriptor_AsDescriptor(descriptor);
if (!message_descriptor) {
return NULL;
}
if (message_descriptor !=
- self->pool->FindMessageTypeByName(message_descriptor->full_name())) {
+ reinterpret_cast<PyDescriptorPool*>(self)->pool->FindMessageTypeByName(
+ message_descriptor->full_name())) {
PyErr_Format(PyExc_ValueError,
"The message descriptor %s does not belong to this pool",
message_descriptor->full_name().c_str());
@@ -406,14 +432,15 @@ PyObject* AddDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
Py_RETURN_NONE;
}
-PyObject* AddEnumDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
+static PyObject* AddEnumDescriptor(PyObject* self, PyObject* descriptor) {
const EnumDescriptor* enum_descriptor =
PyEnumDescriptor_AsDescriptor(descriptor);
if (!enum_descriptor) {
return NULL;
}
if (enum_descriptor !=
- self->pool->FindEnumTypeByName(enum_descriptor->full_name())) {
+ reinterpret_cast<PyDescriptorPool*>(self)->pool->FindEnumTypeByName(
+ enum_descriptor->full_name())) {
PyErr_Format(PyExc_ValueError,
"The enum descriptor %s does not belong to this pool",
enum_descriptor->full_name().c_str());
@@ -422,14 +449,15 @@ PyObject* AddEnumDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
Py_RETURN_NONE;
}
-PyObject* AddExtensionDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
+static PyObject* AddExtensionDescriptor(PyObject* self, PyObject* descriptor) {
const FieldDescriptor* extension_descriptor =
PyFieldDescriptor_AsDescriptor(descriptor);
if (!extension_descriptor) {
return NULL;
}
if (extension_descriptor !=
- self->pool->FindExtensionByName(extension_descriptor->full_name())) {
+ reinterpret_cast<PyDescriptorPool*>(self)->pool->FindExtensionByName(
+ extension_descriptor->full_name())) {
PyErr_Format(PyExc_ValueError,
"The extension descriptor %s does not belong to this pool",
extension_descriptor->full_name().c_str());
@@ -438,14 +466,15 @@ PyObject* AddExtensionDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
Py_RETURN_NONE;
}
-PyObject* AddServiceDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
+static PyObject* AddServiceDescriptor(PyObject* self, PyObject* descriptor) {
const ServiceDescriptor* service_descriptor =
PyServiceDescriptor_AsDescriptor(descriptor);
if (!service_descriptor) {
return NULL;
}
if (service_descriptor !=
- self->pool->FindServiceByName(service_descriptor->full_name())) {
+ reinterpret_cast<PyDescriptorPool*>(self)->pool->FindServiceByName(
+ service_descriptor->full_name())) {
PyErr_Format(PyExc_ValueError,
"The service descriptor %s does not belong to this pool",
service_descriptor->full_name().c_str());
@@ -481,7 +510,8 @@ class BuildFileErrorCollector : public DescriptorPool::ErrorCollector {
bool had_errors;
};
-PyObject* AddSerializedFile(PyDescriptorPool* self, PyObject* serialized_pb) {
+static PyObject* AddSerializedFile(PyObject* pself, PyObject* serialized_pb) {
+ PyDescriptorPool* self = reinterpret_cast<PyDescriptorPool*>(pself);
char* message_type;
Py_ssize_t message_len;
@@ -529,7 +559,7 @@ PyObject* AddSerializedFile(PyDescriptorPool* self, PyObject* serialized_pb) {
descriptor, serialized_pb);
}
-PyObject* Add(PyDescriptorPool* self, PyObject* file_descriptor_proto) {
+static PyObject* Add(PyObject* self, PyObject* file_descriptor_proto) {
ScopedPyObjectPtr serialized_pb(
PyObject_CallMethod(file_descriptor_proto, "SerializeToString", NULL));
if (serialized_pb == NULL) {
@@ -539,46 +569,46 @@ PyObject* Add(PyDescriptorPool* self, PyObject* file_descriptor_proto) {
}
static PyMethodDef Methods[] = {
- { "Add", (PyCFunction)Add, METH_O,
+ { "Add", Add, METH_O,
"Adds the FileDescriptorProto and its types to this pool." },
- { "AddSerializedFile", (PyCFunction)AddSerializedFile, METH_O,
+ { "AddSerializedFile", AddSerializedFile, METH_O,
"Adds a serialized FileDescriptorProto to this pool." },
// TODO(amauryfa): Understand why the Python implementation differs from
// this one, ask users to use another API and deprecate these functions.
- { "AddFileDescriptor", (PyCFunction)AddFileDescriptor, METH_O,
+ { "AddFileDescriptor", AddFileDescriptor, METH_O,
"No-op. Add() must have been called before." },
- { "AddDescriptor", (PyCFunction)AddDescriptor, METH_O,
+ { "AddDescriptor", AddDescriptor, METH_O,
"No-op. Add() must have been called before." },
- { "AddEnumDescriptor", (PyCFunction)AddEnumDescriptor, METH_O,
+ { "AddEnumDescriptor", AddEnumDescriptor, METH_O,
"No-op. Add() must have been called before." },
- { "AddExtensionDescriptor", (PyCFunction)AddExtensionDescriptor, METH_O,
+ { "AddExtensionDescriptor", AddExtensionDescriptor, METH_O,
"No-op. Add() must have been called before." },
- { "AddServiceDescriptor", (PyCFunction)AddServiceDescriptor, METH_O,
+ { "AddServiceDescriptor", AddServiceDescriptor, METH_O,
"No-op. Add() must have been called before." },
- { "FindFileByName", (PyCFunction)FindFileByName, METH_O,
+ { "FindFileByName", FindFileByName, METH_O,
"Searches for a file descriptor by its .proto name." },
- { "FindMessageTypeByName", (PyCFunction)FindMessageByName, METH_O,
+ { "FindMessageTypeByName", FindMessageByName, METH_O,
"Searches for a message descriptor by full name." },
- { "FindFieldByName", (PyCFunction)FindFieldByName, METH_O,
+ { "FindFieldByName", FindFieldByNameMethod, METH_O,
"Searches for a field descriptor by full name." },
- { "FindExtensionByName", (PyCFunction)FindExtensionByName, METH_O,
+ { "FindExtensionByName", FindExtensionByNameMethod, METH_O,
"Searches for extension descriptor by full name." },
- { "FindEnumTypeByName", (PyCFunction)FindEnumTypeByName, METH_O,
+ { "FindEnumTypeByName", FindEnumTypeByNameMethod, METH_O,
"Searches for enum type descriptor by full name." },
- { "FindOneofByName", (PyCFunction)FindOneofByName, METH_O,
+ { "FindOneofByName", FindOneofByNameMethod, METH_O,
"Searches for oneof descriptor by full name." },
- { "FindServiceByName", (PyCFunction)FindServiceByName, METH_O,
+ { "FindServiceByName", FindServiceByName, METH_O,
"Searches for service descriptor by full name." },
- { "FindMethodByName", (PyCFunction)FindMethodByName, METH_O,
+ { "FindMethodByName", FindMethodByName, METH_O,
"Searches for method descriptor by full name." },
- { "FindFileContainingSymbol", (PyCFunction)FindFileContainingSymbol, METH_O,
+ { "FindFileContainingSymbol", FindFileContainingSymbol, METH_O,
"Gets the FileDescriptor containing the specified symbol." },
- { "FindExtensionByNumber", (PyCFunction)FindExtensionByNumber, METH_VARARGS,
+ { "FindExtensionByNumber", FindExtensionByNumber, METH_VARARGS,
"Gets the extension descriptor for the given number." },
- { "FindAllExtensions", (PyCFunction)FindAllExtensions, METH_O,
+ { "FindAllExtensions", FindAllExtensions, METH_O,
"Gets all known extensions of the given message descriptor." },
{NULL}
};
@@ -590,7 +620,7 @@ PyTypeObject PyDescriptorPool_Type = {
FULL_MODULE_NAME ".DescriptorPool", // tp_name
sizeof(PyDescriptorPool), // tp_basicsize
0, // tp_itemsize
- (destructor)cdescriptor_pool::Dealloc, // tp_dealloc
+ cdescriptor_pool::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
diff --git a/python/google/protobuf/pyext/extension_dict.cc b/python/google/protobuf/pyext/extension_dict.cc
index 6830b10d..018b5c2c 100644
--- a/python/google/protobuf/pyext/extension_dict.cc
+++ b/python/google/protobuf/pyext/extension_dict.cc
@@ -33,9 +33,6 @@
#include <google/protobuf/pyext/extension_dict.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
diff --git a/python/google/protobuf/pyext/extension_dict.h b/python/google/protobuf/pyext/extension_dict.h
index 65b87862..0de2c4ee 100644
--- a/python/google/protobuf/pyext/extension_dict.h
+++ b/python/google/protobuf/pyext/extension_dict.h
@@ -37,9 +37,8 @@
#include <Python.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
+
+#include <google/protobuf/pyext/message.h>
namespace google {
namespace protobuf {
@@ -47,16 +46,8 @@ namespace protobuf {
class Message;
class FieldDescriptor;
-#ifdef _SHARED_PTR_H
-using std::shared_ptr;
-#else
-using internal::shared_ptr;
-#endif
-
namespace python {
-struct CMessage;
-
typedef struct ExtensionDict {
PyObject_HEAD;
@@ -64,7 +55,7 @@ typedef struct ExtensionDict {
// 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.
- shared_ptr<Message> owner;
+ CMessage::OwnerRef owner;
// Weak reference to parent message. Used to make sure
// the parent is writable when an extension field is modified.
diff --git a/python/google/protobuf/pyext/map_container.cc b/python/google/protobuf/pyext/map_container.cc
index abd15b77..6d7ee285 100644
--- a/python/google/protobuf/pyext/map_container.cc
+++ b/python/google/protobuf/pyext/map_container.cc
@@ -33,9 +33,6 @@
#include <google/protobuf/pyext/map_container.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -76,7 +73,7 @@ class MapReflectionFriend {
struct MapIterator {
PyObject_HEAD;
- google::protobuf::scoped_ptr< ::google::protobuf::MapIterator> iter;
+ std::unique_ptr<::google::protobuf::MapIterator> iter;
// A pointer back to the container, so we can notice changes to the version.
// We own a ref on this.
@@ -94,7 +91,7 @@ struct MapIterator {
// as this iterator does. This is solely for the benefit of the MapIterator
// destructor -- we should never actually access the iterator in this state
// except to delete it.
- shared_ptr<Message> owner;
+ CMessage::OwnerRef owner;
// The version of the map when we took the iterator to it.
//
@@ -339,6 +336,24 @@ PyObject* GetEntryClass(PyObject* _self) {
return reinterpret_cast<PyObject*>(message_class);
}
+PyObject* MergeFrom(PyObject* _self, PyObject* arg) {
+ MapContainer* self = GetMap(_self);
+ MapContainer* other_map = GetMap(arg);
+ Message* message = self->GetMutableMessage();
+ const Message* other_message = other_map->message;
+ const Reflection* reflection = message->GetReflection();
+ const Reflection* other_reflection = other_message->GetReflection();
+ int count = other_reflection->FieldSize(
+ *other_message, other_map->parent_field_descriptor);
+ for (int i = 0 ; i < count; i ++) {
+ reflection->AddMessage(message, self->parent_field_descriptor)->MergeFrom(
+ other_reflection->GetRepeatedMessage(
+ *other_message, other_map->parent_field_descriptor, i));
+ }
+ self->version++;
+ Py_RETURN_NONE;
+}
+
PyObject* MapReflectionFriend::Contains(PyObject* _self, PyObject* key) {
MapContainer* self = GetMap(_self);
@@ -535,6 +550,8 @@ static PyMethodDef ScalarMapMethods[] = {
"Gets the value for the given key if present, or otherwise a default" },
{ "GetEntryClass", (PyCFunction)GetEntryClass, METH_NOARGS,
"Return the class used to build Entries of (key, value) pairs." },
+ { "MergeFrom", (PyCFunction)MergeFrom, METH_O,
+ "Merges a map into the current map." },
/*
{ "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
"Makes a deep copy of the class." },
@@ -810,6 +827,8 @@ static PyMethodDef MessageMapMethods[] = {
"Alias for getitem, useful to make explicit that the map is mutated." },
{ "GetEntryClass", (PyCFunction)GetEntryClass, METH_NOARGS,
"Return the class used to build Entries of (key, value) pairs." },
+ { "MergeFrom", (PyCFunction)MergeFrom, METH_O,
+ "Merges a map into the current map." },
/*
{ "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
"Makes a deep copy of the class." },
diff --git a/python/google/protobuf/pyext/map_container.h b/python/google/protobuf/pyext/map_container.h
index 615657b0..111fafbf 100644
--- a/python/google/protobuf/pyext/map_container.h
+++ b/python/google/protobuf/pyext/map_container.h
@@ -34,27 +34,18 @@
#include <Python.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
+#include <google/protobuf/pyext/message.h>
namespace google {
namespace protobuf {
class Message;
-#ifdef _SHARED_PTR_H
-using std::shared_ptr;
-#else
-using internal::shared_ptr;
-#endif
-
namespace python {
-struct CMessage;
struct CMessageClass;
// This struct is used directly for ScalarMap, and is the base class of
@@ -66,7 +57,7 @@ struct MapContainer {
// proto tree. Every Python MapContainer 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.
- shared_ptr<Message> owner;
+ CMessage::OwnerRef owner;
// Pointer to the C++ Message that contains this container. The
// MapContainer does not own this pointer.
@@ -99,9 +90,7 @@ struct MapContainer {
int Release();
// Set the owner field of self and any children of self.
- void SetOwner(const shared_ptr<Message>& new_owner) {
- owner = new_owner;
- }
+ void SetOwner(const CMessage::OwnerRef& new_owner) { owner = new_owner; }
};
struct MessageMapContainer : public MapContainer {
diff --git a/python/google/protobuf/pyext/message.cc b/python/google/protobuf/pyext/message.cc
index f515b560..53736b9c 100644
--- a/python/google/protobuf/pyext/message.cc
+++ b/python/google/protobuf/pyext/message.cc
@@ -35,9 +35,6 @@
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
#include <vector>
#include <structmember.h> // A Python header file.
@@ -658,7 +655,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 == NULL)) {
+ if (GOOGLE_PREDICT_FALSE(casted == nullptr)) {
// Propagate existing error.
return false;
}
@@ -683,7 +680,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 == NULL)) {
+ if (GOOGLE_PREDICT_FALSE(casted == nullptr)) {
// Propagate existing error.
return false;
}
@@ -830,7 +827,8 @@ bool CheckAndSetString(
return true;
}
-PyObject* ToStringObject(const FieldDescriptor* descriptor, string value) {
+PyObject* ToStringObject(const FieldDescriptor* descriptor,
+ const string& value) {
if (descriptor->type() != FieldDescriptor::TYPE_STRING) {
return PyBytes_FromStringAndSize(value.c_str(), value.length());
}
@@ -1318,6 +1316,8 @@ CMessage* NewEmptyMessage(CMessageClass* type) {
return NULL;
}
+ // Use "placement new" syntax to initialize the C++ object.
+ new (&self->owner) CMessage::OwnerRef(NULL);
self->message = NULL;
self->parent = NULL;
self->parent_field_descriptor = NULL;
@@ -1414,7 +1414,7 @@ static void Dealloc(CMessage* self) {
Py_CLEAR(self->extensions);
Py_CLEAR(self->composite_fields);
- self->owner.reset();
+ self->owner.~ThreadUnsafeSharedPtr<Message>();
Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
@@ -1616,9 +1616,10 @@ PyObject* HasExtension(CMessage* self, PyObject* extension) {
// * Clear the weak references from the released container to the
// parent.
-struct SetOwnerVisitor : public ChildVisitor {
+class SetOwnerVisitor : public ChildVisitor {
+ public:
// new_owner must outlive this object.
- explicit SetOwnerVisitor(const shared_ptr<Message>& new_owner)
+ explicit SetOwnerVisitor(const CMessage::OwnerRef& new_owner)
: new_owner_(new_owner) {}
int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
@@ -1642,11 +1643,11 @@ struct SetOwnerVisitor : public ChildVisitor {
}
private:
- const shared_ptr<Message>& new_owner_;
+ const CMessage::OwnerRef& new_owner_;
};
// Change the owner of this CMessage and all its children, recursively.
-int SetOwner(CMessage* self, const shared_ptr<Message>& new_owner) {
+int SetOwner(CMessage* self, const CMessage::OwnerRef& new_owner) {
self->owner = new_owner;
if (ForEachCompositeField(self, SetOwnerVisitor(new_owner)) == -1)
return -1;
@@ -1679,7 +1680,7 @@ int ReleaseSubMessage(CMessage* self,
const FieldDescriptor* field_descriptor,
CMessage* child_cmessage) {
// Release the Message
- shared_ptr<Message> released_message(ReleaseMessage(
+ CMessage::OwnerRef released_message(ReleaseMessage(
self, child_cmessage->message->GetDescriptor(), field_descriptor));
child_cmessage->message = released_message.get();
child_cmessage->owner.swap(released_message);
@@ -2329,7 +2330,9 @@ PyObject* InternalGetScalar(const Message* message,
break;
}
case FieldDescriptor::CPPTYPE_STRING: {
- string value = reflection->GetString(*message, field_descriptor);
+ string scratch;
+ const string& value =
+ reflection->GetStringReference(*message, field_descriptor, &scratch);
result = ToStringObject(field_descriptor, value);
break;
}
@@ -2863,17 +2866,38 @@ const Message* (*GetCProtoInsidePyProtoPtr)(PyObject* msg);
Message* (*MutableCProtoInsidePyProtoPtr)(PyObject* msg);
static const Message* GetCProtoInsidePyProtoImpl(PyObject* msg) {
+ 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) {
+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 &&
@@ -2882,6 +2906,9 @@ static Message* MutableCProtoInsidePyProtoImpl(PyObject* msg) {
// 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);
diff --git a/python/google/protobuf/pyext/message.h b/python/google/protobuf/pyext/message.h
index 576d098c..d754e62a 100644
--- a/python/google/protobuf/pyext/message.h
+++ b/python/google/protobuf/pyext/message.h
@@ -37,11 +37,11 @@
#include <Python.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
+#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/pyext/thread_unsafe_shared_ptr.h>
+
namespace google {
namespace protobuf {
@@ -52,13 +52,6 @@ class Descriptor;
class DescriptorPool;
class MessageFactory;
-#ifdef _SHARED_PTR_H
-using std::shared_ptr;
-using std::string;
-#else
-using internal::shared_ptr;
-#endif
-
namespace python {
struct ExtensionDict;
@@ -71,7 +64,9 @@ typedef struct CMessage {
// proto tree. Every Python CMessage 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.
- shared_ptr<Message> owner;
+
+ typedef ThreadUnsafeSharedPtr<Message> OwnerRef;
+ OwnerRef owner;
// Weak reference to a parent CMessage object. This is NULL for any top-level
// message and is set for any child message (i.e. a child submessage or a
@@ -255,7 +250,7 @@ PyObject* FindInitializationErrors(CMessage* self);
// Set the owner field of self and any children of self, recursively.
// Used when self is being released and thus has a new owner (the
// released Message.)
-int SetOwner(CMessage* self, const shared_ptr<Message>& new_owner);
+int SetOwner(CMessage* self, const CMessage::OwnerRef& new_owner);
int AssureWritable(CMessage* self);
@@ -336,7 +331,8 @@ bool CheckAndSetString(
const Reflection* reflection,
bool append,
int index);
-PyObject* ToStringObject(const FieldDescriptor* descriptor, string value);
+PyObject* ToStringObject(const FieldDescriptor* descriptor,
+ const string& value);
// Check if the passed field descriptor belongs to the given message.
// If not, return false and set a Python exception (a KeyError)
@@ -345,8 +341,20 @@ 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
+// These are referenced by repeated_scalar_container, and must
+// be explicitly instantiated.
+extern template bool CheckAndGetInteger<int32>(PyObject*, int32*);
+extern template bool CheckAndGetInteger<int64>(PyObject*, int64*);
+extern template bool CheckAndGetInteger<uint32>(PyObject*, uint32*);
+extern template bool CheckAndGetInteger<uint64>(PyObject*, uint64*);
+#endif
+
} // namespace python
} // namespace protobuf
diff --git a/python/google/protobuf/pyext/message_factory.cc b/python/google/protobuf/pyext/message_factory.cc
index 571bae2b..bacc76a6 100644
--- a/python/google/protobuf/pyext/message_factory.cc
+++ b/python/google/protobuf/pyext/message_factory.cc
@@ -100,7 +100,9 @@ PyObject* New(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
NewMessageFactory(type, reinterpret_cast<PyDescriptorPool*>(pool)));
}
-static void Dealloc(PyMessageFactory* self) {
+static void Dealloc(PyObject* pself) {
+ PyMessageFactory* self = reinterpret_cast<PyMessageFactory*>(pself);
+
// TODO(amauryfa): When the MessageFactory is not created from the
// DescriptorPool this reference should be owned, not borrowed.
// Py_CLEAR(self->pool);
@@ -111,7 +113,7 @@ static void Dealloc(PyMessageFactory* self) {
}
delete self->classes_by_descriptor;
delete self->message_factory;
- Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
+ Py_TYPE(self)->tp_free(pself);
}
// Add a message class to our database.
@@ -231,7 +233,7 @@ PyTypeObject PyMessageFactory_Type = {
".MessageFactory", // tp_name
sizeof(PyMessageFactory), // tp_basicsize
0, // tp_itemsize
- (destructor)message_factory::Dealloc, // tp_dealloc
+ message_factory::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
diff --git a/python/google/protobuf/pyext/message_module.cc b/python/google/protobuf/pyext/message_module.cc
index 7c4df47f..f5c8f295 100644
--- a/python/google/protobuf/pyext/message_module.cc
+++ b/python/google/protobuf/pyext/message_module.cc
@@ -31,9 +31,26 @@
#include <Python.h>
#include <google/protobuf/pyext/message.h>
+#include <google/protobuf/proto_api.h>
#include <google/protobuf/message_lite.h>
+namespace {
+
+// 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::Message*
+ GetMutableMessagePointer(PyObject* msg) const override {
+ return google::protobuf::python::PyMessage_GetMutableMessagePointer(msg);
+ }
+};
+
+} // namespace
+
static PyObject* GetPythonProto3PreserveUnknownsDefault(
PyObject* /*m*/, PyObject* /*args*/) {
if (google::protobuf::internal::GetProto3PreserveUnknownsDefault()) {
diff --git a/python/google/protobuf/pyext/repeated_composite_container.cc b/python/google/protobuf/pyext/repeated_composite_container.cc
index 5ad71db5..5874d5de 100644
--- a/python/google/protobuf/pyext/repeated_composite_container.cc
+++ b/python/google/protobuf/pyext/repeated_composite_container.cc
@@ -34,9 +34,6 @@
#include <google/protobuf/pyext/repeated_composite_container.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -81,7 +78,10 @@ namespace repeated_composite_container {
// ---------------------------------------------------------------------
// len()
-static Py_ssize_t Length(RepeatedCompositeContainer* self) {
+static Py_ssize_t Length(PyObject* pself) {
+ RepeatedCompositeContainer* self =
+ reinterpret_cast<RepeatedCompositeContainer*>(pself);
+
Message* message = self->message;
if (message != NULL) {
return message->GetReflection()->FieldSize(*message,
@@ -102,7 +102,7 @@ static int UpdateChildMessages(RepeatedCompositeContainer* self) {
// A MergeFrom on a parent message could have caused extra messages to be
// added in the underlying protobuf so add them to our list. They can never
// be removed in such a way so there's no need to worry about that.
- Py_ssize_t message_length = Length(self);
+ Py_ssize_t message_length = Length(reinterpret_cast<PyObject*>(self));
Py_ssize_t child_length = PyList_GET_SIZE(self->child_messages);
Message* message = self->message;
const Reflection* reflection = message->GetReflection();
@@ -191,6 +191,10 @@ PyObject* Add(RepeatedCompositeContainer* self,
return AddToAttached(self, args, kwargs);
}
+static PyObject* AddMethod(PyObject* self, PyObject* args, PyObject* kwargs) {
+ return Add(reinterpret_cast<RepeatedCompositeContainer*>(self), args, kwargs);
+}
+
// ---------------------------------------------------------------------
// extend()
@@ -226,6 +230,10 @@ PyObject* Extend(RepeatedCompositeContainer* self, PyObject* value) {
Py_RETURN_NONE;
}
+static PyObject* ExtendMethod(PyObject* self, PyObject* value) {
+ return Extend(reinterpret_cast<RepeatedCompositeContainer*>(self), value);
+}
+
PyObject* MergeFrom(RepeatedCompositeContainer* self, PyObject* other) {
if (UpdateChildMessages(self) < 0) {
return NULL;
@@ -233,6 +241,10 @@ PyObject* MergeFrom(RepeatedCompositeContainer* self, PyObject* other) {
return Extend(self, other);
}
+static PyObject* MergeFromMethod(PyObject* self, PyObject* other) {
+ return MergeFrom(reinterpret_cast<RepeatedCompositeContainer*>(self), other);
+}
+
PyObject* Subscript(RepeatedCompositeContainer* self, PyObject* slice) {
if (UpdateChildMessages(self) < 0) {
return NULL;
@@ -242,6 +254,10 @@ PyObject* Subscript(RepeatedCompositeContainer* self, PyObject* slice) {
return PyObject_GetItem(self->child_messages, slice);
}
+static PyObject* SubscriptMethod(PyObject* self, PyObject* slice) {
+ return Subscript(reinterpret_cast<RepeatedCompositeContainer*>(self), slice);
+}
+
int AssignSubscript(RepeatedCompositeContainer* self,
PyObject* slice,
PyObject* value) {
@@ -265,7 +281,7 @@ int AssignSubscript(RepeatedCompositeContainer* self,
Py_ssize_t from;
Py_ssize_t to;
Py_ssize_t step;
- Py_ssize_t length = Length(self);
+ Py_ssize_t length = Length(reinterpret_cast<PyObject*>(self));
Py_ssize_t slicelength;
if (PySlice_Check(slice)) {
#if PY_MAJOR_VERSION >= 3
@@ -290,7 +306,16 @@ int AssignSubscript(RepeatedCompositeContainer* self,
return 0;
}
-static PyObject* Remove(RepeatedCompositeContainer* self, PyObject* value) {
+static int AssignSubscriptMethod(PyObject* self, PyObject* slice,
+ PyObject* value) {
+ return AssignSubscript(reinterpret_cast<RepeatedCompositeContainer*>(self),
+ slice, value);
+}
+
+static PyObject* Remove(PyObject* pself, PyObject* value) {
+ RepeatedCompositeContainer* self =
+ reinterpret_cast<RepeatedCompositeContainer*>(pself);
+
if (UpdateChildMessages(self) < 0) {
return NULL;
}
@@ -305,9 +330,10 @@ static PyObject* Remove(RepeatedCompositeContainer* self, PyObject* value) {
Py_RETURN_NONE;
}
-static PyObject* RichCompare(RepeatedCompositeContainer* self,
- PyObject* other,
- int opid) {
+static PyObject* RichCompare(PyObject* pself, PyObject* other, int opid) {
+ RepeatedCompositeContainer* self =
+ reinterpret_cast<RepeatedCompositeContainer*>(pself);
+
if (UpdateChildMessages(self) < 0) {
return NULL;
}
@@ -340,12 +366,13 @@ static PyObject* RichCompare(RepeatedCompositeContainer* self,
}
}
-static PyObject* ToStr(RepeatedCompositeContainer* self) {
+static PyObject* ToStr(PyObject* pself) {
ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
if (full_slice == NULL) {
return NULL;
}
- ScopedPyObjectPtr list(Subscript(self, full_slice.get()));
+ ScopedPyObjectPtr list(Subscript(
+ reinterpret_cast<RepeatedCompositeContainer*>(pself), full_slice.get()));
if (list == NULL) {
return NULL;
}
@@ -359,7 +386,7 @@ static void ReorderAttached(RepeatedCompositeContainer* self) {
Message* message = self->message;
const Reflection* reflection = message->GetReflection();
const FieldDescriptor* descriptor = self->parent_field_descriptor;
- const Py_ssize_t length = Length(self);
+ const Py_ssize_t length = Length(reinterpret_cast<PyObject*>(self));
// Since Python protobuf objects are never arena-allocated, adding and
// removing message pointers to the underlying array is just updating
@@ -390,9 +417,10 @@ static int SortPythonMessages(RepeatedCompositeContainer* self,
return 0;
}
-static PyObject* Sort(RepeatedCompositeContainer* self,
- PyObject* args,
- PyObject* kwds) {
+static PyObject* Sort(PyObject* pself, PyObject* args, PyObject* kwds) {
+ RepeatedCompositeContainer* self =
+ reinterpret_cast<RepeatedCompositeContainer*>(pself);
+
// Support the old sort_function argument for backwards
// compatibility.
if (kwds != NULL) {
@@ -416,11 +444,14 @@ static PyObject* Sort(RepeatedCompositeContainer* self,
// ---------------------------------------------------------------------
-static PyObject* Item(RepeatedCompositeContainer* self, Py_ssize_t index) {
+static PyObject* Item(PyObject* pself, Py_ssize_t index) {
+ RepeatedCompositeContainer* self =
+ reinterpret_cast<RepeatedCompositeContainer*>(pself);
+
if (UpdateChildMessages(self) < 0) {
return NULL;
}
- Py_ssize_t length = Length(self);
+ Py_ssize_t length = Length(pself);
if (index < 0) {
index = length + index;
}
@@ -432,17 +463,17 @@ static PyObject* Item(RepeatedCompositeContainer* self, Py_ssize_t index) {
return item;
}
-static PyObject* Pop(RepeatedCompositeContainer* self,
- PyObject* args) {
+static PyObject* Pop(PyObject* pself, PyObject* args) {
+ RepeatedCompositeContainer* self =
+ reinterpret_cast<RepeatedCompositeContainer*>(pself);
+
Py_ssize_t index = -1;
if (!PyArg_ParseTuple(args, "|n", &index)) {
return NULL;
}
- PyObject* item = Item(self, index);
+ PyObject* item = Item(pself, index);
if (item == NULL) {
- PyErr_Format(PyExc_IndexError,
- "list index (%zd) out of range",
- index);
+ PyErr_Format(PyExc_IndexError, "list index (%zd) out of range", index);
return NULL;
}
ScopedPyObjectPtr py_index(PyLong_FromSsize_t(index));
@@ -460,7 +491,7 @@ void ReleaseLastTo(CMessage* parent,
GOOGLE_CHECK_NOTNULL(field);
GOOGLE_CHECK_NOTNULL(target);
- shared_ptr<Message> released_message(
+ CMessage::OwnerRef released_message(
parent->message->GetReflection()->ReleaseLast(parent->message, field));
// TODO(tibell): Deal with proto1.
@@ -503,7 +534,10 @@ int Release(RepeatedCompositeContainer* self) {
return 0;
}
-PyObject* DeepCopy(RepeatedCompositeContainer* self, PyObject* arg) {
+PyObject* DeepCopy(PyObject* pself, PyObject* arg) {
+ RepeatedCompositeContainer* self =
+ reinterpret_cast<RepeatedCompositeContainer*>(pself);
+
ScopedPyObjectPtr cloneObj(
PyType_GenericAlloc(&RepeatedCompositeContainer_Type, 0));
if (cloneObj == NULL) {
@@ -530,7 +564,7 @@ PyObject* DeepCopy(RepeatedCompositeContainer* self, PyObject* arg) {
}
int SetOwner(RepeatedCompositeContainer* self,
- const shared_ptr<Message>& new_owner) {
+ const CMessage::OwnerRef& new_owner) {
GOOGLE_CHECK_ATTACHED(self);
self->owner = new_owner;
@@ -571,43 +605,46 @@ PyObject *NewContainer(
return reinterpret_cast<PyObject*>(self);
}
-static void Dealloc(RepeatedCompositeContainer* self) {
+static void Dealloc(PyObject* pself) {
+ RepeatedCompositeContainer* self =
+ reinterpret_cast<RepeatedCompositeContainer*>(pself);
+
Py_CLEAR(self->child_messages);
Py_CLEAR(self->child_message_class);
// TODO(tibell): Do we need to call delete on these objects to make
// sure their destructors are called?
self->owner.reset();
- Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
+ Py_TYPE(self)->tp_free(pself);
}
static PySequenceMethods SqMethods = {
- (lenfunc)Length, /* sq_length */
- 0, /* sq_concat */
- 0, /* sq_repeat */
- (ssizeargfunc)Item /* sq_item */
+ Length, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ Item /* sq_item */
};
static PyMappingMethods MpMethods = {
- (lenfunc)Length, /* mp_length */
- (binaryfunc)Subscript, /* mp_subscript */
- (objobjargproc)AssignSubscript,/* mp_ass_subscript */
+ Length, /* mp_length */
+ SubscriptMethod, /* mp_subscript */
+ AssignSubscriptMethod, /* mp_ass_subscript */
};
static PyMethodDef Methods[] = {
- { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
+ { "__deepcopy__", DeepCopy, METH_VARARGS,
"Makes a deep copy of the class." },
- { "add", (PyCFunction) Add, METH_VARARGS | METH_KEYWORDS,
+ { "add", (PyCFunction)AddMethod, METH_VARARGS | METH_KEYWORDS,
"Adds an object to the repeated container." },
- { "extend", (PyCFunction) Extend, METH_O,
+ { "extend", ExtendMethod, METH_O,
"Adds objects to the repeated container." },
- { "pop", (PyCFunction)Pop, METH_VARARGS,
+ { "pop", Pop, METH_VARARGS,
"Removes an object from the repeated container and returns it." },
- { "remove", (PyCFunction) Remove, METH_O,
+ { "remove", Remove, METH_O,
"Removes an object from the repeated container." },
- { "sort", (PyCFunction) Sort, METH_VARARGS | METH_KEYWORDS,
+ { "sort", (PyCFunction)Sort, METH_VARARGS | METH_KEYWORDS,
"Sorts the repeated container." },
- { "MergeFrom", (PyCFunction) MergeFrom, METH_O,
+ { "MergeFrom", MergeFromMethod, METH_O,
"Adds objects to the repeated container." },
{ NULL, NULL }
};
@@ -619,12 +656,12 @@ PyTypeObject RepeatedCompositeContainer_Type = {
FULL_MODULE_NAME ".RepeatedCompositeContainer", // tp_name
sizeof(RepeatedCompositeContainer), // tp_basicsize
0, // tp_itemsize
- (destructor)repeated_composite_container::Dealloc, // tp_dealloc
+ repeated_composite_container::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
- (reprfunc)repeated_composite_container::ToStr, // tp_repr
+ repeated_composite_container::ToStr, // tp_repr
0, // tp_as_number
&repeated_composite_container::SqMethods, // tp_as_sequence
&repeated_composite_container::MpMethods, // tp_as_mapping
@@ -638,7 +675,7 @@ PyTypeObject RepeatedCompositeContainer_Type = {
"A Repeated scalar container", // tp_doc
0, // tp_traverse
0, // tp_clear
- (richcmpfunc)repeated_composite_container::RichCompare, // tp_richcompare
+ repeated_composite_container::RichCompare, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
diff --git a/python/google/protobuf/pyext/repeated_composite_container.h b/python/google/protobuf/pyext/repeated_composite_container.h
index a7b56b61..e5e946aa 100644
--- a/python/google/protobuf/pyext/repeated_composite_container.h
+++ b/python/google/protobuf/pyext/repeated_composite_container.h
@@ -37,27 +37,19 @@
#include <Python.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
#include <vector>
+#include <google/protobuf/pyext/message.h>
+
namespace google {
namespace protobuf {
class FieldDescriptor;
class Message;
-#ifdef _SHARED_PTR_H
-using std::shared_ptr;
-#else
-using internal::shared_ptr;
-#endif
-
namespace python {
-struct CMessage;
struct CMessageClass;
// A RepeatedCompositeContainer can be in one of two states: attached
@@ -77,7 +69,7 @@ typedef struct RepeatedCompositeContainer {
// proto tree. Every Python RepeatedCompositeContainer 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.
- shared_ptr<Message> owner;
+ CMessage::OwnerRef owner;
// Weak reference to parent object. May be NULL. Used to make sure
// the parent is writable before modifying the
@@ -148,11 +140,6 @@ int AssignSubscript(RepeatedCompositeContainer* self,
PyObject* slice,
PyObject* value);
-// Releases the messages in the container to the given message.
-//
-// Returns 0 on success, -1 on failure.
-int ReleaseToMessage(RepeatedCompositeContainer* self, Message* new_message);
-
// Releases the messages in the container to a new message.
//
// Returns 0 on success, -1 on failure.
@@ -160,7 +147,7 @@ int Release(RepeatedCompositeContainer* self);
// Returns 0 on success, -1 on failure.
int SetOwner(RepeatedCompositeContainer* self,
- const shared_ptr<Message>& new_owner);
+ const CMessage::OwnerRef& new_owner);
// Removes the last element of the repeated message field 'field' on
// the Message 'parent', and transfers the ownership of the released
diff --git a/python/google/protobuf/pyext/repeated_scalar_container.cc b/python/google/protobuf/pyext/repeated_scalar_container.cc
index 5a7832cd..de3b6e14 100644
--- a/python/google/protobuf/pyext/repeated_scalar_container.cc
+++ b/python/google/protobuf/pyext/repeated_scalar_container.cc
@@ -34,9 +34,6 @@
#include <google/protobuf/pyext/repeated_scalar_container.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
@@ -77,15 +74,18 @@ static int InternalAssignRepeatedField(
return 0;
}
-static Py_ssize_t Len(RepeatedScalarContainer* self) {
+static Py_ssize_t Len(PyObject* pself) {
+ RepeatedScalarContainer* self =
+ reinterpret_cast<RepeatedScalarContainer*>(pself);
Message* message = self->message;
return message->GetReflection()->FieldSize(*message,
self->parent_field_descriptor);
}
-static int AssignItem(RepeatedScalarContainer* self,
- Py_ssize_t index,
- PyObject* arg) {
+static int AssignItem(PyObject* pself, Py_ssize_t index, PyObject* arg) {
+ RepeatedScalarContainer* self =
+ reinterpret_cast<RepeatedScalarContainer*>(pself);
+
cmessage::AssureWritable(self->parent);
Message* message = self->message;
const FieldDescriptor* field_descriptor = self->parent_field_descriptor;
@@ -188,7 +188,10 @@ static int AssignItem(RepeatedScalarContainer* self,
return 0;
}
-static PyObject* Item(RepeatedScalarContainer* self, Py_ssize_t index) {
+static PyObject* Item(PyObject* pself, Py_ssize_t index) {
+ RepeatedScalarContainer* self =
+ reinterpret_cast<RepeatedScalarContainer*>(pself);
+
Message* message = self->message;
const FieldDescriptor* field_descriptor = self->parent_field_descriptor;
const Reflection* reflection = message->GetReflection();
@@ -256,8 +259,9 @@ static PyObject* Item(RepeatedScalarContainer* self, Py_ssize_t index) {
break;
}
case FieldDescriptor::CPPTYPE_STRING: {
- string value = reflection->GetRepeatedString(
- *message, field_descriptor, index);
+ string scratch;
+ const string& value = reflection->GetRepeatedStringReference(
+ *message, field_descriptor, index, &scratch);
result = ToStringObject(field_descriptor, value);
break;
}
@@ -271,7 +275,7 @@ static PyObject* Item(RepeatedScalarContainer* self, Py_ssize_t index) {
return result;
}
-static PyObject* Subscript(RepeatedScalarContainer* self, PyObject* slice) {
+static PyObject* Subscript(PyObject* pself, PyObject* slice) {
Py_ssize_t from;
Py_ssize_t to;
Py_ssize_t step;
@@ -286,14 +290,13 @@ static PyObject* Subscript(RepeatedScalarContainer* self, PyObject* slice) {
if (PyLong_Check(slice)) {
from = to = PyLong_AsLong(slice);
} else if (PySlice_Check(slice)) {
- length = Len(self);
+ length = Len(pself);
#if PY_MAJOR_VERSION >= 3
if (PySlice_GetIndicesEx(slice,
length, &from, &to, &step, &slicelength) == -1) {
#else
if (PySlice_GetIndicesEx(reinterpret_cast<PySliceObject*>(slice),
length, &from, &to, &step, &slicelength) == -1) {
-
#endif
return NULL;
}
@@ -304,7 +307,7 @@ static PyObject* Subscript(RepeatedScalarContainer* self, PyObject* slice) {
}
if (!return_list) {
- return Item(self, from);
+ return Item(pself, from);
}
PyObject* list = PyList_New(0);
@@ -319,7 +322,7 @@ static PyObject* Subscript(RepeatedScalarContainer* self, PyObject* slice) {
if (index < 0 || index >= length) {
break;
}
- ScopedPyObjectPtr s(Item(self, index));
+ ScopedPyObjectPtr s(Item(pself, index));
PyList_Append(list, s.get());
}
} else {
@@ -330,7 +333,7 @@ static PyObject* Subscript(RepeatedScalarContainer* self, PyObject* slice) {
if (index < 0 || index >= length) {
break;
}
- ScopedPyObjectPtr s(Item(self, index));
+ ScopedPyObjectPtr s(Item(pself, index));
PyList_Append(list, s.get());
}
}
@@ -417,9 +420,14 @@ PyObject* Append(RepeatedScalarContainer* self, PyObject* item) {
Py_RETURN_NONE;
}
-static int AssSubscript(RepeatedScalarContainer* self,
- PyObject* slice,
- PyObject* value) {
+static PyObject* AppendMethod(PyObject* self, PyObject* item) {
+ return Append(reinterpret_cast<RepeatedScalarContainer*>(self), item);
+}
+
+static int AssSubscript(PyObject* pself, PyObject* slice, PyObject* value) {
+ RepeatedScalarContainer* self =
+ reinterpret_cast<RepeatedScalarContainer*>(pself);
+
Py_ssize_t from;
Py_ssize_t to;
Py_ssize_t step;
@@ -435,7 +443,7 @@ static int AssSubscript(RepeatedScalarContainer* self,
#if PY_MAJOR_VERSION < 3
if (PyInt_Check(slice)) {
from = to = PyInt_AsLong(slice);
- } else
+ } else // NOLINT
#endif
if (PyLong_Check(slice)) {
from = to = PyLong_AsLong(slice);
@@ -463,14 +471,14 @@ static int AssSubscript(RepeatedScalarContainer* self,
}
if (!create_list) {
- return AssignItem(self, from, value);
+ return AssignItem(pself, from, value);
}
ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
if (full_slice == NULL) {
return -1;
}
- ScopedPyObjectPtr new_list(Subscript(self, full_slice.get()));
+ ScopedPyObjectPtr new_list(Subscript(pself, full_slice.get()));
if (new_list == NULL) {
return -1;
}
@@ -509,14 +517,17 @@ PyObject* Extend(RepeatedScalarContainer* self, PyObject* value) {
Py_RETURN_NONE;
}
-static PyObject* Insert(RepeatedScalarContainer* self, PyObject* args) {
+static PyObject* Insert(PyObject* pself, PyObject* args) {
+ RepeatedScalarContainer* self =
+ reinterpret_cast<RepeatedScalarContainer*>(pself);
+
Py_ssize_t index;
PyObject* value;
if (!PyArg_ParseTuple(args, "lO", &index, &value)) {
return NULL;
}
ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
- ScopedPyObjectPtr new_list(Subscript(self, full_slice.get()));
+ ScopedPyObjectPtr new_list(Subscript(pself, full_slice.get()));
if (PyList_Insert(new_list.get(), index, value) < 0) {
return NULL;
}
@@ -527,10 +538,10 @@ static PyObject* Insert(RepeatedScalarContainer* self, PyObject* args) {
Py_RETURN_NONE;
}
-static PyObject* Remove(RepeatedScalarContainer* self, PyObject* value) {
+static PyObject* Remove(PyObject* pself, PyObject* value) {
Py_ssize_t match_index = -1;
- for (Py_ssize_t i = 0; i < Len(self); ++i) {
- ScopedPyObjectPtr elem(Item(self, i));
+ for (Py_ssize_t i = 0; i < Len(pself); ++i) {
+ ScopedPyObjectPtr elem(Item(pself, i));
if (PyObject_RichCompareBool(elem.get(), value, Py_EQ)) {
match_index = i;
break;
@@ -540,15 +551,17 @@ static PyObject* Remove(RepeatedScalarContainer* self, PyObject* value) {
PyErr_SetString(PyExc_ValueError, "remove(x): x not in container");
return NULL;
}
- if (AssignItem(self, match_index, NULL) < 0) {
+ if (AssignItem(pself, match_index, NULL) < 0) {
return NULL;
}
Py_RETURN_NONE;
}
-static PyObject* RichCompare(RepeatedScalarContainer* self,
- PyObject* other,
- int opid) {
+static PyObject* ExtendMethod(PyObject* self, PyObject* value) {
+ return Extend(reinterpret_cast<RepeatedScalarContainer*>(self), value);
+}
+
+static PyObject* RichCompare(PyObject* pself, PyObject* other, int opid) {
if (opid != Py_EQ && opid != Py_NE) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
@@ -565,28 +578,25 @@ static PyObject* RichCompare(RepeatedScalarContainer* self,
ScopedPyObjectPtr other_list_deleter;
if (PyObject_TypeCheck(other, &RepeatedScalarContainer_Type)) {
- other_list_deleter.reset(Subscript(
- reinterpret_cast<RepeatedScalarContainer*>(other), full_slice.get()));
+ other_list_deleter.reset(Subscript(other, full_slice.get()));
other = other_list_deleter.get();
}
- ScopedPyObjectPtr list(Subscript(self, full_slice.get()));
+ ScopedPyObjectPtr list(Subscript(pself, full_slice.get()));
if (list == NULL) {
return NULL;
}
return PyObject_RichCompare(list.get(), other, opid);
}
-PyObject* Reduce(RepeatedScalarContainer* unused_self) {
+PyObject* Reduce(PyObject* unused_self, PyObject* unused_other) {
PyErr_Format(
PickleError_class,
"can't pickle repeated message fields, convert to list first");
return NULL;
}
-static PyObject* Sort(RepeatedScalarContainer* self,
- PyObject* args,
- PyObject* kwds) {
+static PyObject* Sort(PyObject* pself, PyObject* args, PyObject* kwds) {
// Support the old sort_function argument for backwards
// compatibility.
if (kwds != NULL) {
@@ -605,7 +615,7 @@ static PyObject* Sort(RepeatedScalarContainer* self,
if (full_slice == NULL) {
return NULL;
}
- ScopedPyObjectPtr list(Subscript(self, full_slice.get()));
+ ScopedPyObjectPtr list(Subscript(pself, full_slice.get()));
if (list == NULL) {
return NULL;
}
@@ -617,38 +627,36 @@ static PyObject* Sort(RepeatedScalarContainer* self,
if (res == NULL) {
return NULL;
}
- int ret = InternalAssignRepeatedField(self, list.get());
+ int ret = InternalAssignRepeatedField(
+ reinterpret_cast<RepeatedScalarContainer*>(pself), list.get());
if (ret < 0) {
return NULL;
}
Py_RETURN_NONE;
}
-static PyObject* Pop(RepeatedScalarContainer* self,
- PyObject* args) {
+static PyObject* Pop(PyObject* pself, PyObject* args) {
Py_ssize_t index = -1;
if (!PyArg_ParseTuple(args, "|n", &index)) {
return NULL;
}
- PyObject* item = Item(self, index);
+ PyObject* item = Item(pself, index);
if (item == NULL) {
- PyErr_Format(PyExc_IndexError,
- "list index (%zd) out of range",
- index);
+ PyErr_Format(PyExc_IndexError, "list index (%zd) out of range", index);
return NULL;
}
- if (AssignItem(self, index, NULL) < 0) {
+ if (AssignItem(pself, index, NULL) < 0) {
return NULL;
}
return item;
}
-static PyObject* ToStr(RepeatedScalarContainer* self) {
+static PyObject* ToStr(PyObject* pself) {
ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
if (full_slice == NULL) {
return NULL;
}
- ScopedPyObjectPtr list(Subscript(self, full_slice.get()));
+ ScopedPyObjectPtr list(Subscript(pself, full_slice.get()));
if (list == NULL) {
return NULL;
}
@@ -687,7 +695,8 @@ static int InitializeAndCopyToParentContainer(
if (full_slice == NULL) {
return -1;
}
- ScopedPyObjectPtr values(Subscript(from, full_slice.get()));
+ ScopedPyObjectPtr values(
+ Subscript(reinterpret_cast<PyObject*>(from), full_slice.get()));
if (values == NULL) {
return -1;
}
@@ -706,7 +715,10 @@ int Release(RepeatedScalarContainer* self) {
return InitializeAndCopyToParentContainer(self, self);
}
-PyObject* DeepCopy(RepeatedScalarContainer* self, PyObject* arg) {
+PyObject* DeepCopy(PyObject* pself, PyObject* arg) {
+ RepeatedScalarContainer* self =
+ reinterpret_cast<RepeatedScalarContainer*>(pself);
+
RepeatedScalarContainer* clone = reinterpret_cast<RepeatedScalarContainer*>(
PyType_GenericAlloc(&RepeatedScalarContainer_Type, 0));
if (clone == NULL) {
@@ -720,45 +732,47 @@ PyObject* DeepCopy(RepeatedScalarContainer* self, PyObject* arg) {
return reinterpret_cast<PyObject*>(clone);
}
-static void Dealloc(RepeatedScalarContainer* self) {
+static void Dealloc(PyObject* pself) {
+ RepeatedScalarContainer* self =
+ reinterpret_cast<RepeatedScalarContainer*>(pself);
self->owner.reset();
- Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
+ Py_TYPE(self)->tp_free(pself);
}
void SetOwner(RepeatedScalarContainer* self,
- const shared_ptr<Message>& new_owner) {
+ const CMessage::OwnerRef& new_owner) {
self->owner = new_owner;
}
static PySequenceMethods SqMethods = {
- (lenfunc)Len, /* sq_length */
- 0, /* sq_concat */
- 0, /* sq_repeat */
- (ssizeargfunc)Item, /* sq_item */
- 0, /* sq_slice */
- (ssizeobjargproc)AssignItem /* sq_ass_item */
+ Len, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ Item, /* sq_item */
+ 0, /* sq_slice */
+ AssignItem /* sq_ass_item */
};
static PyMappingMethods MpMethods = {
- (lenfunc)Len, /* mp_length */
- (binaryfunc)Subscript, /* mp_subscript */
- (objobjargproc)AssSubscript, /* mp_ass_subscript */
+ Len, /* mp_length */
+ Subscript, /* mp_subscript */
+ AssSubscript, /* mp_ass_subscript */
};
static PyMethodDef Methods[] = {
- { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
+ { "__deepcopy__", DeepCopy, METH_VARARGS,
"Makes a deep copy of the class." },
- { "__reduce__", (PyCFunction)Reduce, METH_NOARGS,
+ { "__reduce__", Reduce, METH_NOARGS,
"Outputs picklable representation of the repeated field." },
- { "append", (PyCFunction)Append, METH_O,
+ { "append", AppendMethod, METH_O,
"Appends an object to the repeated container." },
- { "extend", (PyCFunction)Extend, METH_O,
- "Appends objects to the repeated container." },
- { "insert", (PyCFunction)Insert, METH_VARARGS,
+ { "extend", ExtendMethod, METH_O,
"Appends objects to the repeated container." },
- { "pop", (PyCFunction)Pop, METH_VARARGS,
+ { "insert", Insert, METH_VARARGS,
+ "Inserts an object at the specified position in the container." },
+ { "pop", Pop, METH_VARARGS,
"Removes an object from the repeated container and returns it." },
- { "remove", (PyCFunction)Remove, METH_O,
+ { "remove", Remove, METH_O,
"Removes an object from the repeated container." },
{ "sort", (PyCFunction)Sort, METH_VARARGS | METH_KEYWORDS,
"Sorts the repeated container."},
@@ -772,12 +786,12 @@ PyTypeObject RepeatedScalarContainer_Type = {
FULL_MODULE_NAME ".RepeatedScalarContainer", // tp_name
sizeof(RepeatedScalarContainer), // tp_basicsize
0, // tp_itemsize
- (destructor)repeated_scalar_container::Dealloc, // tp_dealloc
+ repeated_scalar_container::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
- (reprfunc)repeated_scalar_container::ToStr, // tp_repr
+ repeated_scalar_container::ToStr, // tp_repr
0, // tp_as_number
&repeated_scalar_container::SqMethods, // tp_as_sequence
&repeated_scalar_container::MpMethods, // tp_as_mapping
@@ -791,7 +805,7 @@ PyTypeObject RepeatedScalarContainer_Type = {
"A Repeated scalar container", // tp_doc
0, // tp_traverse
0, // tp_clear
- (richcmpfunc)repeated_scalar_container::RichCompare, // tp_richcompare
+ repeated_scalar_container::RichCompare, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
diff --git a/python/google/protobuf/pyext/repeated_scalar_container.h b/python/google/protobuf/pyext/repeated_scalar_container.h
index 555e621c..559dec98 100644
--- a/python/google/protobuf/pyext/repeated_scalar_container.h
+++ b/python/google/protobuf/pyext/repeated_scalar_container.h
@@ -37,27 +37,14 @@
#include <Python.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/descriptor.h>
+#include <google/protobuf/pyext/message.h>
namespace google {
namespace protobuf {
-
-class Message;
-
-#ifdef _SHARED_PTR_H
-using std::shared_ptr;
-#else
-using internal::shared_ptr;
-#endif
-
namespace python {
-struct CMessage;
-
typedef struct RepeatedScalarContainer {
PyObject_HEAD;
@@ -65,7 +52,7 @@ typedef struct RepeatedScalarContainer {
// proto tree. Every Python RepeatedScalarContainer 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.
- shared_ptr<Message> owner;
+ CMessage::OwnerRef owner;
// Pointer to the C++ Message that contains this container. The
// RepeatedScalarContainer does not own this pointer.
@@ -112,7 +99,7 @@ PyObject* Extend(RepeatedScalarContainer* self, PyObject* value);
// Set the owner field of self and any children of self.
void SetOwner(RepeatedScalarContainer* self,
- const shared_ptr<Message>& new_owner);
+ const CMessage::OwnerRef& new_owner);
} // namespace repeated_scalar_container
} // namespace python
diff --git a/src/google/protobuf/compiler/javanano/javanano_extension.h b/python/google/protobuf/pyext/thread_unsafe_shared_ptr.h
index f4e9eb2d..ad804b5f 100644
--- a/src/google/protobuf/compiler/javanano/javanano_extension.h
+++ b/python/google/protobuf/pyext/thread_unsafe_shared_ptr.h
@@ -1,6 +1,6 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
+// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
@@ -28,47 +28,77 @@
// (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: bduff@google.com (Brian Duff)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
+// ThreadUnsafeSharedPtr<T> is the same as shared_ptr<T> without the locking
+// overhread (and thread-safety).
+#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_THREAD_UNSAFE_SHARED_PTR_H__
+#define GOOGLE_PROTOBUF_PYTHON_CPP_THREAD_UNSAFE_SHARED_PTR_H__
-#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_EXTENSION_H_
-#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_EXTENSION_H_
+#include <algorithm>
+#include <utility>
+#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/compiler/javanano/javanano_params.h>
-#include <google/protobuf/descriptor.pb.h>
-
namespace google {
namespace protobuf {
- namespace io {
- class Printer; // printer.h
+namespace python {
+
+template <typename T>
+class ThreadUnsafeSharedPtr {
+ public:
+ // Takes ownership.
+ explicit ThreadUnsafeSharedPtr(T* ptr)
+ : ptr_(ptr), refcount_(ptr ? new RefcountT(1) : nullptr) {
}
-}
-namespace protobuf {
-namespace compiler {
-namespace javanano {
+ ThreadUnsafeSharedPtr(const ThreadUnsafeSharedPtr& other)
+ : ThreadUnsafeSharedPtr(nullptr) {
+ *this = other;
+ }
-class ExtensionGenerator {
- public:
- explicit ExtensionGenerator(const FieldDescriptor* descriptor, const Params& params);
- ~ExtensionGenerator();
+ ThreadUnsafeSharedPtr& operator=(const ThreadUnsafeSharedPtr& other) {
+ if (other.refcount_ == refcount_) {
+ return *this;
+ }
+ this->~ThreadUnsafeSharedPtr();
+ ptr_ = other.ptr_;
+ refcount_ = other.refcount_;
+ if (refcount_) {
+ ++*refcount_;
+ }
+ return *this;
+ }
- void Generate(io::Printer* printer) const;
+ ~ThreadUnsafeSharedPtr() {
+ if (refcount_ == nullptr) {
+ GOOGLE_DCHECK(ptr_ == nullptr);
+ return;
+ }
+ if (--*refcount_ == 0) {
+ delete refcount_;
+ delete ptr_;
+ }
+ }
- private:
- const Params& params_;
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ void reset(T* ptr = nullptr) { *this = ThreadUnsafeSharedPtr(ptr); }
+
+ T* get() { return ptr_; }
+ const T* get() const { return ptr_; }
+
+ void swap(ThreadUnsafeSharedPtr& other) {
+ using std::swap;
+ swap(ptr_, other.ptr_);
+ swap(refcount_, other.refcount_);
+ }
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator);
+ private:
+ typedef int RefcountT;
+ T* ptr_;
+ RefcountT* refcount_;
};
-} // namespace javanano
-} // namespace compiler
+} // namespace python
} // namespace protobuf
-} // namespace google
-#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_EXTENSION_H_
+} // namespace google
+#endif // GOOGLE_PROTOBUF_PYTHON_CPP_THREAD_UNSAFE_SHARED_PTR_H__
diff --git a/python/google/protobuf/text_format.py b/python/google/protobuf/text_format.py
index 36ddd1b7..2cbd21bc 100755
--- a/python/google/protobuf/text_format.py
+++ b/python/google/protobuf/text_format.py
@@ -141,9 +141,11 @@ def MessageToString(message,
as_one_line: Don't introduce newlines between fields.
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
- defined in source code instead of the field number. By default, use the
- field number order.
+ use_index_order: If True, fields of a proto message will be printed using
+ the order defined in source code instead of the field number, extensions
+ will be printed at the end of the message and their relative order is
+ determined by the extension number. By default, use the field number
+ order.
float_format: If set, use this to specify floating point number formatting
(per the "Format Specification Mini-Language"); otherwise, str() is used.
use_field_number: If True, print field numbers instead of names.
@@ -336,11 +338,12 @@ class _Printer(object):
return
fields = message.ListFields()
if self.use_index_order:
- fields.sort(key=lambda x: x[0].index)
+ fields.sort(
+ key=lambda x: x[0].number if x[0].is_extension else x[0].index)
for field, value in fields:
if _IsMapEntry(field):
for key in sorted(value):
- # This is slow for maps with submessage entires because it copies the
+ # This is slow for maps with submessage entries because it copies the
# entire tree. Unfortunately this would take significant refactoring
# of this file to work around.
#
@@ -645,6 +648,30 @@ class _Parser(object):
ParseError: In case of text parsing problems.
"""
message_descriptor = message.DESCRIPTOR
+ if (message_descriptor.full_name == _ANY_FULL_TYPE_NAME and
+ tokenizer.TryConsume('[')):
+ type_url_prefix, packed_type_name = self._ConsumeAnyTypeUrl(tokenizer)
+ tokenizer.Consume(']')
+ tokenizer.TryConsume(':')
+ if tokenizer.TryConsume('<'):
+ expanded_any_end_token = '>'
+ else:
+ tokenizer.Consume('{')
+ expanded_any_end_token = '}'
+ expanded_any_sub_message = _BuildMessageFromTypeName(packed_type_name,
+ self.descriptor_pool)
+ if not expanded_any_sub_message:
+ raise ParseError('Type %s not found in descriptor pool' %
+ packed_type_name)
+ while not tokenizer.TryConsume(expanded_any_end_token):
+ if tokenizer.AtEnd():
+ raise tokenizer.ParseErrorPreviousToken('Expected "%s".' %
+ (expanded_any_end_token,))
+ self._MergeField(tokenizer, expanded_any_sub_message)
+ message.Pack(expanded_any_sub_message,
+ type_url_prefix=type_url_prefix)
+ return
+
if tokenizer.TryConsume('['):
name = [tokenizer.ConsumeIdentifier()]
while tokenizer.TryConsume('.'):
@@ -725,11 +752,12 @@ class _Parser(object):
if (field.label == descriptor.FieldDescriptor.LABEL_REPEATED and
tokenizer.TryConsume('[')):
# Short repeated format, e.g. "foo: [1, 2, 3]"
- while True:
- merger(tokenizer, message, field)
- if tokenizer.TryConsume(']'):
- break
- tokenizer.Consume(',')
+ if not tokenizer.TryConsume(']'):
+ while True:
+ merger(tokenizer, message, field)
+ if tokenizer.TryConsume(']'):
+ break
+ tokenizer.Consume(',')
else:
merger(tokenizer, message, field)
@@ -777,33 +805,7 @@ class _Parser(object):
tokenizer.Consume('{')
end_token = '}'
- if (field.message_type.full_name == _ANY_FULL_TYPE_NAME and
- tokenizer.TryConsume('[')):
- type_url_prefix, packed_type_name = self._ConsumeAnyTypeUrl(tokenizer)
- tokenizer.Consume(']')
- tokenizer.TryConsume(':')
- if tokenizer.TryConsume('<'):
- expanded_any_end_token = '>'
- else:
- tokenizer.Consume('{')
- expanded_any_end_token = '}'
- expanded_any_sub_message = _BuildMessageFromTypeName(packed_type_name,
- self.descriptor_pool)
- if not expanded_any_sub_message:
- raise ParseError('Type %s not found in descriptor pool' %
- packed_type_name)
- while not tokenizer.TryConsume(expanded_any_end_token):
- if tokenizer.AtEnd():
- raise tokenizer.ParseErrorPreviousToken('Expected "%s".' %
- (expanded_any_end_token,))
- self._MergeField(tokenizer, expanded_any_sub_message)
- if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
- any_message = getattr(message, field.name).add()
- else:
- any_message = getattr(message, field.name)
- any_message.Pack(expanded_any_sub_message,
- type_url_prefix=type_url_prefix)
- elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
+ if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
if field.is_extension:
sub_message = message.Extensions[field].add()
elif is_map_entry:
@@ -812,8 +814,20 @@ class _Parser(object):
sub_message = getattr(message, field.name).add()
else:
if field.is_extension:
+ if (not self._allow_multiple_scalars and
+ message.HasExtension(field)):
+ raise tokenizer.ParseErrorPreviousToken(
+ 'Message type "%s" should not have multiple "%s" extensions.' %
+ (message.DESCRIPTOR.full_name, field.full_name))
sub_message = message.Extensions[field]
else:
+ # Also apply _allow_multiple_scalars to message field.
+ # TODO(jieluo): Change to _allow_singular_overwrites.
+ if (not self._allow_multiple_scalars and
+ message.HasField(field.name)):
+ raise tokenizer.ParseErrorPreviousToken(
+ 'Message type "%s" should not have multiple "%s" fields.' %
+ (message.DESCRIPTOR.full_name, field.name))
sub_message = getattr(message, field.name)
sub_message.SetInParent()
diff --git a/python/google/protobuf/util/__init__.py b/python/google/protobuf/util/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/python/google/protobuf/util/__init__.py
diff --git a/python/setup.py b/python/setup.py
index 0f7e58b0..335e9114 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__
@@ -107,6 +108,7 @@ def GenerateUnittestProtos():
generate_proto("google/protobuf/internal/more_extensions.proto", False)
generate_proto("google/protobuf/internal/more_extensions_dynamic.proto", False)
generate_proto("google/protobuf/internal/more_messages.proto", False)
+ generate_proto("google/protobuf/internal/no_package.proto", False)
generate_proto("google/protobuf/internal/packed_field_test.proto", False)
generate_proto("google/protobuf/internal/test_bad_identifiers.proto", False)
generate_proto("google/protobuf/pyext/python.proto", False)
@@ -119,9 +121,7 @@ class clean(_clean):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
if filepath.endswith("_pb2.py") or filepath.endswith(".pyc") or \
- filepath.endswith(".so") or filepath.endswith(".o") or \
- filepath.endswith('google/protobuf/compiler/__init__.py') or \
- filepath.endswith('google/protobuf/util/__init__.py'):
+ filepath.endswith(".so") or filepath.endswith(".o"):
os.remove(filepath)
# _clean is an old-style class, so super() doesn't work.
_clean.run(self)
@@ -143,22 +143,15 @@ class build_py(_build_py):
generate_proto("../src/google/protobuf/wrappers.proto")
GenerateUnittestProtos()
- # Make sure google.protobuf/** are valid packages.
- for path in ['', 'internal/', 'compiler/', 'pyext/', 'util/']:
- try:
- open('google/protobuf/%s__init__.py' % path, 'a').close()
- except EnvironmentError:
- pass
# _build_py is an old-style class, so super() doesn't work.
_build_py.run(self)
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)
@@ -178,9 +171,6 @@ if __name__ == '__main__':
# extension. Note that those libraries have to be compiled with
# -fPIC for this to work.
compile_static_ext = get_option_from_sys_argv('--compile_static_extension')
- extra_compile_args = ['-Wno-write-strings',
- '-Wno-invalid-offsetof',
- '-Wno-sign-compare']
libraries = ['protobuf']
extra_objects = None
if compile_static_ext:
@@ -189,14 +179,33 @@ if __name__ == '__main__':
'../src/.libs/libprotobuf-lite.a']
test_conformance.target = 'test_python_cpp'
+ extra_compile_args = []
+
+ if sys.platform != 'win32':
+ extra_compile_args.append('-Wno-write-strings')
+ extra_compile_args.append('-Wno-invalid-offsetof')
+ extra_compile_args.append('-Wno-sign-compare')
+
+ # https://github.com/Theano/Theano/issues/4926
+ if sys.platform == 'win32':
+ extra_compile_args.append('-D_hypot=hypot')
+
+ # https://github.com/tpaviot/pythonocc-core/issues/48
+ if sys.platform == 'win32' and '64 bit' in sys.version:
+ extra_compile_args.append('-DMS_WIN64')
+
+ # MSVS default is dymanic
+ if (sys.platform == 'win32'):
+ extra_compile_args.append('/MT')
+
if "clang" in os.popen('$CC --version 2> /dev/null').read():
extra_compile_args.append('-Wno-shorten-64-to-32')
v, _, _ = platform.mac_ver()
if v:
- v = float('.'.join(v.split('.')[:2]))
- if v >= 10.12:
- extra_compile_args.append('-std=c++11')
+ 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')
@@ -216,7 +225,7 @@ if __name__ == '__main__':
Extension(
"google.protobuf.internal._api_implementation",
glob.glob('google/protobuf/internal/api_implementation.cc'),
- extra_compile_args=['-DPYTHON_PROTO2_CPP_IMPL_V2'],
+ extra_compile_args=extra_compile_args + ['-DPYTHON_PROTO2_CPP_IMPL_V2'],
),
])
os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'cpp'
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/Rakefile b/ruby/Rakefile
index e30a75a3..013bc99a 100644
--- a/ruby/Rakefile
+++ b/ruby/Rakefile
@@ -52,6 +52,12 @@ if RUBY_PLATFORM == "java"
end
else
Rake::ExtensionTask.new("protobuf_c", spec) do |ext|
+ unless RUBY_PLATFORM =~ /darwin/
+ # TODO: also set "no_native to true" for mac if possible. As is,
+ # "no_native" can only be set if the RUBY_PLATFORM doing
+ # cross-compilation is contained in the "ext.cross_platform" array.
+ ext.no_native = true
+ end
ext.ext_dir = "ext/google/protobuf_c"
ext.lib_dir = "lib/google"
ext.cross_compile = true
@@ -64,13 +70,13 @@ else
task 'gem:windows' do
require 'rake_compiler_dock'
- RakeCompilerDock.sh "bundle && IN_DOCKER=true rake cross native gem RUBY_CC_VERSION=2.4.0:2.3.0:2.2.2:2.1.5:2.0.0"
+ RakeCompilerDock.sh "bundle && IN_DOCKER=true rake cross native gem RUBY_CC_VERSION=2.5.0:2.4.0:2.3.0:2.2.2:2.1.6:2.0.0"
end
if RUBY_PLATFORM =~ /darwin/
task 'gem:native' do
system "rake genproto"
- system "rake cross native gem RUBY_CC_VERSION=2.4.0:2.3.0:2.2.2:2.1.5:2.0.0"
+ system "rake cross native gem RUBY_CC_VERSION=2.5.0:2.4.0:2.3.0:2.2.2:2.1.6:2.0.0"
end
else
task 'gem:native' => [:genproto, 'gem:windows']
@@ -81,6 +87,7 @@ end
# Proto for tests.
genproto_output << "tests/generated_code.rb"
genproto_output << "tests/test_import.rb"
+genproto_output << "tests/test_ruby_package.rb"
file "tests/generated_code.rb" => "tests/generated_code.proto" do |file_task|
sh "../src/protoc --ruby_out=. tests/generated_code.proto"
end
@@ -89,6 +96,10 @@ file "tests/test_import.rb" => "tests/test_import.proto" do |file_task|
sh "../src/protoc --ruby_out=. tests/test_import.proto"
end
+file "tests/test_ruby_package.rb" => "tests/test_ruby_package.proto" do |file_task|
+ sh "../src/protoc --ruby_out=. tests/test_ruby_package.proto"
+end
+
task :genproto => genproto_output
task :clean do
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/extconf.rb b/ruby/ext/google/protobuf_c/extconf.rb
index 0886e607..cc097e11 100644
--- a/ruby/ext/google/protobuf_c/extconf.rb
+++ b/ruby/ext/google/protobuf_c/extconf.rb
@@ -2,7 +2,9 @@
require 'mkmf'
-$CFLAGS += " -std=c99 -O3 -DNDEBUG"
+unless RUBY_PLATFORM =~ /mswin|mingw/
+ $CFLAGS += " -std=c99 -O3 -DNDEBUG"
+end
if RUBY_PLATFORM =~ /linux/
diff --git a/ruby/ext/google/protobuf_c/message.c b/ruby/ext/google/protobuf_c/message.c
index bc73d48c..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;
@@ -540,9 +544,9 @@ VALUE build_class_from_descriptor(Descriptor* desc) {
get_def_obj(desc->msgdef));
rb_define_alloc_func(klass, Message_alloc);
rb_require("google/protobuf/message_exts");
- rb_include_module(klass, rb_eval_string("Google::Protobuf::MessageExts"));
+ rb_include_module(klass, rb_eval_string("::Google::Protobuf::MessageExts"));
rb_extend_object(
- klass, rb_eval_string("Google::Protobuf::MessageExts::ClassMethods"));
+ klass, rb_eval_string("::Google::Protobuf::MessageExts::ClassMethods"));
rb_define_method(klass, "method_missing",
Message_method_missing, -1);
@@ -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 1437c0b5..5d0ac976 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, NULL);
} 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, NULL);
} 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/google-protobuf.gemspec b/ruby/google-protobuf.gemspec
index 998952d0..cc7625d4 100644
--- a/ruby/google-protobuf.gemspec
+++ b/ruby/google-protobuf.gemspec
@@ -1,6 +1,6 @@
Gem::Specification.new do |s|
s.name = "google-protobuf"
- s.version = "3.5.1"
+ s.version = "3.6.0"
s.licenses = ["BSD-3-Clause"]
s.summary = "Protocol Buffers"
s.description = "Protocol Buffers are Google's data interchange format."
diff --git a/ruby/lib/google/protobuf.rb b/ruby/lib/google/protobuf.rb
index 9b8d8231..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
@@ -60,8 +61,8 @@ module Google
msg.to_proto
end
- def self.encode_json(msg)
- msg.to_json
+ def self.encode_json(msg, options = {})
+ msg.to_json(options)
end
def self.decode(klass, proto)
diff --git a/ruby/lib/google/protobuf/message_exts.rb b/ruby/lib/google/protobuf/message_exts.rb
index e10266ba..f432f89f 100644
--- a/ruby/lib/google/protobuf/message_exts.rb
+++ b/ruby/lib/google/protobuf/message_exts.rb
@@ -40,8 +40,8 @@ module Google
module ClassMethods
end
- def to_json
- self.class.encode_json(self)
+ def to_json(options = {})
+ self.class.encode_json(self, options)
end
def to_proto
diff --git a/ruby/lib/google/protobuf/repeated_field.rb b/ruby/lib/google/protobuf/repeated_field.rb
index 11d6c2eb..2dae1e65 100644
--- a/ruby/lib/google/protobuf/repeated_field.rb
+++ b/ruby/lib/google/protobuf/repeated_field.rb
@@ -150,12 +150,12 @@ module Google
end
- %w(delete delete_at delete_if shift slice! unshift).each do |method_name|
+ %w(delete delete_at shift slice! unshift).each do |method_name|
define_array_wrapper_method(method_name)
end
- %w(collect! compact! fill flatten! insert reverse!
+ %w(collect! compact! delete_if fill flatten! insert reverse!
rotate! select! shuffle! sort! sort_by! uniq!).each do |method_name|
define_array_wrapper_with_result_method(method_name)
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/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 cadb1380..9e9ff385 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
@@ -373,7 +387,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
@@ -423,10 +437,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
@@ -575,7 +589,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
@@ -584,7 +598,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
@@ -609,10 +623,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
@@ -639,7 +653,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
@@ -706,17 +720,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
@@ -1015,7 +1029,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
@@ -1023,7 +1037,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
diff --git a/ruby/tests/encode_decode_test.rb b/ruby/tests/encode_decode_test.rb
index 09581ab0..2bd9b98b 100644
--- a/ruby/tests/encode_decode_test.rb
+++ b/ruby/tests/encode_decode_test.rb
@@ -60,4 +60,28 @@ class EncodeDecodeTest < Test::Unit::TestCase
to = A::B::C::TestMessage.encode(m.oneof_msg)
assert_equal '', to
end
+
+ def test_encode_json
+ msg = A::B::C::TestMessage.new({ optional_int32: 22 })
+ json = msg.to_json
+
+ to = A::B::C::TestMessage.decode_json(json)
+ assert_equal to.optional_int32, 22
+
+ msg = A::B::C::TestMessage.new({ optional_int32: 22 })
+ json = msg.to_json({ preserve_proto_fieldnames: true })
+
+ assert_match 'optional_int32', json
+
+ to = A::B::C::TestMessage.decode_json(json)
+ assert_equal 22, to.optional_int32
+
+ msg = A::B::C::TestMessage.new({ optional_int32: 22 })
+ json = A::B::C::TestMessage.encode_json(
+ msg,
+ { preserve_proto_fieldnames: true, emit_defaults: true }
+ )
+
+ assert_match 'optional_int32', json
+ end
end
diff --git a/ruby/tests/generated_code_test.rb b/ruby/tests/generated_code_test.rb
index b92b0462..431d681b 100644
--- a/ruby/tests/generated_code_test.rb
+++ b/ruby/tests/generated_code_test.rb
@@ -5,6 +5,7 @@ $LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__)))
require 'generated_code_pb'
require 'test_import_pb'
+require 'test_ruby_package_pb'
require 'test/unit'
class GeneratedCodeTest < Test::Unit::TestCase
@@ -15,5 +16,6 @@ class GeneratedCodeTest < Test::Unit::TestCase
# aspect of the extension (basic.rb is for that).
m = A::B::C::TestMessage.new()
m2 = FooBar::TestImportedMessage.new()
+ m3 = A::B::TestRubyPackageMessage.new()
end
end
diff --git a/ruby/tests/repeated_field_test.rb b/ruby/tests/repeated_field_test.rb
index b64c3991..61ac4afd 100644
--- a/ruby/tests/repeated_field_test.rb
+++ b/ruby/tests/repeated_field_test.rb
@@ -369,6 +369,15 @@ class RepeatedFieldTest < Test::Unit::TestCase
end
end
+ def test_delete_if
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.delete_if { |v| v == "bar" }
+ end
+ end
+
def test_fill
m = TestMessage.new
reference_arr = %w(foo bar baz)
diff --git a/ruby/tests/test_ruby_package.proto b/ruby/tests/test_ruby_package.proto
new file mode 100644
index 00000000..b8725620
--- /dev/null
+++ b/ruby/tests/test_ruby_package.proto
@@ -0,0 +1,7 @@
+syntax = "proto3";
+
+package foo_bar;
+
+option ruby_package = "A.B";
+
+message TestRubyPackageMessage {}
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 af2db52f..cb1b1006 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -56,28 +56,12 @@ clean-local:
CLEANFILES = $(protoc_outputs) unittest_proto_middleman \
testzip.jar testzip.list testzip.proto testzip.zip \
- no_warning_test.cc \
- google/protobuf/compiler/js/well_known_types_embed.cc \
- js_embed$(EXEEXT)
+ no_warning_test.cc
MAINTAINERCLEANFILES = \
Makefile.in
nobase_include_HEADERS = \
- google/protobuf/stubs/atomic_sequence_num.h \
- google/protobuf/stubs/atomicops.h \
- google/protobuf/stubs/atomicops_internals_power.h \
- google/protobuf/stubs/atomicops_internals_ppc_gcc.h \
- google/protobuf/stubs/atomicops_internals_arm64_gcc.h \
- google/protobuf/stubs/atomicops_internals_arm_gcc.h \
- google/protobuf/stubs/atomicops_internals_arm_qnx.h \
- google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h \
- google/protobuf/stubs/atomicops_internals_generic_gcc.h \
- google/protobuf/stubs/atomicops_internals_mips_gcc.h \
- google/protobuf/stubs/atomicops_internals_solaris.h \
- google/protobuf/stubs/atomicops_internals_tsan.h \
- google/protobuf/stubs/atomicops_internals_x86_gcc.h \
- google/protobuf/stubs/atomicops_internals_x86_msvc.h \
google/protobuf/stubs/callback.h \
google/protobuf/stubs/bytestream.h \
google/protobuf/stubs/casts.h \
@@ -90,14 +74,11 @@ nobase_include_HEADERS = \
google/protobuf/stubs/once.h \
google/protobuf/stubs/platform_macros.h \
google/protobuf/stubs/port.h \
- google/protobuf/stubs/scoped_ptr.h \
- google/protobuf/stubs/shared_ptr.h \
google/protobuf/stubs/singleton.h \
google/protobuf/stubs/status.h \
google/protobuf/stubs/stl_util.h \
google/protobuf/stubs/stringpiece.h \
google/protobuf/stubs/template_util.h \
- google/protobuf/stubs/type_traits.h \
google/protobuf/any.pb.h \
google/protobuf/api.pb.h \
google/protobuf/any.h \
@@ -119,6 +100,7 @@ nobase_include_HEADERS = \
google/protobuf/generated_message_util.h \
google/protobuf/has_bits.h \
google/protobuf/implicit_weak_message.h \
+ google/protobuf/inlined_string_field.h \
google/protobuf/map_entry.h \
google/protobuf/map_entry_lite.h \
google/protobuf/map_field.h \
@@ -163,7 +145,6 @@ nobase_include_HEADERS = \
google/protobuf/compiler/csharp/csharp_names.h \
google/protobuf/compiler/java/java_generator.h \
google/protobuf/compiler/java/java_names.h \
- google/protobuf/compiler/javanano/javanano_generator.h \
google/protobuf/compiler/js/js_generator.h \
google/protobuf/compiler/js/well_known_types_embed.h \
google/protobuf/compiler/objectivec/objectivec_generator.h \
@@ -183,14 +164,12 @@ nobase_include_HEADERS = \
lib_LTLIBRARIES = libprotobuf-lite.la libprotobuf.la libprotoc.la
libprotobuf_lite_la_LIBADD = $(PTHREAD_LIBS)
-libprotobuf_lite_la_LDFLAGS = -version-info 15:1:0 -export-dynamic -no-undefined
+libprotobuf_lite_la_LDFLAGS = -version-info 16:0:0 -export-dynamic -no-undefined
if HAVE_LD_VERSION_SCRIPT
libprotobuf_lite_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libprotobuf-lite.map
EXTRA_libprotobuf_lite_la_DEPENDENCIES = libprotobuf-lite.map
endif
libprotobuf_lite_la_SOURCES = \
- google/protobuf/stubs/atomicops_internals_x86_gcc.cc \
- google/protobuf/stubs/atomicops_internals_x86_msvc.cc \
google/protobuf/stubs/bytestream.cc \
google/protobuf/stubs/bytestream.h \
google/protobuf/stubs/common.cc \
@@ -201,8 +180,6 @@ libprotobuf_lite_la_SOURCES = \
google/protobuf/stubs/io_win32.h \
google/protobuf/stubs/map_util.h \
google/protobuf/stubs/mathutil.h \
- google/protobuf/stubs/once.cc \
- google/protobuf/stubs/shared_ptr.h \
google/protobuf/stubs/status.cc \
google/protobuf/stubs/status.h \
google/protobuf/stubs/status_macros.h \
@@ -233,7 +210,7 @@ libprotobuf_lite_la_SOURCES = \
google/protobuf/io/zero_copy_stream_impl_lite.cc
libprotobuf_la_LIBADD = $(PTHREAD_LIBS)
-libprotobuf_la_LDFLAGS = -version-info 15:1:0 -export-dynamic -no-undefined
+libprotobuf_la_LDFLAGS = -version-info 16:0:0 -export-dynamic -no-undefined
if HAVE_LD_VERSION_SCRIPT
libprotobuf_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libprotobuf.map
EXTRA_libprotobuf_la_DEPENDENCIES = libprotobuf.map
@@ -324,7 +301,7 @@ libprotobuf_la_SOURCES = \
nodist_libprotobuf_la_SOURCES = $(nodist_libprotobuf_lite_la_SOURCES)
libprotoc_la_LIBADD = $(PTHREAD_LIBS) libprotobuf.la
-libprotoc_la_LDFLAGS = -version-info 15:1:0 -export-dynamic -no-undefined
+libprotoc_la_LDFLAGS = -version-info 16:0:0 -export-dynamic -no-undefined
if HAVE_LD_VERSION_SCRIPT
libprotoc_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libprotoc.map
EXTRA_libprotoc_la_DEPENDENCIES = libprotoc.map
@@ -429,29 +406,6 @@ libprotoc_la_SOURCES = \
google/protobuf/compiler/java/java_doc_comment.h \
google/protobuf/compiler/js/js_generator.cc \
google/protobuf/compiler/js/well_known_types_embed.cc \
- google/protobuf/compiler/javanano/javanano_enum.cc \
- google/protobuf/compiler/javanano/javanano_enum.h \
- google/protobuf/compiler/javanano/javanano_enum_field.cc \
- google/protobuf/compiler/javanano/javanano_enum_field.h \
- google/protobuf/compiler/javanano/javanano_extension.cc \
- google/protobuf/compiler/javanano/javanano_extension.h \
- google/protobuf/compiler/javanano/javanano_field.cc \
- google/protobuf/compiler/javanano/javanano_field.h \
- google/protobuf/compiler/javanano/javanano_file.cc \
- google/protobuf/compiler/javanano/javanano_file.h \
- google/protobuf/compiler/javanano/javanano_generator.cc \
- google/protobuf/compiler/javanano/javanano_generator.h \
- google/protobuf/compiler/javanano/javanano_helpers.cc \
- google/protobuf/compiler/javanano/javanano_helpers.h \
- google/protobuf/compiler/javanano/javanano_map_field.cc \
- google/protobuf/compiler/javanano/javanano_map_field.h \
- google/protobuf/compiler/javanano/javanano_message.cc \
- google/protobuf/compiler/javanano/javanano_message.h \
- google/protobuf/compiler/javanano/javanano_message_field.cc \
- google/protobuf/compiler/javanano/javanano_message_field.h \
- google/protobuf/compiler/javanano/javanano_params.h \
- google/protobuf/compiler/javanano/javanano_primitive_field.cc \
- google/protobuf/compiler/javanano/javanano_primitive_field.h \
google/protobuf/compiler/objectivec/objectivec_enum.cc \
google/protobuf/compiler/objectivec/objectivec_enum.h \
google/protobuf/compiler/objectivec/objectivec_enum_field.cc \
@@ -515,22 +469,6 @@ bin_PROGRAMS = protoc
protoc_LDADD = $(PTHREAD_LIBS) libprotobuf.la libprotoc.la
protoc_SOURCES = google/protobuf/compiler/main.cc
-# The special JS code for the well-known types is linked into the compiler via
-# well_known_types_embed.cc, which is generated from .js source files. We have
-# to build the js_embed binary using $(CXX_FOR_BUILD) so that it is executable
-# on the build machine in a cross-compilation setup.
-js_embed$(EXEEXT): $(srcdir)/google/protobuf/compiler/js/embed.cc
- $(CXX_FOR_BUILD) -o $@ $<
-js_well_known_types_sources = \
- google/protobuf/compiler/js/well_known_types/any.js \
- google/protobuf/compiler/js/well_known_types/struct.js \
- google/protobuf/compiler/js/well_known_types/timestamp.js
-# We have to cd to $(srcdir) so that out-of-tree builds work properly.
-google/protobuf/compiler/js/well_known_types_embed.cc: js_embed$(EXEEXT) $(js_well_known_types_sources)
- mkdir -p `dirname $@` && \
- oldpwd=`pwd` && cd $(srcdir) && \
- $$oldpwd/js_embed$(EXEEXT) $(js_well_known_types_sources) > $$oldpwd/$@
-
# Tests ==============================================================
protoc_inputs = \
@@ -609,7 +547,6 @@ EXTRA_DIST = \
google/protobuf/package_info.h \
google/protobuf/io/package_info.h \
google/protobuf/util/package_info.h \
- google/protobuf/compiler/js/embed.cc \
google/protobuf/compiler/ruby/ruby_generated_code.proto \
google/protobuf/compiler/ruby/ruby_generated_code_pb.rb \
google/protobuf/compiler/package_info.h \
@@ -749,20 +686,25 @@ COMMON_TEST_SOURCES = \
google/protobuf/map_test_util_impl.h \
google/protobuf/test_util.cc \
google/protobuf/test_util.h \
+ google/protobuf/test_util.inc \
google/protobuf/testing/googletest.cc \
google/protobuf/testing/googletest.h \
google/protobuf/testing/file.cc \
google/protobuf/testing/file.h
+GOOGLETEST_BUILD_DIR=../third_party/googletest/googletest
+GOOGLEMOCK_BUILD_DIR=../third_party/googletest/googlemock
+GOOGLETEST_SRC_DIR=$(srcdir)/../third_party/googletest/googletest
+GOOGLEMOCK_SRC_DIR=$(srcdir)/../third_party/googletest/googlemock
check_PROGRAMS = protoc protobuf-test protobuf-lazy-descriptor-test \
protobuf-lite-test test_plugin protobuf-lite-arena-test \
no-warning-test $(GZCHECKPROGRAMS)
protobuf_test_LDADD = $(PTHREAD_LIBS) libprotobuf.la libprotoc.la \
- ../gmock/gtest/lib/libgtest.la \
- ../gmock/lib/libgmock.la \
- ../gmock/lib/libgmock_main.la
-protobuf_test_CPPFLAGS = -I$(srcdir)/../gmock/gtest/include \
- -I$(srcdir)/../gmock/include
+ $(GOOGLETEST_BUILD_DIR)/lib/libgtest.la \
+ $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock.la \
+ $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock_main.la
+protobuf_test_CPPFLAGS = -I$(GOOGLETEST_SRC_DIR)/include \
+ -I$(GOOGLEMOCK_SRC_DIR)/include
# Disable optimization for tests unless the user explicitly asked for it,
# since test_util.cc takes forever to compile with optimization (with GCC).
# See configure.ac for more info.
@@ -772,7 +714,6 @@ protobuf_test_SOURCES = \
google/protobuf/stubs/common_unittest.cc \
google/protobuf/stubs/int128_unittest.cc \
google/protobuf/stubs/io_win32_unittest.cc \
- google/protobuf/stubs/once_unittest.cc \
google/protobuf/stubs/statusor_test.cc \
google/protobuf/stubs/status_test.cc \
google/protobuf/stubs/stringpiece_unittest.cc \
@@ -781,7 +722,6 @@ protobuf_test_SOURCES = \
google/protobuf/stubs/strutil_unittest.cc \
google/protobuf/stubs/template_util_unittest.cc \
google/protobuf/stubs/time_test.cc \
- google/protobuf/stubs/type_traits_unittest.cc \
google/protobuf/any_test.cc \
google/protobuf/arenastring_unittest.cc \
google/protobuf/arena_unittest.cc \
@@ -794,10 +734,11 @@ protobuf_test_SOURCES = \
google/protobuf/map_field_test.cc \
google/protobuf/map_test.cc \
google/protobuf/message_unittest.cc \
+ google/protobuf/message_unittest.inc \
google/protobuf/no_field_presence_test.cc \
google/protobuf/preserve_unknown_enum_test.cc \
- google/protobuf/proto3_arena_unittest.cc \
google/protobuf/proto3_arena_lite_unittest.cc \
+ google/protobuf/proto3_arena_unittest.cc \
google/protobuf/proto3_lite_unittest.cc \
google/protobuf/reflection_ops_unittest.cc \
google/protobuf/repeated_field_reflection_unittest.cc \
@@ -821,6 +762,7 @@ protobuf_test_SOURCES = \
google/protobuf/compiler/cpp/cpp_move_unittest.cc \
google/protobuf/compiler/cpp/cpp_unittest.h \
google/protobuf/compiler/cpp/cpp_unittest.cc \
+ google/protobuf/compiler/cpp/cpp_unittest.inc \
google/protobuf/compiler/cpp/cpp_plugin_unittest.cc \
google/protobuf/compiler/cpp/metadata_test.cc \
google/protobuf/compiler/java/java_plugin_unittest.cc \
@@ -850,11 +792,11 @@ $(am_protobuf_test_OBJECTS): unittest_proto_middleman
# Run cpp_unittest again with PROTOBUF_TEST_NO_DESCRIPTORS defined.
protobuf_lazy_descriptor_test_LDADD = $(PTHREAD_LIBS) libprotobuf.la \
libprotoc.la \
- ../gmock/gtest/lib/libgtest.la \
- ../gmock/lib/libgmock.la \
- ../gmock/lib/libgmock_main.la
-protobuf_lazy_descriptor_test_CPPFLAGS = -I$(srcdir)/../gmock/include \
- -I$(srcdir)/../gmock/gtest/include \
+ $(GOOGLETEST_BUILD_DIR)/lib/libgtest.la \
+ $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock.la \
+ $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock_main.la
+protobuf_lazy_descriptor_test_CPPFLAGS = -I$(GOOGLEMOCK_SRC_DIR)/include \
+ -I$(GOOGLETEST_SRC_DIR)/include \
-DPROTOBUF_TEST_NO_DESCRIPTORS
protobuf_lazy_descriptor_test_CXXFLAGS = $(NO_OPT_CXXFLAGS)
protobuf_lazy_descriptor_test_SOURCES = \
@@ -875,12 +817,12 @@ COMMON_LITE_TEST_SOURCES = \
# depend on gtest because our internal version of gtest depend on proto
# full runtime and we want to make sure this test builds without full
# runtime.
-protobuf_lite_test_LDADD = $(PTHREAD_LIBS) libprotobuf-lite.la \
- ../gmock/gtest/lib/libgtest.la \
- ../gmock/lib/libgmock.la \
- ../gmock/lib/libgmock_main.la
-protobuf_lite_test_CPPFLAGS= -I$(srcdir)/../gmock/include \
- -I$(srcdir)/../gmock/gtest/include
+protobuf_lite_test_LDADD = $(PTHREAD_LIBS) libprotobuf-lite.la \
+ $(GOOGLETEST_BUILD_DIR)/lib/libgtest.la \
+ $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock.la \
+ $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock_main.la
+protobuf_lite_test_CPPFLAGS= -I$(GOOGLEMOCK_SRC_DIR)/include \
+ -I$(GOOGLETEST_SRC_DIR)/include
protobuf_lite_test_CXXFLAGS = $(NO_OPT_CXXFLAGS)
protobuf_lite_test_SOURCES = \
google/protobuf/lite_unittest.cc \
@@ -892,11 +834,11 @@ $(am_protobuf_lite_test_OBJECTS): unittest_proto_middleman
# gtest when building the test internally our memory sanitizer doesn't detect
# memory leaks (don't know why).
protobuf_lite_arena_test_LDADD = $(PTHREAD_LIBS) libprotobuf-lite.la \
- ../gmock/gtest/lib/libgtest.la \
- ../gmock/lib/libgmock.la \
- ../gmock/lib/libgmock_main.la
-protobuf_lite_arena_test_CPPFLAGS = -I$(srcdir)/../gmock/include \
- -I$(srcdir)/../gmock/gtest/include
+ $(GOOGLETEST_BUILD_DIR)/lib/libgtest.la \
+ $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock.la \
+ $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock_main.la
+protobuf_lite_arena_test_CPPFLAGS = -I$(GOOGLEMOCK_SRC_DIR)/include \
+ -I$(GOOGLETEST_SRC_DIR)/include
protobuf_lite_arena_test_CXXFLAGS = $(NO_OPT_CXXFLAGS)
protobuf_lite_arena_test_SOURCES = \
google/protobuf/lite_arena_unittest.cc \
@@ -906,8 +848,8 @@ $(am_protobuf_lite_arena_test_OBJECTS): unittest_proto_middleman
# Test plugin binary.
test_plugin_LDADD = $(PTHREAD_LIBS) libprotobuf.la libprotoc.la \
- ../gmock/gtest/lib/libgtest.la
-test_plugin_CPPFLAGS = -I$(srcdir)/../gmock/gtest/include
+ $(GOOGLETEST_BUILD_DIR)/lib/libgtest.la
+test_plugin_CPPFLAGS = -I$(GOOGLETEST_SRC_DIR)/include
test_plugin_SOURCES = \
google/protobuf/compiler/mock_code_generator.cc \
google/protobuf/testing/file.cc \
@@ -928,15 +870,13 @@ endif
no_warning_test.cc:
echo "// Generated from Makefile.am" > no_warning_test.cc
for FILE in $(nobase_include_HEADERS); do \
- if ! echo $${FILE} | grep "atomicops"; then \
- echo "#include <$${FILE}>" >> no_warning_test.cc; \
- fi \
+ echo "#include <$${FILE}>" >> no_warning_test.cc; \
done
echo "int main(int, char**) { return 0; }" >> 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 3ae23fa6..3cbeb3e6 100644
--- a/src/README.md
+++ b/src/README.md
@@ -15,29 +15,35 @@ To build protobuf from source, the following tools are needed:
* autoconf
* automake
* libtool
- * curl (used to download gmock)
* make
* g++
* unzip
-On Ubuntu, you can install them with:
+On Ubuntu/Debian, you can install them with:
$ sudo apt-get install autoconf automake libtool curl make g++ unzip
On other platforms, please use the corresponding package managing tool to
install them before proceeding.
-If you get the source from github, you need to generate the configure script
-first:
+To get the source, download one of the release .tar.gz or .zip packages in the
+release page:
- $ ./autogen.sh
+ https://github.com/google/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
+contains C++ source already); if you need C++ and multiple other languages,
+download `protobuf-all-[VERSION].tar.gz`.
-This will download gmock source (which is used for C++ Protocol Buffer
-unit-tests) to the current directory and run automake, autoconf, etc.
-to generate the configure script and various template makefiles.
+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):
-You can skip this step if you are using a release package (which already
-contains gmock and the configure script).
+ $ git clone https://github.com/google/protobuf.git
+ $ cd protobuf
+ $ git submodule update --init --recursive
+ $ ./autogen.sh
To build and install the C++ Protocol Buffer runtime and the Protocol
Buffer compiler (protoc) execute the following:
@@ -55,122 +61,122 @@ Proceed at your own risk.
For advanced usage information on configure and make, please refer to the
autoconf documentation:
- http://www.gnu.org/software/autoconf/manual/autoconf.html#Running-configure-Scripts
+ http://www.gnu.org/software/autoconf/manual/autoconf.html#Running-configure-Scripts
**Hint on install location**
- By default, the package will be installed to /usr/local. However,
- on many platforms, /usr/local/lib is not part of LD_LIBRARY_PATH.
- You can add it, but it may be easier to just install to /usr
- instead. To do this, invoke configure as follows:
+By default, the package will be installed to /usr/local. However,
+on many platforms, /usr/local/lib is not part of LD_LIBRARY_PATH.
+You can add it, but it may be easier to just install to /usr
+instead. To do this, invoke configure as follows:
./configure --prefix=/usr
- If you already built the package with a different prefix, make sure
- to run "make clean" before building again.
+If you already built the package with a different prefix, make sure
+to run "make clean" before building again.
**Compiling dependent packages**
- To compile a package that uses Protocol Buffers, you need to pass
- various flags to your compiler and linker. As of version 2.2.0,
- Protocol Buffers integrates with pkg-config to manage this. If you
- have pkg-config installed, then you can invoke it to get a list of
- flags like so:
+To compile a package that uses Protocol Buffers, you need to pass
+various flags to your compiler and linker. As of version 2.2.0,
+Protocol Buffers integrates with pkg-config to manage this. If you
+have pkg-config installed, then you can invoke it to get a list of
+flags like so:
pkg-config --cflags protobuf # print compiler flags
pkg-config --libs protobuf # print linker flags
pkg-config --cflags --libs protobuf # print both
- For example:
+For example:
c++ my_program.cc my_proto.pb.cc `pkg-config --cflags --libs protobuf`
- Note that packages written prior to the 2.2.0 release of Protocol
- Buffers may not yet integrate with pkg-config to get flags, and may
- not pass the correct set of flags to correctly link against
- libprotobuf. If the package in question uses autoconf, you can
- often fix the problem by invoking its configure script like:
+Note that packages written prior to the 2.2.0 release of Protocol
+Buffers may not yet integrate with pkg-config to get flags, and may
+not pass the correct set of flags to correctly link against
+libprotobuf. If the package in question uses autoconf, you can
+often fix the problem by invoking its configure script like:
configure CXXFLAGS="$(pkg-config --cflags protobuf)" \
LIBS="$(pkg-config --libs protobuf)"
- This will force it to use the correct flags.
+This will force it to use the correct flags.
- If you are writing an autoconf-based package that uses Protocol
- Buffers, you should probably use the PKG_CHECK_MODULES macro in your
- configure script like:
+If you are writing an autoconf-based package that uses Protocol
+Buffers, you should probably use the PKG_CHECK_MODULES macro in your
+configure script like:
PKG_CHECK_MODULES([protobuf], [protobuf])
- See the pkg-config man page for more info.
+See the pkg-config man page for more info.
- If you only want protobuf-lite, substitute "protobuf-lite" in place
- of "protobuf" in these examples.
+If you only want protobuf-lite, substitute "protobuf-lite" in place
+of "protobuf" in these examples.
**Note for Mac users**
- For a Mac system, Unix tools are not available by default. You will first need
- to install Xcode from the Mac AppStore and then run the following command from
- a terminal:
+For a Mac system, Unix tools are not available by default. You will first need
+to install Xcode from the Mac AppStore and then run the following command from
+a terminal:
$ sudo xcode-select --install
- To install Unix tools, you can install "port" following the instructions at
- https://www.macports.org . This will reside in /opt/local/bin/port for most
- Mac installations.
+To install Unix tools, you can install "port" following the instructions at
+https://www.macports.org . This will reside in /opt/local/bin/port for most
+Mac installations.
$ sudo /opt/local/bin/port install autoconf automake libtool
- Then follow the Unix instructions above.
+Then follow the Unix instructions above.
**Note for cross-compiling**
- The makefiles normally invoke the protoc executable that they just
- built in order to build tests. When cross-compiling, the protoc
- executable may not be executable on the host machine. In this case,
- you must build a copy of protoc for the host machine first, then use
- the --with-protoc option to tell configure to use it instead. For
- example:
+The makefiles normally invoke the protoc executable that they just
+built in order to build tests. When cross-compiling, the protoc
+executable may not be executable on the host machine. In this case,
+you must build a copy of protoc for the host machine first, then use
+the --with-protoc option to tell configure to use it instead. For
+example:
./configure --with-protoc=protoc
- This will use the installed protoc (found in your $PATH) instead of
- trying to execute the one built during the build process. You can
- also use an executable that hasn't been installed. For example, if
- you built the protobuf package for your host machine in ../host,
- you might do:
+This will use the installed protoc (found in your $PATH) instead of
+trying to execute the one built during the build process. You can
+also use an executable that hasn't been installed. For example, if
+you built the protobuf package for your host machine in ../host,
+you might do:
./configure --with-protoc=../host/src/protoc
- Either way, you must make sure that the protoc executable you use
- has the same version as the protobuf source code you are trying to
- use it with.
+Either way, you must make sure that the protoc executable you use
+has the same version as the protobuf source code you are trying to
+use it with.
**Note for Solaris users**
- Solaris 10 x86 has a bug that will make linking fail, complaining
- about libstdc++.la being invalid. We have included a work-around
- in this package. To use the work-around, run configure as follows:
+Solaris 10 x86 has a bug that will make linking fail, complaining
+about libstdc++.la being invalid. We have included a work-around
+in this package. To use the work-around, run configure as follows:
./configure LDFLAGS=-L$PWD/src/solaris
- See src/solaris/libstdc++.la for more info on this bug.
+See src/solaris/libstdc++.la for more info on this bug.
**Note for HP C++ Tru64 users**
- To compile invoke configure as follows:
+To compile invoke configure as follows:
./configure CXXFLAGS="-O -std ansi -ieee -D__USE_STD_IOSTREAM"
- Also, you will need to use gmake instead of make.
+Also, you will need to use gmake instead of make.
**Note for AIX users**
- Compile using the IBM xlC C++ compiler as follows:
+Compile using the IBM xlC C++ compiler as follows:
./configure CXX=xlC
- Also, you will need to use GNU `make` (`gmake`) instead of AIX `make`.
+Also, you will need to use GNU `make` (`gmake`) instead of AIX `make`.
C++ Installation - Windows
--------------------------
@@ -178,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
+ https://github.com/google/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.cc b/src/google/protobuf/any.cc
index 83edba57..b94529e6 100644
--- a/src/google/protobuf/any.cc
+++ b/src/google/protobuf/any.cc
@@ -32,6 +32,7 @@
#include <google/protobuf/generated_message_util.h>
+
namespace google {
namespace protobuf {
namespace internal {
@@ -84,15 +85,23 @@ bool AnyMetadata::InternalIs(const Descriptor* descriptor) const {
return full_name == descriptor->full_name();
}
-bool ParseAnyTypeUrl(const string& type_url, string* full_type_name) {
+bool ParseAnyTypeUrl(const string& type_url, string* url_prefix,
+ string* full_type_name) {
size_t pos = type_url.find_last_of("/");
if (pos == string::npos || pos + 1 == type_url.size()) {
return false;
}
+ if (url_prefix) {
+ *url_prefix = type_url.substr(0, pos + 1);
+ }
*full_type_name = type_url.substr(pos + 1);
return true;
}
+bool ParseAnyTypeUrl(const string& type_url, string* full_type_name) {
+ return ParseAnyTypeUrl(type_url, NULL, full_type_name);
+}
+
bool GetAnyFieldDescriptors(const Message& message,
const FieldDescriptor** type_url_field,
diff --git a/src/google/protobuf/any.h b/src/google/protobuf/any.h
index c2c27ec3..a34e5f8e 100644
--- a/src/google/protobuf/any.h
+++ b/src/google/protobuf/any.h
@@ -92,8 +92,19 @@ extern const char kTypeGoogleProdComPrefix[]; // "type.googleprod.com/".
// "type.googleapis.com/rpc.QueryOrigin" will return "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.
+//
+// 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);
+// 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);
+
// See if message is of type google.protobuf.Any, if so, return the descriptors
// for "type_url" and "value" fields.
bool GetAnyFieldDescriptors(const Message& message,
diff --git a/src/google/protobuf/any.pb.cc b/src/google/protobuf/any.pb.cc
index 4335e467..d0fc2905 100644
--- a/src/google/protobuf/any.pb.cc
+++ b/src/google/protobuf/any.pb.cc
@@ -7,7 +7,6 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
@@ -19,6 +18,7 @@
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
+
namespace google {
namespace protobuf {
class AnyDefaultTypeInternal {
@@ -29,14 +29,9 @@ class AnyDefaultTypeInternal {
} // namespace protobuf
} // namespace google
namespace protobuf_google_2fprotobuf_2fany_2eproto {
-void InitDefaultsAnyImpl() {
+static void InitDefaultsAny() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_Any_default_instance_;
new (ptr) ::google::protobuf::Any();
@@ -45,9 +40,11 @@ void InitDefaultsAnyImpl() {
::google::protobuf::Any::InitAsDefaultInstance();
}
-void InitDefaultsAny() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsAnyImpl);
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Any =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsAny}, {}};
+
+void InitDefaults() {
+ ::google::protobuf::internal::InitSCC(&scc_info_Any.base);
}
::google::protobuf::Metadata file_level_metadata[1];
@@ -69,17 +66,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Any_default_instance_),
};
-void protobuf_AssignDescriptors() {
+static void protobuf_AssignDescriptors() {
AddDescriptors();
- ::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/any.proto", schemas, file_default_instances, TableStruct::offsets, factory,
+ "google/protobuf/any.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
-void protobuf_AssignDescriptorsOnce() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
+static 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;
@@ -88,7 +84,7 @@ void protobuf_RegisterTypes(const ::std::string&) {
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
-void AddDescriptorsImpl() {
+static void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\031google/protobuf/any.proto\022\017google.prot"
@@ -105,8 +101,8 @@ void AddDescriptorsImpl() {
}
void AddDescriptors() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
+ 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 {
@@ -134,6 +130,11 @@ void Any::PackFrom(const ::google::protobuf::Message& message,
bool Any::UnpackTo(::google::protobuf::Message* message) const {
return _any_metadata_.UnpackTo(message);
}
+bool Any::ParseAnyTypeUrl(const string& type_url,
+ string* full_type_name) {
+ return ::google::protobuf::internal::ParseAnyTypeUrl(type_url,
+ full_type_name);
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Any::kTypeUrlFieldNumber;
@@ -142,16 +143,14 @@ const int Any::kValueFieldNumber;
Any::Any()
: ::google::protobuf::Message(), _internal_metadata_(NULL), _any_metadata_(&type_url_, &value_) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Any)
}
Any::Any(const Any& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- _cached_size_(0),
_any_metadata_(&type_url_, &value_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -168,7 +167,6 @@ Any::Any(const Any& from)
void Any::SharedCtor() {
type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- _cached_size_ = 0;
}
Any::~Any() {
@@ -182,9 +180,7 @@ void Any::SharedDtor() {
}
void Any::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Any::descriptor() {
::protobuf_google_2fprotobuf_2fany_2eproto::protobuf_AssignDescriptorsOnce();
@@ -192,7 +188,7 @@ const ::google::protobuf::Descriptor* Any::descriptor() {
}
const Any& Any::default_instance() {
- ::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base);
return *internal_default_instance();
}
@@ -214,7 +210,7 @@ bool Any::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Any)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -352,9 +348,7 @@ size_t Any::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -414,10 +408,11 @@ void Any::Swap(Any* other) {
}
void Any::InternalSwap(Any* other) {
using std::swap;
- type_url_.Swap(&other->type_url_);
- value_.Swap(&other->value_);
+ 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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Any::GetMetadata() const {
@@ -431,7 +426,7 @@ void Any::InternalSwap(Any* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Any* Arena::Create< ::google::protobuf::Any >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Any* Arena::CreateMaybeMessage< ::google::protobuf::Any >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::Any >(arena);
}
} // namespace protobuf
diff --git a/src/google/protobuf/any.pb.h b/src/google/protobuf/any.pb.h
index 14c21a8f..8a4c7f97 100644
--- a/src/google/protobuf/any.pb.h
+++ b/src/google/protobuf/any.pb.h
@@ -1,19 +1,19 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/any.proto
-#ifndef PROTOBUF_google_2fprotobuf_2fany_2eproto_INCLUDED
-#define PROTOBUF_google_2fprotobuf_2fany_2eproto_INCLUDED
+#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto
+#define PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3005000
+#if GOOGLE_PROTOBUF_VERSION < 3006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3005001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -24,6 +24,7 @@
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -31,6 +32,7 @@
#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
namespace protobuf_google_2fprotobuf_2fany_2eproto {
// Internal implementation detail -- do not use these members.
@@ -43,11 +45,6 @@ struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::uint32 offsets[];
};
void LIBPROTOBUF_EXPORT AddDescriptors();
-void LIBPROTOBUF_EXPORT InitDefaultsAnyImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsAny();
-inline void LIBPROTOBUF_EXPORT InitDefaults() {
- InitDefaultsAny();
-}
} // namespace protobuf_google_2fprotobuf_2fany_2eproto
namespace google {
namespace protobuf {
@@ -58,7 +55,7 @@ LIBPROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_;
} // namespace google
namespace google {
namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Any* Arena::Create< ::google::protobuf::Any>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Any* Arena::CreateMaybeMessage<::google::protobuf::Any>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -100,7 +97,7 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
return reinterpret_cast<const Any*>(
&_Any_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
0;
// implements Any -----------------------------------------------
@@ -112,6 +109,8 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
template<typename T> bool Is() const {
return _any_metadata_.Is<T>();
}
+ static bool ParseAnyTypeUrl(const string& type_url,
+ string* full_type_name);
void Swap(Any* other);
friend void swap(Any& a, Any& b) {
@@ -120,32 +119,33 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
// implements Message ----------------------------------------------
- inline Any* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<Any>(NULL);
+ inline Any* New() const final {
+ return CreateMaybeMessage<Any>(NULL);
}
- Any* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<Any>(arena);
+ Any* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Any>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Any& from);
void MergeFrom(const Any& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Any* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
@@ -156,7 +156,7 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -196,10 +196,9 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::ArenaStringPtr type_url_;
::google::protobuf::internal::ArenaStringPtr value_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::internal::AnyMetadata _any_metadata_;
friend struct ::protobuf_google_2fprotobuf_2fany_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAnyImpl();
};
// ===================================================================
@@ -329,4 +328,4 @@ inline void Any::set_allocated_value(::std::string* value) {
// @@protoc_insertion_point(global_scope)
-#endif // PROTOBUF_google_2fprotobuf_2fany_2eproto_INCLUDED
+#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto
diff --git a/src/google/protobuf/api.pb.cc b/src/google/protobuf/api.pb.cc
index b0354551..273307c7 100644
--- a/src/google/protobuf/api.pb.cc
+++ b/src/google/protobuf/api.pb.cc
@@ -7,7 +7,6 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
@@ -19,6 +18,17 @@
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
+
+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
namespace google {
namespace protobuf {
class ApiDefaultTypeInternal {
@@ -39,18 +49,9 @@ class MixinDefaultTypeInternal {
} // namespace protobuf
} // namespace google
namespace protobuf_google_2fprotobuf_2fapi_2eproto {
-void InitDefaultsApiImpl() {
+static void InitDefaultsApi() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethod();
- protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
- protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext();
- protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixin();
{
void* ptr = &::google::protobuf::_Api_default_instance_;
new (ptr) ::google::protobuf::Api();
@@ -59,20 +60,16 @@ void InitDefaultsApiImpl() {
::google::protobuf::Api::InitAsDefaultInstance();
}
-void InitDefaultsApi() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsApiImpl);
-}
+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,}};
-void InitDefaultsMethodImpl() {
+static void InitDefaultsMethod() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
{
void* ptr = &::google::protobuf::_Method_default_instance_;
new (ptr) ::google::protobuf::Method();
@@ -81,19 +78,13 @@ void InitDefaultsMethodImpl() {
::google::protobuf::Method::InitAsDefaultInstance();
}
-void InitDefaultsMethod() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMethodImpl);
-}
+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,}};
-void InitDefaultsMixinImpl() {
+static void InitDefaultsMixin() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_Mixin_default_instance_;
new (ptr) ::google::protobuf::Mixin();
@@ -102,9 +93,13 @@ void InitDefaultsMixinImpl() {
::google::protobuf::Mixin::InitAsDefaultInstance();
}
-void InitDefaultsMixin() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMixinImpl);
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsMixin}, {}};
+
+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);
}
::google::protobuf::Metadata file_level_metadata[3];
@@ -154,17 +149,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Mixin_default_instance_),
};
-void protobuf_AssignDescriptors() {
+static void protobuf_AssignDescriptors() {
AddDescriptors();
- ::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/api.proto", schemas, file_default_instances, TableStruct::offsets, factory,
+ "google/protobuf/api.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
-void protobuf_AssignDescriptorsOnce() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
+static 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;
@@ -173,7 +167,7 @@ void protobuf_RegisterTypes(const ::std::string&) {
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 3);
}
-void AddDescriptorsImpl() {
+static void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\031google/protobuf/api.proto\022\017google.prot"
@@ -205,8 +199,8 @@ void AddDescriptorsImpl() {
}
void AddDescriptors() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
+ 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 {
@@ -245,9 +239,8 @@ const int Api::kSyntaxFieldNumber;
Api::Api()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApi();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Api.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Api)
}
@@ -256,8 +249,7 @@ Api::Api(const Api& from)
_internal_metadata_(NULL),
methods_(from.methods_),
options_(from.options_),
- mixins_(from.mixins_),
- _cached_size_(0) {
+ mixins_(from.mixins_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
@@ -282,7 +274,6 @@ void Api::SharedCtor() {
::memset(&source_context_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&syntax_) -
reinterpret_cast<char*>(&source_context_)) + sizeof(syntax_));
- _cached_size_ = 0;
}
Api::~Api() {
@@ -297,9 +288,7 @@ void Api::SharedDtor() {
}
void Api::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Api::descriptor() {
::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
@@ -307,7 +296,7 @@ const ::google::protobuf::Descriptor* Api::descriptor() {
}
const Api& Api::default_instance() {
- ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApi();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Api.base);
return *internal_default_instance();
}
@@ -337,7 +326,7 @@ bool Api::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Api)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -425,7 +414,7 @@ bool Api::MergePartialFromCodedStream(
case 7: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) {
- int value;
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -503,7 +492,7 @@ void Api::SerializeWithCachedSizes(
// .google.protobuf.SourceContext source_context = 5;
if (this->has_source_context()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 5, *source_context_, output);
+ 5, this->_internal_source_context(), output);
}
// repeated .google.protobuf.Mixin mixins = 6;
@@ -577,7 +566,7 @@ void Api::SerializeWithCachedSizes(
if (this->has_source_context()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 5, *source_context_, deterministic, target);
+ 5, this->_internal_source_context(), deterministic, target);
}
// repeated .google.protobuf.Mixin mixins = 6;
@@ -672,9 +661,7 @@ size_t Api::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -746,12 +733,13 @@ void Api::InternalSwap(Api* other) {
CastToBase(&methods_)->InternalSwap(CastToBase(&other->methods_));
CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
CastToBase(&mixins_)->InternalSwap(CastToBase(&other->mixins_));
- name_.Swap(&other->name_);
- version_.Swap(&other->version_);
+ name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ version_.Swap(&other->version_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
swap(source_context_, other->source_context_);
swap(syntax_, other->syntax_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Api::GetMetadata() const {
@@ -779,17 +767,15 @@ const int Method::kSyntaxFieldNumber;
Method::Method()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethod();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Method)
}
Method::Method(const Method& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- options_(from.options_),
- _cached_size_(0) {
+ options_(from.options_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
@@ -816,7 +802,6 @@ void Method::SharedCtor() {
::memset(&request_streaming_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&syntax_) -
reinterpret_cast<char*>(&request_streaming_)) + sizeof(syntax_));
- _cached_size_ = 0;
}
Method::~Method() {
@@ -831,9 +816,7 @@ void Method::SharedDtor() {
}
void Method::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Method::descriptor() {
::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
@@ -841,7 +824,7 @@ const ::google::protobuf::Descriptor* Method::descriptor() {
}
const Method& Method::default_instance() {
- ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethod();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base);
return *internal_default_instance();
}
@@ -868,7 +851,7 @@ bool Method::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Method)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -964,7 +947,7 @@ bool Method::MergePartialFromCodedStream(
case 7: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) {
- int value;
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -1193,9 +1176,7 @@ size_t Method::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -1270,14 +1251,16 @@ void Method::Swap(Method* other) {
void Method::InternalSwap(Method* other) {
using std::swap;
CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
- name_.Swap(&other->name_);
- request_type_url_.Swap(&other->request_type_url_);
- response_type_url_.Swap(&other->response_type_url_);
+ name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ request_type_url_.Swap(&other->request_type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ response_type_url_.Swap(&other->response_type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
swap(request_streaming_, other->request_streaming_);
swap(response_streaming_, other->response_streaming_);
swap(syntax_, other->syntax_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Method::GetMetadata() const {
@@ -1297,16 +1280,14 @@ const int Mixin::kRootFieldNumber;
Mixin::Mixin()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixin();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Mixin)
}
Mixin::Mixin(const Mixin& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
@@ -1322,7 +1303,6 @@ Mixin::Mixin(const Mixin& from)
void Mixin::SharedCtor() {
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
root_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- _cached_size_ = 0;
}
Mixin::~Mixin() {
@@ -1336,9 +1316,7 @@ void Mixin::SharedDtor() {
}
void Mixin::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Mixin::descriptor() {
::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
@@ -1346,7 +1324,7 @@ const ::google::protobuf::Descriptor* Mixin::descriptor() {
}
const Mixin& Mixin::default_instance() {
- ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixin();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base);
return *internal_default_instance();
}
@@ -1368,7 +1346,7 @@ bool Mixin::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Mixin)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -1518,9 +1496,7 @@ size_t Mixin::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -1580,10 +1556,11 @@ void Mixin::Swap(Mixin* other) {
}
void Mixin::InternalSwap(Mixin* other) {
using std::swap;
- name_.Swap(&other->name_);
- root_.Swap(&other->root_);
+ name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ root_.Swap(&other->root_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Mixin::GetMetadata() const {
@@ -1597,13 +1574,13 @@ void Mixin::InternalSwap(Mixin* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Api* Arena::Create< ::google::protobuf::Api >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::Create< ::google::protobuf::Method >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::Create< ::google::protobuf::Mixin >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Mixin* Arena::CreateMaybeMessage< ::google::protobuf::Mixin >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::Mixin >(arena);
}
} // namespace protobuf
diff --git a/src/google/protobuf/api.pb.h b/src/google/protobuf/api.pb.h
index 648aa308..0f90f411 100644
--- a/src/google/protobuf/api.pb.h
+++ b/src/google/protobuf/api.pb.h
@@ -1,19 +1,19 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/api.proto
-#ifndef PROTOBUF_google_2fprotobuf_2fapi_2eproto_INCLUDED
-#define PROTOBUF_google_2fprotobuf_2fapi_2eproto_INCLUDED
+#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto
+#define PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3005000
+#if GOOGLE_PROTOBUF_VERSION < 3006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3005001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -24,6 +24,7 @@
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -32,6 +33,7 @@
#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
namespace protobuf_google_2fprotobuf_2fapi_2eproto {
// Internal implementation detail -- do not use these members.
@@ -44,17 +46,6 @@ struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::uint32 offsets[];
};
void LIBPROTOBUF_EXPORT AddDescriptors();
-void LIBPROTOBUF_EXPORT InitDefaultsApiImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsApi();
-void LIBPROTOBUF_EXPORT InitDefaultsMethodImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsMethod();
-void LIBPROTOBUF_EXPORT InitDefaultsMixinImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsMixin();
-inline void LIBPROTOBUF_EXPORT InitDefaults() {
- InitDefaultsApi();
- InitDefaultsMethod();
- InitDefaultsMixin();
-}
} // namespace protobuf_google_2fprotobuf_2fapi_2eproto
namespace google {
namespace protobuf {
@@ -71,9 +62,9 @@ LIBPROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_;
} // namespace google
namespace google {
namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Api* Arena::Create< ::google::protobuf::Api>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Method* Arena::Create< ::google::protobuf::Method>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Mixin* Arena::Create< ::google::protobuf::Mixin>(Arena*);
+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*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -115,7 +106,7 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
return reinterpret_cast<const Api*>(
&_Api_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
0;
void Swap(Api* other);
@@ -125,32 +116,33 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
// implements Message ----------------------------------------------
- inline Api* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<Api>(NULL);
+ inline Api* New() const final {
+ return CreateMaybeMessage<Api>(NULL);
}
- Api* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<Api>(arena);
+ Api* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Api>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Api& from);
void MergeFrom(const Api& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Api* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
@@ -161,7 +153,7 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -235,6 +227,9 @@ 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();
@@ -257,9 +252,8 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
::google::protobuf::internal::ArenaStringPtr version_;
::google::protobuf::SourceContext* source_context_;
int syntax_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApiImpl();
};
// -------------------------------------------------------------------
@@ -297,7 +291,7 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
return reinterpret_cast<const Method*>(
&_Method_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
1;
void Swap(Method* other);
@@ -307,32 +301,33 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
// implements Message ----------------------------------------------
- inline Method* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<Method>(NULL);
+ inline Method* New() const final {
+ return CreateMaybeMessage<Method>(NULL);
}
- Method* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<Method>(arena);
+ Method* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Method>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Method& from);
void MergeFrom(const Method& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Method* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
@@ -343,7 +338,7 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -432,9 +427,8 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
bool request_streaming_;
bool response_streaming_;
int syntax_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethodImpl();
};
// -------------------------------------------------------------------
@@ -472,7 +466,7 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
return reinterpret_cast<const Mixin*>(
&_Mixin_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
2;
void Swap(Mixin* other);
@@ -482,32 +476,33 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
// implements Message ----------------------------------------------
- inline Mixin* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<Mixin>(NULL);
+ inline Mixin* New() const final {
+ return CreateMaybeMessage<Mixin>(NULL);
}
- Mixin* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<Mixin>(arena);
+ Mixin* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Mixin>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Mixin& from);
void MergeFrom(const Mixin& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Mixin* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
@@ -518,7 +513,7 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -558,9 +553,8 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::internal::ArenaStringPtr root_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixinImpl();
};
// ===================================================================
@@ -740,6 +734,9 @@ 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)
@@ -756,8 +753,8 @@ inline ::google::protobuf::SourceContext* Api::release_source_context() {
inline ::google::protobuf::SourceContext* Api::mutable_source_context() {
if (source_context_ == NULL) {
- source_context_ = ::google::protobuf::Arena::Create< ::google::protobuf::SourceContext >(
- GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<::google::protobuf::SourceContext>(GetArenaNoVirtual());
+ source_context_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Api.source_context)
return source_context_;
@@ -1182,4 +1179,4 @@ inline void Mixin::set_allocated_root(::std::string* root) {
// @@protoc_insertion_point(global_scope)
-#endif // PROTOBUF_google_2fprotobuf_2fapi_2eproto_INCLUDED
+#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto
diff --git a/src/google/protobuf/arena.cc b/src/google/protobuf/arena.cc
index e53d7219..c117c9e5 100755..100644
--- a/src/google/protobuf/arena.cc
+++ b/src/google/protobuf/arena.cc
@@ -48,7 +48,7 @@ namespace protobuf {
namespace internal {
-google::protobuf::internal::SequenceNumber ArenaImpl::lifecycle_id_generator_;
+std::atomic<int64> ArenaImpl::lifecycle_id_generator_;
#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
ArenaImpl::ThreadCache& ArenaImpl::thread_cache() {
static internal::ThreadLocalStorage<ThreadCache>* thread_cache_ =
@@ -65,9 +65,10 @@ GOOGLE_THREAD_LOCAL ArenaImpl::ThreadCache ArenaImpl::thread_cache_ = {-1, NULL}
#endif
void ArenaImpl::Init() {
- lifecycle_id_ = lifecycle_id_generator_.GetNext();
- google::protobuf::internal::NoBarrier_Store(&hint_, 0);
- google::protobuf::internal::NoBarrier_Store(&threads_, 0);
+ lifecycle_id_ =
+ lifecycle_id_generator_.fetch_add(1, std::memory_order_relaxed);
+ hint_.store(nullptr, std::memory_order_relaxed);
+ threads_.store(nullptr, std::memory_order_relaxed);
if (initial_block_) {
// Thread which calls Init() owns the first block. This allows the
@@ -77,13 +78,12 @@ void ArenaImpl::Init() {
SerialArena* serial =
SerialArena::New(initial_block_, &thread_cache(), this);
serial->set_next(NULL);
- google::protobuf::internal::NoBarrier_Store(&threads_,
- reinterpret_cast<google::protobuf::internal::AtomicWord>(serial));
- google::protobuf::internal::NoBarrier_Store(&space_allocated_,
- options_.initial_block_size);
+ threads_.store(serial, std::memory_order_relaxed);
+ space_allocated_.store(options_.initial_block_size,
+ std::memory_order_relaxed);
CacheSerialArena(serial);
} else {
- google::protobuf::internal::NoBarrier_Store(&space_allocated_, 0);
+ space_allocated_.store(0, std::memory_order_relaxed);
}
}
@@ -118,7 +118,7 @@ ArenaImpl::Block* ArenaImpl::NewBlock(Block* last_block, size_t min_bytes) {
void* mem = options_.block_alloc(size);
Block* b = new (mem) Block(size, last_block);
- google::protobuf::internal::NoBarrier_AtomicIncrement(&space_allocated_, size);
+ space_allocated_.fetch_add(size, std::memory_order_relaxed);
return b;
}
@@ -142,6 +142,7 @@ void ArenaImpl::SerialArena::AddCleanupFallback(void* elem,
AddCleanup(elem, cleanup);
}
+GOOGLE_PROTOBUF_ATTRIBUTE_FUNC_ALIGN(32)
void* ArenaImpl::AllocateAligned(size_t n) {
SerialArena* arena;
if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) {
@@ -199,8 +200,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 =
- reinterpret_cast<SerialArena*>(google::protobuf::internal::Acquire_Load(&hint_));
+ SerialArena* serial = hint_.load(std::memory_order_acquire);
if (GOOGLE_PREDICT_TRUE(serial != NULL && serial->owner() == tc)) {
*arena = serial;
return true;
@@ -235,12 +235,11 @@ void* ArenaImpl::SerialArena::AllocateAlignedFallback(size_t n) {
}
uint64 ArenaImpl::SpaceAllocated() const {
- return google::protobuf::internal::NoBarrier_Load(&space_allocated_);
+ return space_allocated_.load(std::memory_order_relaxed);
}
uint64 ArenaImpl::SpaceUsed() const {
- SerialArena* serial =
- reinterpret_cast<SerialArena*>(google::protobuf::internal::Acquire_Load(&threads_));
+ SerialArena* serial = threads_.load(std::memory_order_acquire);
uint64 space_used = 0;
for ( ; serial; serial = serial->next()) {
space_used += serial->SpaceUsed();
@@ -264,8 +263,7 @@ uint64 ArenaImpl::FreeBlocks() {
uint64 space_allocated = 0;
// By omitting an Acquire barrier we ensure that any user code that doesn't
// properly synchronize Reset() or the destructor will throw a TSAN warning.
- SerialArena* serial =
- reinterpret_cast<SerialArena*>(google::protobuf::internal::NoBarrier_Load(&threads_));
+ SerialArena* serial = threads_.load(std::memory_order_relaxed);
while (serial) {
// This is inside a block we are freeing, so we need to read it now.
@@ -311,8 +309,7 @@ uint64 ArenaImpl::SerialArena::Free(ArenaImpl::SerialArena* serial,
void ArenaImpl::CleanupList() {
// By omitting an Acquire barrier we ensure that any user code that doesn't
// properly synchronize Reset() or the destructor will throw a TSAN warning.
- SerialArena* serial =
- reinterpret_cast<SerialArena*>(google::protobuf::internal::NoBarrier_Load(&threads_));
+ SerialArena* serial = threads_.load(std::memory_order_relaxed);
for ( ; serial; serial = serial->next()) {
serial->CleanupList();
@@ -368,8 +365,7 @@ ArenaImpl::SerialArena* ArenaImpl::SerialArena::New(Block* b, void* owner,
GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
ArenaImpl::SerialArena* ArenaImpl::GetSerialArenaFallback(void* me) {
// Look for this SerialArena in our linked list.
- SerialArena* serial =
- reinterpret_cast<SerialArena*>(google::protobuf::internal::Acquire_Load(&threads_));
+ SerialArena* serial = threads_.load(std::memory_order_acquire);
for ( ; serial; serial = serial->next()) {
if (serial->owner() == me) {
break;
@@ -382,12 +378,11 @@ ArenaImpl::SerialArena* ArenaImpl::GetSerialArenaFallback(void* me) {
Block* b = NewBlock(NULL, kSerialArenaSize);
serial = SerialArena::New(b, me, this);
- google::protobuf::internal::AtomicWord head;
+ SerialArena* head = threads_.load(std::memory_order_relaxed);
do {
- head = google::protobuf::internal::NoBarrier_Load(&threads_);
- serial->set_next(reinterpret_cast<SerialArena*>(head));
- } while (google::protobuf::internal::Release_CompareAndSwap(
- &threads_, head, reinterpret_cast<google::protobuf::internal::AtomicWord>(serial)) != head);
+ serial->set_next(head);
+ } while (!threads_.compare_exchange_weak(
+ head, serial, std::memory_order_release, std::memory_order_relaxed));
}
CacheSerialArena(serial);
diff --git a/src/google/protobuf/arena.h b/src/google/protobuf/arena.h
index f3cdedac..9928c8e6 100644
--- a/src/google/protobuf/arena.h
+++ b/src/google/protobuf/arena.h
@@ -37,10 +37,7 @@
#ifdef max
#undef max // Visual Studio defines this macro
#endif
-#if LANG_CXX11
-#include <google/protobuf/stubs/type_traits.h>
-#endif
-#if defined(_MSC_VER) && !_HAS_EXCEPTIONS
+#if defined(_MSC_VER) && !defined(_LIBCPP_STD_VER) && !_HAS_EXCEPTIONS
// Work around bugs in MSVC <typeinfo> header when _HAS_EXCEPTIONS=0.
#include <exception>
#include <typeinfo>
@@ -53,10 +50,13 @@ using type_info = ::type_info;
#include <google/protobuf/arena_impl.h>
#include <google/protobuf/stubs/port.h>
+#include <type_traits>
namespace google {
namespace protobuf {
-struct ArenaOptions;
+
+struct ArenaOptions; // defined below
+
} // namespace protobuf
namespace quality_webanswers {
@@ -66,27 +66,32 @@ void TempPrivateWorkAround(::google::protobuf::ArenaOptions* arena_options);
} // namespace quality_webanswers
namespace protobuf {
+
+class Arena; // defined below
+class Message; // defined in message.h
+class MessageLite;
+
namespace arena_metrics {
void EnableArenaMetrics(::google::protobuf::ArenaOptions* options);
} // namespace arena_metrics
-class Arena; // defined below
-class Message; // message.h
-
namespace internal {
-struct ArenaStringPtr; // arenastring.h
-class LazyField; // lazy_field.h
-template<typename Type>
-class GenericTypeHandler; // repeated_field.h
+struct ArenaStringPtr; // defined in arenastring.h
+class LazyField; // defined in lazy_field.h
+
+template <typename Type>
+class GenericTypeHandler; // defined in repeated_field.h
// Templated cleanup methods.
-template<typename T> void arena_destruct_object(void* object) {
+template <typename T>
+void arena_destruct_object(void* object) {
reinterpret_cast<T*>(object)->~T();
}
-template<typename T> void arena_delete_object(void* object) {
+template <typename T>
+void arena_delete_object(void* object) {
delete reinterpret_cast<T*>(object);
}
inline void arena_free(void* object, size_t size) {
@@ -165,12 +170,12 @@ struct ArenaOptions {
// intentionally want to avoid monitoring an allocation. (i.e. internal
// allocations for managing the arena)
void (*on_arena_allocation)(const std::type_info* allocated_type,
- uint64 alloc_size, void* cookie);
+ uint64 alloc_size, void* cookie);
// Constants define default starting block size and max block size for
// arena allocator behavior -- see descriptions above.
static const size_t kDefaultStartBlockSize = 256;
- static const size_t kDefaultMaxBlockSize = 8192;
+ static const size_t kDefaultMaxBlockSize = 8192;
friend void ::google::protobuf::arena_metrics::EnableArenaMetrics(ArenaOptions*);
friend void quality_webanswers::TempPrivateWorkAround(ArenaOptions*);
@@ -285,70 +290,16 @@ class LIBPROTOBUF_EXPORT Arena {
//
// This function also accepts any type T that satisfies the arena message
// allocation protocol, documented above.
-#if LANG_CXX11
template <typename T, typename... Args>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessage(
- ::google::protobuf::Arena* arena, Args&&... args) {
- static_assert(
- InternalHelper<T>::is_arena_constructable::value,
- "CreateMessage can only construct types that are ArenaConstructable");
- if (arena == NULL) {
- return new T(NULL, std::forward<Args>(args)...);
- } else {
- return arena->CreateMessageInternal<T>(std::forward<Args>(args)...);
- }
- }
-#endif
-
- template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* CreateMessage(::google::protobuf::Arena* arena) {
-#if LANG_CXX11
- static_assert(
- InternalHelper<T>::is_arena_constructable::value,
- "CreateMessage can only construct types that are ArenaConstructable");
-#endif
- if (arena == NULL) {
- return new T;
- } else {
- return arena->CreateMessageInternal<T>();
- }
- }
-
- // One-argument form of CreateMessage. This is useful for constructing objects
- // that implement the arena message construction protocol described above but
- // take additional constructor arguments.
- template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* CreateMessage(::google::protobuf::Arena* arena, const Arg& arg) {
-#if LANG_CXX11
- static_assert(
- InternalHelper<T>::is_arena_constructable::value,
- "CreateMessage can only construct types that are ArenaConstructable");
-#endif
- if (arena == NULL) {
- return new T(NULL, arg);
- } else {
- return arena->CreateMessageInternal<T>(arg);
- }
- }
-
- // Two-argument form of CreateMessage. This is useful for constructing objects
- // that implement the arena message construction protocol described above but
- // take additional constructor arguments.
- template <typename T, typename Arg1, typename Arg2>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* CreateMessage(::google::protobuf::Arena* arena,
- const Arg1& arg1,
- const Arg2& arg2) {
-#if LANG_CXX11
+ Arena* arena, Args&&... args) {
static_assert(
InternalHelper<T>::is_arena_constructable::value,
"CreateMessage can only construct types that are ArenaConstructable");
-#endif
- if (arena == NULL) {
- return new T(NULL, arg1, arg2);
- } else {
- return arena->CreateMessageInternal<T>(arg1, arg2);
- }
+ // We must delegate to CreateMaybeMessage() and NOT CreateMessageInternal()
+ // because protobuf generated classes specialize CreateMaybeMessage() and we
+ // need to use that specialization for code size reasons.
+ return Arena::CreateMaybeMessage<T>(arena, std::forward<Args>(args)...);
}
// API to create any objects on the arena. Note that only the object will
@@ -366,153 +317,11 @@ class LIBPROTOBUF_EXPORT Arena {
// (unless the destructor is trivial). Hence, from T's point of view, it is as
// if the object were allocated on the heap (except that the underlying memory
// is obtained from the arena).
-#if LANG_CXX11
template <typename T, typename... Args>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* Create(::google::protobuf::Arena* arena, Args&&... args) {
- if (arena == NULL) {
- return new T(std::forward<Args>(args)...);
- } else {
- return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
- std::forward<Args>(args)...);
- }
- }
-#endif
-
- template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* Create(::google::protobuf::Arena* arena) {
- if (arena == NULL) {
- return new T();
- } else {
- return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value);
- }
- }
-
- // Version of the above with one constructor argument for the created object.
- template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* Create(::google::protobuf::Arena* arena, const Arg& arg) {
- if (arena == NULL) {
- return new T(arg);
- } else {
- return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
- arg);
- }
- }
-
- // Version of the above with two constructor arguments for the created object.
- template <typename T, typename Arg1, typename Arg2>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* Create(::google::protobuf::Arena* arena, const Arg1& arg1, const Arg2& arg2) {
- if (arena == NULL) {
- return new T(arg1, arg2);
- } else {
- return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
- arg1, arg2);
- }
- }
-
- // Version of the above with three constructor arguments for the created
- // object.
- template <typename T, typename Arg1, typename Arg2, typename Arg3>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* Create(::google::protobuf::Arena* arena,
- const Arg1& arg1,
- const Arg2& arg2,
- const Arg3& arg3) {
- if (arena == NULL) {
- return new T(arg1, arg2, arg3);
- } else {
- return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
- arg1, arg2, arg3);
- }
- }
-
- // Version of the above with four constructor arguments for the created
- // object.
- template <typename T, typename Arg1, typename Arg2, typename Arg3,
- typename Arg4>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* Create(::google::protobuf::Arena* arena,
- const Arg1& arg1, const Arg2& arg2,
- const Arg3& arg3, const Arg4& arg4) {
- if (arena == NULL) {
- return new T(arg1, arg2, arg3, arg4);
- } else {
- return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
- arg1, arg2, arg3, arg4);
- }
- }
-
- // Version of the above with five constructor arguments for the created
- // object.
- template <typename T, typename Arg1, typename Arg2, typename Arg3,
- typename Arg4, typename Arg5>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* Create(::google::protobuf::Arena* arena,
- const Arg1& arg1, const Arg2& arg2,
- const Arg3& arg3, const Arg4& arg4,
- const Arg5& arg5) {
- if (arena == NULL) {
- return new T(arg1, arg2, arg3, arg4, arg5);
- } else {
- return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
- arg1, arg2, arg3, arg4, arg5);
- }
- }
-
- // Version of the above with six constructor arguments for the created
- // object.
- template <typename T, typename Arg1, typename Arg2, typename Arg3,
- typename Arg4, typename Arg5, typename Arg6>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* Create(::google::protobuf::Arena* arena,
- const Arg1& arg1, const Arg2& arg2,
- const Arg3& arg3, const Arg4& arg4,
- const Arg5& arg5, const Arg6& arg6) {
- if (arena == NULL) {
- return new T(arg1, arg2, arg3, arg4, arg5, arg6);
- } else {
- return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
- arg1, arg2, arg3, arg4, arg5, arg6);
- }
- }
-
- // Version of the above with seven constructor arguments for the created
- // object.
- template <typename T, typename Arg1, typename Arg2, typename Arg3,
- typename Arg4, typename Arg5, typename Arg6, typename Arg7>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* Create(::google::protobuf::Arena* arena,
- const Arg1& arg1, const Arg2& arg2,
- const Arg3& arg3, const Arg4& arg4,
- const Arg5& arg5, const Arg6& arg6,
- const Arg7& arg7) {
- if (arena == NULL) {
- return new T(arg1, arg2, arg3, arg4, arg5, arg6, arg7);
- } else {
- return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
- arg1, arg2, arg3, arg4, arg5, arg6, arg7);
- }
- }
-
- // Version of the above with eight constructor arguments for the created
- // object.
- template <typename T, typename Arg1, typename Arg2, typename Arg3,
- typename Arg4, typename Arg5, typename Arg6, typename Arg7,
- typename Arg8>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* Create(::google::protobuf::Arena* arena,
- const Arg1& arg1, const Arg2& arg2,
- const Arg3& arg3, const Arg4& arg4,
- const Arg5& arg5, const Arg6& arg6,
- const Arg7& arg7, const Arg8& arg8) {
- if (arena == NULL) {
- return new T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
- } else {
- return arena->CreateInternal<T>(
- google::protobuf::internal::has_trivial_destructor<T>::value,
- arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
- }
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* Create(Arena* arena,
+ Args&&... args) {
+ return CreateNoMessage<T>(arena, is_arena_constructable<T>(),
+ std::forward<Args>(args)...);
}
// Create an array of object type T on the arena *without* invoking the
@@ -521,10 +330,14 @@ class LIBPROTOBUF_EXPORT Arena {
// To ensure safe uses, this function checks at compile time
// (when compiled as C++11) that T is trivially default-constructible and
// trivially destructible.
- template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* CreateArray(::google::protobuf::Arena* arena, size_t num_elements) {
- GOOGLE_CHECK_LE(num_elements,
- std::numeric_limits<size_t>::max() / sizeof(T))
+ template <typename T>
+ GOOGLE_PROTOBUF_ATTRIBUTE_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,
+ "CreateArray requires a trivially destructible type");
+ GOOGLE_CHECK_LE(num_elements, std::numeric_limits<size_t>::max() / sizeof(T))
<< "Requested size is too large to fit into size_t.";
if (arena == NULL) {
return static_cast<T*>(::operator new[](num_elements * sizeof(T)));
@@ -566,9 +379,9 @@ 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) {
- OwnInternal(object, google::protobuf::internal::is_convertible<T*, ::google::protobuf::Message*>());
+ template <typename T>
+ GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void Own(T* object) {
+ OwnInternal(object, std::is_convertible<T*, Message*>());
}
// Adds |object| to a list of objects whose destructors will be manually
@@ -576,8 +389,8 @@ class LIBPROTOBUF_EXPORT Arena {
// that it does not free the underlying memory with |delete|; hence, it is
// normally only used for objects that are placement-newed into
// arena-allocated memory.
- template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
- void OwnDestructor(T* object) {
+ template <typename T>
+ GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void OwnDestructor(T* object) {
if (object != NULL) {
impl_.AddCleanup(object, &internal::arena_destruct_object<T>);
}
@@ -596,8 +409,9 @@ class LIBPROTOBUF_EXPORT Arena {
// message, or NULL otherwise. This differs from value->GetArena() in that the
// latter is a virtual call, while this method is a templated call that
// resolves at compile-time.
- template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static ::google::protobuf::Arena* GetArena(const T* value) {
+ template <typename T>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArena(
+ const T* value) {
return GetArenaInternal(value, is_arena_constructable<T>());
}
@@ -608,80 +422,89 @@ class LIBPROTOBUF_EXPORT Arena {
template <typename U>
static double DestructorSkippable(...);
- typedef google::protobuf::internal::integral_constant<
+ typedef std::integral_constant<
bool, sizeof(DestructorSkippable<T>(static_cast<const T*>(0))) ==
sizeof(char) ||
- google::protobuf::internal::has_trivial_destructor<T>::value>
+ std::is_trivially_destructible<T>::value>
is_destructor_skippable;
- template<typename U>
+ template <typename U>
static char ArenaConstructable(
const typename U::InternalArenaConstructable_*);
- template<typename U>
+ template <typename U>
static double ArenaConstructable(...);
- typedef google::protobuf::internal::integral_constant<bool, sizeof(ArenaConstructable<T>(
- static_cast<const T*>(0))) ==
- sizeof(char)>
+ typedef std::integral_constant<bool, sizeof(ArenaConstructable<T>(
+ static_cast<const T*>(0))) ==
+ sizeof(char)>
is_arena_constructable;
-#if LANG_CXX11
template <typename... Args>
static T* Construct(void* ptr, Args&&... args) {
return new (ptr) T(std::forward<Args>(args)...);
}
-#else
- template <typename Arg1>
- static T* Construct(void* ptr, const Arg1& arg1) {
- return new (ptr) T(arg1);
- }
- template <typename Arg1, typename Arg2>
- static T* Construct(void* ptr, const Arg1& arg1, const Arg2& arg2) {
- return new (ptr) T(arg1, arg2);
- }
- template <typename Arg1, typename Arg2, typename Arg3>
- static T* Construct(void* ptr, const Arg1& arg1,
- const Arg2& arg2, const Arg3& arg3) {
- return new (ptr) T(arg1, arg2, arg3);
- }
-#endif // LANG_CXX11
static Arena* GetArena(const T* p) { return p->GetArenaNoVirtual(); }
friend class Arena;
};
- // Helper typetrait that indicates support for arenas in a type T at compile
+ // Helper typetraits that indicates support for arenas in a type T at compile
// time. This is public only to allow construction of higher-level templated
- // utilities. is_arena_constructable<T>::value is true if the message type T
- // has arena support enabled, and false otherwise.
+ // utilities.
+ //
+ // is_arena_constructable<T>::value is true if the message type T has arena
+ // support enabled, and false otherwise.
+ //
+ // is_destructor_skippable<T>::value is true if the message type T has told
+ // the arena that it is safe to skip the destructor, and false otherwise.
//
// This is inside Arena because only Arena has the friend relationships
// necessary to see the underlying generated code traits.
template <typename T>
struct is_arena_constructable : InternalHelper<T>::is_arena_constructable {};
+ template <typename T>
+ struct is_destructor_skippable : InternalHelper<T>::is_destructor_skippable {
+ };
private:
- template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* CreateMessageInternal(::google::protobuf::Arena* arena) {
-#if LANG_CXX11
+ template <typename T, typename... Args>
+ GOOGLE_PROTOBUF_ATTRIBUTE_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");
-#endif
if (arena == NULL) {
- return new T;
+ return new T(nullptr, std::forward<Args>(args)...);
} else {
- return arena->CreateMessageInternal<T>();
+ return arena->DoCreateMessage<T>(std::forward<Args>(args)...);
}
}
- template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* CreateInternal(::google::protobuf::Arena* arena) {
+ // This specialization for no arguments is necessary, because its behavior is
+ // 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) {
+ static_assert(
+ InternalHelper<T>::is_arena_constructable::value,
+ "CreateMessage can only construct types that are ArenaConstructable");
if (arena == NULL) {
return new T();
} else {
- return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value);
+ return arena->DoCreateMessage<T>();
+ }
+ }
+
+ template <typename T, typename... Args>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateInternal(
+ Arena* arena, Args&&... args) {
+ if (arena == NULL) {
+ return new T(std::forward<Args>(args)...);
+ } else {
+ return arena->DoCreate<T>(std::is_trivially_destructible<T>::value,
+ std::forward<Args>(args)...);
}
}
@@ -696,8 +519,9 @@ class LIBPROTOBUF_EXPORT Arena {
// Allocate and also optionally call on_arena_allocation callback with the
// allocated type info when the hooks are in place in ArenaOptions and
// the cookie is not null.
- template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- void* AllocateInternal(bool skip_explicit_ownership) {
+ template <typename T>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void* AllocateInternal(
+ bool skip_explicit_ownership) {
const size_t n = internal::AlignUpTo8(sizeof(T));
AllocHook(RTTI_TYPE_ID(T), n);
// Monitor allocation if needed.
@@ -714,27 +538,49 @@ class LIBPROTOBUF_EXPORT Arena {
// as it can cause confusing API usages, and end up having double free in
// user code. These are used only internally from LazyField and Repeated
// fields, since they are designed to work in all mode combinations.
- template <typename Msg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static Msg* CreateMaybeMessage(Arena* arena, google::protobuf::internal::true_type) {
- return CreateMessageInternal<Msg>(arena);
+ template <typename Msg, typename... Args>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Msg* DoCreateMaybeMessage(
+ Arena* arena, std::true_type, Args&&... args) {
+ return CreateMessageInternal<Msg>(arena, std::forward<Args>(args)...);
}
- template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* CreateMaybeMessage(Arena* arena, google::protobuf::internal::false_type) {
- return CreateInternal<T>(arena);
+ template <typename T, typename... Args>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* DoCreateMaybeMessage(
+ Arena* arena, std::false_type, Args&&... args) {
+ return CreateInternal<T>(arena, std::forward<Args>(args)...);
}
- template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* CreateMaybeMessage(Arena* arena) {
- return CreateMaybeMessage<T>(arena, is_arena_constructable<T>());
+ template <typename T, typename... Args>
+ GOOGLE_PROTOBUF_ATTRIBUTE_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) {
+ // 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.
+ return CreateInternal<T>(arena, std::forward<Args>(args)...);
+ }
+
+ template <typename T, typename... Args>
+ GOOGLE_PROTOBUF_ATTRIBUTE_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.
+ return CreateMaybeMessage<T>(arena, std::forward<Args>(args)...);
}
// 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) {
- GOOGLE_CHECK_LE(num_elements,
- std::numeric_limits<size_t>::max() / sizeof(T))
+ template <typename T>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateInternalRawArray(
+ size_t num_elements) {
+ GOOGLE_CHECK_LE(num_elements, std::numeric_limits<size_t>::max() / sizeof(T))
<< "Requested size is too large to fit into size_t.";
const size_t n = internal::AlignUpTo8(sizeof(T) * num_elements);
// Monitor allocation if needed.
@@ -742,143 +588,18 @@ class LIBPROTOBUF_EXPORT Arena {
return static_cast<T*>(impl_.AllocateAligned(n));
}
-#if LANG_CXX11
template <typename T, typename... Args>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- T* CreateInternal(bool skip_explicit_ownership, Args&&... args) {
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreate(
+ bool skip_explicit_ownership, Args&&... args) {
return new (AllocateInternal<T>(skip_explicit_ownership))
T(std::forward<Args>(args)...);
}
-#else
- template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- T* CreateInternal(bool skip_explicit_ownership) {
- return new (AllocateInternal<T>(skip_explicit_ownership)) T();
- }
-
- template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- T* CreateInternal(bool skip_explicit_ownership, const Arg& arg) {
- return new (AllocateInternal<T>(skip_explicit_ownership)) T(arg);
- }
-
- template <typename T, typename Arg1, typename Arg2>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- T* CreateInternal(bool skip_explicit_ownership,
- const Arg1& arg1,
- const Arg2& arg2) {
- return new (AllocateInternal<T>(skip_explicit_ownership)) T(arg1, arg2);
- }
-
- template <typename T, typename Arg1, typename Arg2, typename Arg3>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- T* CreateInternal(bool skip_explicit_ownership,
- const Arg1& arg1,
- const Arg2& arg2,
- const Arg3& arg3) {
- return new (AllocateInternal<T>(skip_explicit_ownership))
- T(arg1, arg2, arg3);
- }
-
- template <typename T, typename Arg1, typename Arg2, typename Arg3,
- typename Arg4>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- T* CreateInternal(bool skip_explicit_ownership,
- const Arg1& arg1,
- const Arg2& arg2,
- const Arg3& arg3,
- const Arg4& arg4) {
- return new (AllocateInternal<T>(skip_explicit_ownership))
- T(arg1, arg2, arg3, arg4);
- }
-
- template <typename T, typename Arg1, typename Arg2, typename Arg3,
- typename Arg4, typename Arg5>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- T* CreateInternal(bool skip_explicit_ownership,
- const Arg1& arg1,
- const Arg2& arg2,
- const Arg3& arg3,
- const Arg4& arg4,
- const Arg5& arg5) {
- return new (AllocateInternal<T>(skip_explicit_ownership))
- T(arg1, arg2, arg3, arg4, arg5);
- }
-
- template <typename T, typename Arg1, typename Arg2, typename Arg3,
- typename Arg4, typename Arg5, typename Arg6>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- T* CreateInternal(bool skip_explicit_ownership,
- const Arg1& arg1,
- const Arg2& arg2,
- const Arg3& arg3,
- const Arg4& arg4,
- const Arg5& arg5,
- const Arg6& arg6) {
- return new (AllocateInternal<T>(skip_explicit_ownership))
- T(arg1, arg2, arg3, arg4, arg5, arg6);
- }
-
- template <typename T, typename Arg1, typename Arg2, typename Arg3,
- typename Arg4, typename Arg5, typename Arg6, typename Arg7>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- T* CreateInternal(bool skip_explicit_ownership,
- const Arg1& arg1,
- const Arg2& arg2,
- const Arg3& arg3,
- const Arg4& arg4,
- const Arg5& arg5,
- const Arg6& arg6,
- const Arg7& arg7) {
- return new (AllocateInternal<T>(skip_explicit_ownership))
- T(arg1, arg2, arg3, arg4, arg5, arg6, arg7);
- }
-
- template <typename T, typename Arg1, typename Arg2, typename Arg3,
- typename Arg4, typename Arg5, typename Arg6, typename Arg7,
- typename Arg8>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- T* CreateInternal(bool skip_explicit_ownership,
- const Arg1& arg1,
- const Arg2& arg2,
- const Arg3& arg3,
- const Arg4& arg4,
- const Arg5& arg5,
- const Arg6& arg6,
- const Arg7& arg7,
- const Arg8& arg8) {
- return new (AllocateInternal<T>(skip_explicit_ownership))
- T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
- }
-#endif
-#if LANG_CXX11
template <typename T, typename... Args>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateMessageInternal(
- Args&&... args) {
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreateMessage(Args&&... args) {
return InternalHelper<T>::Construct(
AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value),
this, std::forward<Args>(args)...);
}
-#endif
- template <typename T>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateMessageInternal() {
- return InternalHelper<T>::Construct(
- AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value),
- this);
- }
-
- template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- T* CreateMessageInternal(const Arg& arg) {
- return InternalHelper<T>::Construct(
- AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value),
- this, arg);
- }
-
- template <typename T, typename Arg1, typename Arg2>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- T* CreateMessageInternal(const Arg1& arg1, const Arg2& arg2) {
- return InternalHelper<T>::Construct(
- AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value),
- this, arg1, arg2);
- }
// CreateInArenaStorage is used to implement map field. Without it,
// google::protobuf::Map need to call generated message's protected arena constructor,
@@ -893,22 +614,22 @@ class LIBPROTOBUF_EXPORT Arena {
}
template <typename T>
- static void CreateInArenaStorageInternal(
- T* ptr, Arena* arena, google::protobuf::internal::true_type) {
+ static void CreateInArenaStorageInternal(T* ptr, Arena* arena,
+ std::true_type) {
InternalHelper<T>::Construct(ptr, arena);
}
template <typename T>
- static void CreateInArenaStorageInternal(
- T* ptr, Arena* /* arena */, google::protobuf::internal::false_type) {
+ static void CreateInArenaStorageInternal(T* ptr, Arena* /* arena */,
+ std::false_type) {
new (ptr) T();
}
template <typename T>
- static void RegisterDestructorInternal(
- T* /* ptr */, Arena* /* arena */, google::protobuf::internal::true_type) {}
+ static void RegisterDestructorInternal(T* /* ptr */, Arena* /* arena */,
+ std::true_type) {}
template <typename T>
- static void RegisterDestructorInternal(
- T* ptr, Arena* arena, google::protobuf::internal::false_type) {
+ static void RegisterDestructorInternal(T* ptr, Arena* arena,
+ std::false_type) {
arena->OwnDestructor(ptr);
}
@@ -917,15 +638,16 @@ class LIBPROTOBUF_EXPORT Arena {
// is a subtype of ::google::protobuf::Message and 'false_type' otherwise. Collapsing
// all template instantiations to one for generic Message reduces code size,
// using the virtual destructor instead.
- template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- void OwnInternal(T* object, google::protobuf::internal::true_type) {
+ template <typename T>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object,
+ std::true_type) {
if (object != NULL) {
- impl_.AddCleanup(object,
- &internal::arena_delete_object< ::google::protobuf::Message>);
+ impl_.AddCleanup(object, &internal::arena_delete_object<Message>);
}
}
- template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- void OwnInternal(T* object, google::protobuf::internal::false_type) {
+ template <typename T>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object,
+ std::false_type) {
if (object != NULL) {
impl_.AddCleanup(object, &internal::arena_delete_object<T>);
}
@@ -934,16 +656,15 @@ class LIBPROTOBUF_EXPORT Arena {
// Implementation for GetArena(). Only message objects with
// InternalArenaConstructable_ tags can be associated with an arena, and such
// objects must implement a GetArenaNoVirtual() method.
- template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static ::google::protobuf::Arena* GetArenaInternal(
- const T* value, google::protobuf::internal::true_type) {
+ template <typename T>
+ GOOGLE_PROTOBUF_ATTRIBUTE_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 ::google::protobuf::Arena* GetArenaInternal(
- const T* /* value */, google::protobuf::internal::false_type) {
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal(
+ const T* /* value */, std::false_type) {
return NULL;
}
@@ -965,9 +686,10 @@ class LIBPROTOBUF_EXPORT Arena {
void* hooks_cookie_;
template <typename Type>
- friend class ::google::protobuf::internal::GenericTypeHandler;
+ friend class internal::GenericTypeHandler;
friend struct internal::ArenaStringPtr; // For AllocateAligned.
- friend class internal::LazyField; // For CreateMaybeMessage.
+ friend class internal::LazyField; // For CreateMaybeMessage.
+ friend class MessageLite;
template <typename Key, typename T>
friend class Map;
};
diff --git a/src/google/protobuf/arena_impl.h b/src/google/protobuf/arena_impl.h
index 439b0969..f648f166 100644
--- a/src/google/protobuf/arena_impl.h
+++ b/src/google/protobuf/arena_impl.h
@@ -33,13 +33,11 @@
#ifndef GOOGLE_PROTOBUF_ARENA_IMPL_H__
#define GOOGLE_PROTOBUF_ARENA_IMPL_H__
+#include <atomic>
#include <limits>
-#include <google/protobuf/stubs/atomic_sequence_num.h>
-#include <google/protobuf/stubs/atomicops.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/mutex.h>
#include <google/protobuf/stubs/port.h>
@@ -248,7 +246,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
int64 last_lifecycle_id_seen;
SerialArena* last_serial_arena;
};
- static google::protobuf::internal::SequenceNumber lifecycle_id_generator_;
+ static std::atomic<int64> lifecycle_id_generator_;
#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
// Android ndk does not support GOOGLE_THREAD_LOCAL keyword so we use a custom thread
// local storage class we implemented.
@@ -277,12 +275,15 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
// TODO(haberman): evaluate whether we would gain efficiency by getting rid
// of hint_. It's the only write we do to ArenaImpl in the allocation path,
// which will dirty the cache line.
- google::protobuf::internal::Release_Store(&hint_, reinterpret_cast<google::protobuf::internal::AtomicWord>(serial));
+
+ hint_.store(serial, std::memory_order_release);
}
- google::protobuf::internal::AtomicWord threads_; // Pointer to a linked list of SerialArena.
- google::protobuf::internal::AtomicWord hint_; // Fast thread-local block access
- google::protobuf::internal::AtomicWord space_allocated_; // Sum of sizes of all allocated blocks.
+
+ std::atomic<SerialArena*>
+ threads_; // Pointer to a linked list of SerialArena.
+ std::atomic<SerialArena*> hint_; // Fast thread-local block access
+ std::atomic<size_t> space_allocated_; // Total size of all allocated blocks.
Block *initial_block_; // If non-NULL, points to the block that came from
// user data.
@@ -297,18 +298,20 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
Options options_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArenaImpl);
+ // All protos have pointers back to the arena hence Arena must have
+ // pointer stability.
+ ArenaImpl(ArenaImpl&&) = delete;
+ ArenaImpl& operator=(ArenaImpl&&) = delete;
public:
// kBlockHeaderSize is sizeof(Block), aligned up to the nearest multiple of 8
// to protect the invariant that pos is always at a multiple of 8.
static const size_t kBlockHeaderSize = (sizeof(Block) + 7) & -8;
static const size_t kSerialArenaSize = (sizeof(SerialArena) + 7) & -8;
-#if LANG_CXX11
static_assert(kBlockHeaderSize % 8 == 0,
"kBlockHeaderSize must be a multiple of 8.");
static_assert(kSerialArenaSize % 8 == 0,
"kSerialArenaSize must be a multiple of 8.");
-#endif
};
} // namespace internal
diff --git a/src/google/protobuf/arena_test_util.h b/src/google/protobuf/arena_test_util.h
index 8c9f7698..df56ece8 100644
--- a/src/google/protobuf/arena_test_util.h
+++ b/src/google/protobuf/arena_test_util.h
@@ -50,7 +50,7 @@ void TestParseCorruptedString(const T& message) {
s[i] ^= c;
google::protobuf::Arena arena;
T* message =
- google::protobuf::Arena::CreateMessage<T>(use_arena ? &arena : NULL);
+ google::protobuf::Arena::CreateMessage<T>(use_arena ? &arena : nullptr);
if (message->ParseFromString(s)) {
++success_count;
}
diff --git a/src/google/protobuf/arena_unittest.cc b/src/google/protobuf/arena_unittest.cc
index 71e28b0c..eaaffce2 100644
--- a/src/google/protobuf/arena_unittest.cc
+++ b/src/google/protobuf/arena_unittest.cc
@@ -33,10 +33,8 @@
#include <algorithm>
#include <cstring>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
+#include <type_traits>
#include <typeinfo>
#include <vector>
@@ -153,9 +151,19 @@ class MustBeConstructedWithOneThroughEight {
TEST(ArenaTest, ArenaConstructable) {
EXPECT_TRUE(Arena::is_arena_constructable<TestAllTypes>::type::value);
EXPECT_TRUE(Arena::is_arena_constructable<const TestAllTypes>::type::value);
+ EXPECT_FALSE(Arena::is_arena_constructable<
+ protobuf_unittest_no_arena::TestNoArenaMessage>::type::value);
EXPECT_FALSE(Arena::is_arena_constructable<Arena>::type::value);
}
+TEST(ArenaTest, DestructorSkippable) {
+ EXPECT_TRUE(Arena::is_destructor_skippable<TestAllTypes>::type::value);
+ EXPECT_TRUE(Arena::is_destructor_skippable<const TestAllTypes>::type::value);
+ EXPECT_FALSE(Arena::is_destructor_skippable<
+ protobuf_unittest_no_arena::TestNoArenaMessage>::type::value);
+ EXPECT_FALSE(Arena::is_destructor_skippable<Arena>::type::value);
+}
+
TEST(ArenaTest, BasicCreate) {
Arena arena;
EXPECT_TRUE(Arena::Create<int32>(&arena) != NULL);
@@ -197,7 +205,6 @@ TEST(ArenaTest, CreateAndNonConstCopy) {
EXPECT_EQ("foo", *s_copy);
}
-#if LANG_CXX11
TEST(ArenaTest, CreateAndMove) {
Arena arena;
string s("foo");
@@ -206,7 +213,6 @@ TEST(ArenaTest, CreateAndMove) {
EXPECT_TRUE(s.empty()); // NOLINT
EXPECT_EQ("foo", *s_move);
}
-#endif
TEST(ArenaTest, CreateWithFourConstructorArguments) {
Arena arena;
@@ -242,7 +248,6 @@ TEST(ArenaTest, CreateWithEightConstructorArguments) {
ASSERT_EQ("8", new_object->eight_);
}
-#if LANG_CXX11
class PleaseMoveMe {
public:
explicit PleaseMoveMe(const string& value) : value_(value) {}
@@ -263,7 +268,6 @@ TEST(ArenaTest, CreateWithMoveArguments) {
EXPECT_TRUE(new_object);
ASSERT_EQ("1", new_object->value());
}
-#endif
TEST(ArenaTest, InitialBlockTooSmall) {
// Construct a small (64 byte) initial block of memory to be used by the
@@ -442,7 +446,7 @@ TEST(ArenaTest, ReflectionSwapFields) {
TestUtil::SetAllFields(arena1_message);
reflection->SwapFields(arena1_message, &message, fields);
EXPECT_EQ(&arena1, arena1_message->GetArena());
- EXPECT_EQ(NULL, message.GetArena());
+ EXPECT_EQ(nullptr, message.GetArena());
arena1_message->SerializeToString(&output);
EXPECT_EQ(0, output.size());
TestUtil::ExpectAllFieldsSet(message);
@@ -468,7 +472,7 @@ TEST(ArenaTest, ReleaseMessage) {
Arena arena;
TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
arena_message->mutable_optional_nested_message()->set_bb(118);
- google::protobuf::scoped_ptr<TestAllTypes::NestedMessage> nested(
+ std::unique_ptr<TestAllTypes::NestedMessage> nested(
arena_message->release_optional_nested_message());
EXPECT_EQ(118, nested->bb());
@@ -489,7 +493,7 @@ TEST(ArenaTest, ReleaseString) {
Arena arena;
TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
arena_message->set_optional_string("hello");
- google::protobuf::scoped_ptr<string> released_str(
+ std::unique_ptr<string> released_str(
arena_message->release_optional_string());
EXPECT_EQ("hello", *released_str);
@@ -600,25 +604,6 @@ TEST(ArenaTest, ReleaseFromArenaMessageUsingReflectionMakesCopy) {
}
#endif // !GOOGLE_PROTOBUF_NO_RTTI
-TEST(ArenaTest, UnsafeArenaReleaseDoesNotMakeCopy) {
- Arena arena;
- TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
- TestAllTypes::NestedMessage* nested_msg = NULL;
- TestAllTypes::NestedMessage* orig_nested_msg = NULL;
- string* nested_string = NULL;
- string* orig_nested_string = NULL;
- arena_message->mutable_optional_nested_message()->set_bb(42);
- *arena_message->mutable_optional_string() = "Hello";
- orig_nested_msg = arena_message->mutable_optional_nested_message();
- orig_nested_string = arena_message->mutable_optional_string();
- nested_msg = arena_message->unsafe_arena_release_optional_nested_message();
- nested_string = arena_message->unsafe_arena_release_optional_string();
-
- EXPECT_EQ(orig_nested_msg, nested_msg);
- EXPECT_EQ(orig_nested_string, nested_string);
- // Released pointers still on arena; no 'delete' calls needed here.
-}
-
TEST(ArenaTest, SetAllocatedAcrossArenas) {
Arena arena1;
TestAllTypes* arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
@@ -898,17 +883,18 @@ TEST(ArenaTest, ReleaseLastRepeatedField) {
TEST(ArenaTest, UnsafeArenaReleaseAdd) {
// Use unsafe_arena_release() and unsafe_arena_set_allocated() to transfer an
// arena-allocated string from one message to another.
+ const char kContent[] = "Test content";
+
Arena arena;
TestAllTypes* message1 = Arena::CreateMessage<TestAllTypes>(&arena);
TestAllTypes* message2 = Arena::CreateMessage<TestAllTypes>(&arena);
string* arena_string = Arena::Create<string>(&arena);
- *arena_string = "Test content";
+ *arena_string = kContent;
message1->unsafe_arena_set_allocated_optional_string(arena_string);
- EXPECT_EQ(arena_string, message1->mutable_optional_string());
message2->unsafe_arena_set_allocated_optional_string(
message1->unsafe_arena_release_optional_string());
- EXPECT_EQ(arena_string, message2->mutable_optional_string());
+ EXPECT_EQ(kContent, message2->optional_string());
}
TEST(ArenaTest, UnsafeArenaAddAllocated) {
@@ -1432,7 +1418,7 @@ TEST(ArenaTest, ArenaHooksSanity) {
EXPECT_EQ(1, ArenaHooksTestUtil::num_init);
EXPECT_EQ(0, ArenaHooksTestUtil::num_allocations);
::google::protobuf::Arena::Create<uint64>(&arena);
- if (google::protobuf::internal::has_trivial_destructor<uint64>::value) {
+ if (std::is_trivially_destructible<uint64>::value) {
EXPECT_EQ(1, ArenaHooksTestUtil::num_allocations);
} else {
EXPECT_EQ(2, ArenaHooksTestUtil::num_allocations);
diff --git a/src/google/protobuf/arenastring.h b/src/google/protobuf/arenastring.h
index 2b108616..168fc972 100755..100644
--- a/src/google/protobuf/arenastring.h
+++ b/src/google/protobuf/arenastring.h
@@ -99,6 +99,13 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
if (ptr_ == default_value) {
return NULL;
}
+ return ReleaseNonDefault(default_value, arena);
+ }
+
+ // Similar to Release, but ptr_ cannot be the default_value.
+ inline ::std::string* ReleaseNonDefault(
+ const ::std::string* default_value, ::google::protobuf::Arena* arena) {
+ GOOGLE_DCHECK(!IsDefault(default_value));
::std::string* released = NULL;
if (arena != NULL) {
// ptr_ is owned by the arena.
@@ -164,6 +171,29 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
GOOGLE_PROTOBUF_ATTRIBUTE_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) {
+#ifndef NDEBUG
+ // For debug builds, we swap the contents of the string, rather than the
+ // string instances themselves. This invalidates previously taken const
+ // references that are (per our documentation) invalidated by calling Swap()
+ // on the message.
+ //
+ // If both strings are the default_value, swapping is uninteresting.
+ // Otherwise, we use ArenaStringPtr::Mutable() to access the string, to
+ // ensure that we do not try to mutate default_value itself.
+ if (IsDefault(default_value) && other->IsDefault(default_value)) {
+ return;
+ }
+
+ ::std::string* this_ptr = Mutable(default_value, arena);
+ ::std::string* other_ptr = other->Mutable(default_value, arena);
+
+ this_ptr->swap(*other_ptr);
+#else
+ std::swap(ptr_, other->ptr_);
+#endif
+ }
// Frees storage (if not on an arena).
inline void Destroy(const ::std::string* default_value,
@@ -186,6 +216,15 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
}
}
+ // Clears content, assuming that the current value is not the empty string
+ // default.
+ inline void ClearNonDefaultToEmpty() {
+ ptr_->clear();
+ }
+ inline void ClearNonDefaultToEmptyNoArena() {
+ ptr_->clear();
+ }
+
// Clears content, but keeps allocated string if arena != NULL, to avoid the
// overhead of heap operations. After this returns, the content (as seen by
// the user) will always be equal to |default_value|.
@@ -253,12 +292,19 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
if (ptr_ == default_value) {
return NULL;
} else {
- ::std::string* released = ptr_;
- ptr_ = const_cast< ::std::string* >(default_value);
- return released;
+ return ReleaseNonDefaultNoArena(default_value);
}
}
+ inline ::std::string* ReleaseNonDefaultNoArena(
+ const ::std::string* default_value) {
+ GOOGLE_DCHECK(!IsDefault(default_value));
+ ::std::string* released = ptr_;
+ ptr_ = const_cast< ::std::string* >(default_value);
+ return released;
+ }
+
+
inline void SetAllocatedNoArena(const ::std::string* default_value,
::std::string* value) {
if (ptr_ != default_value) {
diff --git a/src/google/protobuf/arenastring_unittest.cc b/src/google/protobuf/arenastring_unittest.cc
index d5d995a6..adc44fe2 100644
--- a/src/google/protobuf/arenastring_unittest.cc
+++ b/src/google/protobuf/arenastring_unittest.cc
@@ -35,9 +35,6 @@
#include <algorithm>
#include <cstdlib>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
#include <vector>
diff --git a/src/google/protobuf/compiler/annotation_test_util.cc b/src/google/protobuf/compiler/annotation_test_util.cc
index cc8534cc..a0530b9a 100644
--- a/src/google/protobuf/compiler/annotation_test_util.cc
+++ b/src/google/protobuf/compiler/annotation_test_util.cc
@@ -31,9 +31,6 @@
#include <google/protobuf/compiler/annotation_test_util.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/command_line_interface.h>
#include <google/protobuf/io/printer.h>
diff --git a/src/google/protobuf/compiler/code_generator.cc b/src/google/protobuf/compiler/code_generator.cc
index 11d0f334..aaabd914 100644
--- a/src/google/protobuf/compiler/code_generator.cc
+++ b/src/google/protobuf/compiler/code_generator.cc
@@ -34,9 +34,9 @@
#include <google/protobuf/compiler/code_generator.h>
-#include <google/protobuf/compiler/plugin.pb.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/compiler/plugin.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/strutil.h>
diff --git a/src/google/protobuf/compiler/command_line_interface.cc b/src/google/protobuf/compiler/command_line_interface.cc
index 7c45fe75..8380367f 100644
--- a/src/google/protobuf/compiler/command_line_interface.cc
+++ b/src/google/protobuf/compiler/command_line_interface.cc
@@ -58,9 +58,6 @@
#include <limits.h> //For PATH_MAX
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#ifdef __APPLE__
#include <mach-o/dyld.h>
@@ -171,8 +168,7 @@ 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);
+ 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];
@@ -440,7 +436,7 @@ class CommandLineInterface::MemoryOutputStream
bool append_mode_;
// StringOutputStream writing to data_.
- google::protobuf::scoped_ptr<io::StringOutputStream> inner_;
+ std::unique_ptr<io::StringOutputStream> inner_;
};
// -------------------------------------------------------------------
@@ -835,10 +831,10 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) {
std::vector<const FileDescriptor*> parsed_files;
// null unless descriptor_set_in_names_.empty()
- google::protobuf::scoped_ptr<DiskSourceTree> disk_source_tree;
- google::protobuf::scoped_ptr<ErrorPrinter> error_collector;
- google::protobuf::scoped_ptr<DescriptorPool> descriptor_pool;
- google::protobuf::scoped_ptr<DescriptorDatabase> descriptor_database;
+ std::unique_ptr<DiskSourceTree> disk_source_tree;
+ std::unique_ptr<ErrorPrinter> error_collector;
+ std::unique_ptr<DescriptorPool> descriptor_pool;
+ std::unique_ptr<DescriptorDatabase> descriptor_database;
if (descriptor_set_in_names_.empty()) {
disk_source_tree.reset(new DiskSourceTree());
if (!InitializeDiskSourceTree(disk_source_tree.get())) {
@@ -1395,8 +1391,7 @@ CommandLineInterface::InterpretArgument(const string& name,
// with colons. Let's accept that syntax too just to make things more
// intuitive.
std::vector<string> parts = Split(
- value,
- CommandLineInterface::kPathSeparator,
+ value, CommandLineInterface::kPathSeparator,
true);
for (int i = 0; i < parts.size(); i++) {
@@ -1421,7 +1416,7 @@ CommandLineInterface::InterpretArgument(const string& name,
// Make sure disk path exists, warn otherwise.
if (access(disk_path.c_str(), F_OK) < 0) {
- // Try the original path; it may have just happed to have a '=' in it.
+ // Try the original path; it may have just happened to have a '=' in it.
if (access(parts[i].c_str(), F_OK) < 0) {
std::cerr << disk_path << ": warning: directory does not exist."
<< std::endl;
@@ -1447,8 +1442,7 @@ CommandLineInterface::InterpretArgument(const string& name,
}
direct_dependencies_explicitly_set_ = true;
- std::vector<string> direct = Split(
- value, ":", true);
+ std::vector<string> direct = Split(value, ":", true);
GOOGLE_DCHECK(direct_dependencies_.empty());
direct_dependencies_.insert(direct.begin(), direct.end());
@@ -1481,9 +1475,8 @@ CommandLineInterface::InterpretArgument(const string& name,
}
descriptor_set_in_names_ = Split(
- value,
- CommandLineInterface::kPathSeparator,
- true);
+ value, CommandLineInterface::kPathSeparator,
+ true);
} else if (name == "-o" || name == "--descriptor_set_out") {
if (!descriptor_set_out_name_.empty()) {
@@ -1629,7 +1622,6 @@ CommandLineInterface::InterpretArgument(const string& name,
}
mode_ = MODE_PRINT;
print_mode_ = PRINT_FREE_FIELDS;
- } else if (name == "--profile_path") {
} else {
// Some other flag. Look it up in the generators list.
const GeneratorInfo* generator_info =
@@ -1908,10 +1900,12 @@ bool CommandLineInterface::GeneratePluginOutput(
string* error) {
CodeGeneratorRequest request;
CodeGeneratorResponse response;
+ string processed_parameter = parameter;
+
// Build the request.
- if (!parameter.empty()) {
- request.set_parameter(parameter);
+ if (!processed_parameter.empty()) {
+ request.set_parameter(processed_parameter);
}
@@ -1948,17 +1942,18 @@ bool CommandLineInterface::GeneratePluginOutput(
// Write the files. We do this even if there was a generator error in order
// to match the behavior of a compiled-in generator.
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> current_output;
+ std::unique_ptr<io::ZeroCopyOutputStream> current_output;
for (int i = 0; i < response.file_size(); i++) {
const CodeGeneratorResponse::File& output_file = response.file(i);
if (!output_file.insertion_point().empty()) {
+ string filename = output_file.name();
// Open a file for insert.
// We reset current_output to NULL first so that the old file is closed
// before the new one is opened.
current_output.reset();
current_output.reset(generator_context->OpenForInsert(
- output_file.name(), output_file.insertion_point()));
+ filename, output_file.insertion_point()));
} else if (!output_file.name().empty()) {
// Starting a new file. Open it.
// We reset current_output to NULL first so that the old file is closed
@@ -1997,7 +1992,7 @@ bool CommandLineInterface::EncodeOrDecode(const DescriptorPool* pool) {
}
DynamicMessageFactory dynamic_factory(pool);
- google::protobuf::scoped_ptr<Message> message(dynamic_factory.GetPrototype(type)->New());
+ std::unique_ptr<Message> message(dynamic_factory.GetPrototype(type)->New());
if (mode_ == MODE_ENCODE) {
SetFdToTextMode(STDIN_FILENO);
diff --git a/src/google/protobuf/compiler/command_line_interface.h b/src/google/protobuf/compiler/command_line_interface.h
index d5d85f2d..7d3037a9 100644
--- a/src/google/protobuf/compiler/command_line_interface.h
+++ b/src/google/protobuf/compiler/command_line_interface.h
@@ -413,11 +413,6 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// dependency file will be written. Otherwise, empty.
string dependency_out_name_;
- // Path to a file that contains serialized AccessInfo which provides
- // relative hotness of fields per message. This helps protoc to generate
- // better code.
- string profile_path_;
-
// True if --include_imports was given, meaning that we should
// write all transitive dependencies to the DescriptorSet. Otherwise, only
// the .proto files listed on the command-line are added.
diff --git a/src/google/protobuf/compiler/command_line_interface_unittest.cc b/src/google/protobuf/compiler/command_line_interface_unittest.cc
index ef7579a2..41eb244a 100644
--- a/src/google/protobuf/compiler/command_line_interface_unittest.cc
+++ b/src/google/protobuf/compiler/command_line_interface_unittest.cc
@@ -40,9 +40,6 @@
#include <unistd.h>
#endif
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
#include <google/protobuf/stubs/stringprintf.h>
@@ -344,7 +341,7 @@ void CommandLineInterfaceTest::RunWithArgs(std::vector<string> args) {
}
}
- google::protobuf::scoped_array<const char * > argv(new const char* [args.size()]);
+ std::unique_ptr<const char * []> argv(new const char* [args.size()]);
for (int i = 0; i < args.size(); i++) {
args[i] = StringReplace(args[i], "$tmpdir", temp_directory_, true);
@@ -2298,7 +2295,7 @@ class EncodeDecodeTest : public testing::TestWithParam<EncodeDecodeTestMode> {
ADD_FAILURE() << "unexpected EncodeDecodeTestMode: " << GetParam();
}
- google::protobuf::scoped_array<const char * > argv(new const char* [args.size()]);
+ std::unique_ptr<const char * []> argv(new const char* [args.size()]);
for (int i = 0; i < args.size(); i++) {
argv[i] = args[i].c_str();
}
diff --git a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
index f99159f5..4e150fe3 100644
--- a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
@@ -44,6 +44,7 @@
#include <map>
+#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/io/zero_copy_stream_impl.h>
@@ -97,9 +98,10 @@ class MockGeneratorContext : public GeneratorContext {
File::GetContents(TestSourceDir() + "/" + physical_filename,
&actual_contents, true));
EXPECT_TRUE(actual_contents == *expected_contents)
- << physical_filename << " needs to be regenerated. Please run "
- "generate_descriptor_proto.sh. Then add this file "
- "to your CL.";
+ << physical_filename
+ << " needs to be regenerated. Please run "
+ "generate_descriptor_proto.sh. "
+ "Then add this file to your CL.";
}
// implements GeneratorContext --------------------------------------
@@ -116,37 +118,50 @@ class MockGeneratorContext : public GeneratorContext {
std::map<string, string*> files_;
};
-TEST(BootstrapTest, GeneratedDescriptorMatches) {
- MockErrorCollector error_collector;
+const char kDescriptorParameter[] = "dllexport_decl=LIBPROTOBUF_EXPORT";
+const char kPluginParameter[] = "dllexport_decl=LIBPROTOC_EXPORT";
+const char kNormalParameter[] = "";
+
+const char* test_protos[][2] = {
+ {"google/protobuf/descriptor", kDescriptorParameter},
+ {"google/protobuf/compiler/plugin", kPluginParameter},
+};
+
+TEST(BootstrapTest, GeneratedFilesMatch) {
+ // We need a mapping from the actual file to virtual and actual path
+ // of the data to compare to.
+ std::map<string, string> vpath_map;
+ std::map<string, string> rpath_map;
+ rpath_map["third_party/protobuf/src/google/protobuf/test_messages_proto2"] =
+ "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"] =
+ "net/proto2/z_generated_example/proto2_weak";
+
DiskSourceTree source_tree;
source_tree.MapPath("", TestSourceDir());
- Importer importer(&source_tree, &error_collector);
- const FileDescriptor* proto_file =
- importer.Import("google/protobuf/descriptor.proto");
- const FileDescriptor* plugin_proto_file =
- importer.Import("google/protobuf/compiler/plugin.proto");
- EXPECT_EQ("", error_collector.text_);
- ASSERT_TRUE(proto_file != NULL);
- ASSERT_TRUE(plugin_proto_file != NULL);
-
- CppGenerator generator;
- MockGeneratorContext context;
- string error;
- string parameter = "dllexport_decl=LIBPROTOBUF_EXPORT";
- ASSERT_TRUE(generator.Generate(proto_file, parameter,
- &context, &error));
- parameter = "dllexport_decl=LIBPROTOC_EXPORT";
- ASSERT_TRUE(generator.Generate(plugin_proto_file, parameter,
- &context, &error));
-
- context.ExpectFileMatches("google/protobuf/descriptor.pb.h",
- "google/protobuf/descriptor.pb.h");
- context.ExpectFileMatches("google/protobuf/descriptor.pb.cc",
- "google/protobuf/descriptor.pb.cc");
- context.ExpectFileMatches("google/protobuf/compiler/plugin.pb.h",
- "google/protobuf/compiler/plugin.pb.h");
- context.ExpectFileMatches("google/protobuf/compiler/plugin.pb.cc",
- "google/protobuf/compiler/plugin.pb.cc");
+
+ for (auto file_parameter : test_protos) {
+ MockErrorCollector error_collector;
+ Importer importer(&source_tree, &error_collector);
+ const FileDescriptor* file =
+ importer.Import(file_parameter[0] + string(".proto"));
+ ASSERT_TRUE(file != nullptr)
+ << "Can't import file " << file_parameter[0] + string(".proto") << "\n";
+ EXPECT_EQ("", error_collector.text_);
+ CppGenerator generator;
+ MockGeneratorContext context;
+ string error;
+ ASSERT_TRUE(generator.Generate(file, file_parameter[1], &context, &error));
+
+ string vpath =
+ FindWithDefault(vpath_map, file_parameter[0], file_parameter[0]);
+ string rpath =
+ FindWithDefault(rpath_map, file_parameter[0], file_parameter[0]);
+ context.ExpectFileMatches(vpath + ".pb.cc", rpath + ".pb.cc");
+ context.ExpectFileMatches(vpath + ".pb.h", rpath + ".pb.h");
+ }
}
} // namespace
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum.cc b/src/google/protobuf/compiler/cpp/cpp_enum.cc
index 8adee0f5..0d6a9e24 100644
--- a/src/google/protobuf/compiler/cpp/cpp_enum.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_enum.cc
@@ -179,7 +179,7 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) {
void EnumGenerator::
GenerateGetEnumDescriptorSpecializations(io::Printer* printer) {
printer->Print(
- "template <> struct is_proto_enum< $classname$> : ::google::protobuf::internal::true_type "
+ "template <> struct is_proto_enum< $classname$> : ::std::true_type "
"{};\n",
"classname", ClassName(descriptor_, true));
if (HasDescriptorMethods(descriptor_->file(), options_)) {
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum_field.cc b/src/google/protobuf/compiler/cpp/cpp_enum_field.cc
index 50c7b5f3..828d0be5 100644
--- a/src/google/protobuf/compiler/cpp/cpp_enum_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_enum_field.cc
@@ -128,7 +128,7 @@ GenerateCopyConstructorCode(io::Printer* printer) const {
void EnumFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
printer->Print(variables_,
- "int value;\n"
+ "int value = 0;\n"
"DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
" int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(\n"
" input, &value)));\n");
@@ -334,7 +334,7 @@ void RepeatedEnumFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
// Don't use ReadRepeatedPrimitive here so that the enum can be validated.
printer->Print(variables_,
- "int value;\n"
+ "int value = 0;\n"
"DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
" int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(\n"
" input, &value)));\n");
@@ -399,7 +399,7 @@ GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const {
"::google::protobuf::io::CodedInputStream::Limit limit = "
"input->PushLimit(static_cast<int>(length));\n"
"while (input->BytesUntilLimit() > 0) {\n"
- " int value;\n"
+ " int value = 0;\n"
" DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
" int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(\n"
" input, &value)));\n");
diff --git a/src/google/protobuf/compiler/cpp/cpp_extension.cc b/src/google/protobuf/compiler/cpp/cpp_extension.cc
index 0a4e0bb9..c416ba10 100644
--- a/src/google/protobuf/compiler/cpp/cpp_extension.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_extension.cc
@@ -35,8 +35,8 @@
#include <google/protobuf/compiler/cpp/cpp_extension.h>
#include <map>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
-#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
@@ -120,7 +120,6 @@ void ExtensionGenerator::GenerateDeclaration(io::Printer* printer) {
" ::google::protobuf::internal::$type_traits$, $field_type$, $packed$ >\n"
" $name$;\n"
);
-
}
void ExtensionGenerator::GenerateDefinition(io::Printer* printer) {
diff --git a/src/google/protobuf/compiler/cpp/cpp_field.cc b/src/google/protobuf/compiler/cpp/cpp_field.cc
index 0cf25b33..0de20f84 100644
--- a/src/google/protobuf/compiler/cpp/cpp_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_field.cc
@@ -34,21 +34,18 @@
#include <google/protobuf/compiler/cpp/cpp_field.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#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>
#include <google/protobuf/compiler/cpp/cpp_map_field.h>
#include <google/protobuf/compiler/cpp/cpp_message_field.h>
#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/wire_format.h>
#include <google/protobuf/io/printer.h>
-#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
@@ -116,26 +113,29 @@ GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const {
}
FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor,
- const Options& options)
+ const Options& options,
+ SCCAnalyzer* scc_analyzer)
: descriptor_(descriptor),
options_(options),
- field_generators_(
- new google::protobuf::scoped_ptr<FieldGenerator>[descriptor->field_count()]) {
+ field_generators_(descriptor->field_count()) {
// Construct all the FieldGenerators.
for (int i = 0; i < descriptor->field_count(); i++) {
- field_generators_[i].reset(MakeGenerator(descriptor->field(i), options));
+ field_generators_[i].reset(
+ MakeGenerator(descriptor->field(i), options, scc_analyzer));
}
}
FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field,
- const Options& options) {
+ const Options& options,
+ SCCAnalyzer* scc_analyzer) {
if (field->is_repeated()) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
if (field->is_map()) {
return new MapFieldGenerator(field, options);
} else {
- return new RepeatedMessageFieldGenerator(field, options);
+ return new RepeatedMessageFieldGenerator(field, options,
+ scc_analyzer);
}
case FieldDescriptor::CPPTYPE_STRING:
switch (field->options().ctype()) {
@@ -151,7 +151,7 @@ FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field,
} else if (field->containing_oneof()) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
- return new MessageOneofFieldGenerator(field, options);
+ return new MessageOneofFieldGenerator(field, options, scc_analyzer);
case FieldDescriptor::CPPTYPE_STRING:
switch (field->options().ctype()) {
default: // StringOneofFieldGenerator handles unknown ctypes.
@@ -166,7 +166,7 @@ FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field,
} else {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
- return new MessageFieldGenerator(field, options);
+ return new MessageFieldGenerator(field, options, scc_analyzer);
case FieldDescriptor::CPPTYPE_STRING:
switch (field->options().ctype()) {
default: // StringFieldGenerator handles unknown ctypes.
diff --git a/src/google/protobuf/compiler/cpp/cpp_field.h b/src/google/protobuf/compiler/cpp/cpp_field.h
index bccfcb9a..8cdbe886 100644
--- a/src/google/protobuf/compiler/cpp/cpp_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_field.h
@@ -37,13 +37,11 @@
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
-#include <google/protobuf/descriptor.h>
+#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_options.h>
+#include <google/protobuf/descriptor.h>
namespace google {
namespace protobuf {
@@ -82,38 +80,12 @@ class FieldGenerator {
// implementation is empty.
virtual void GenerateStaticMembers(io::Printer* /*printer*/) const {}
- // Generate prototypes for accessors that will manipulate imported
- // messages inline. These are for .proto.h headers.
- //
- // In .proto.h mode, the headers of imports are not #included. However,
- // functions that manipulate the imported message types need access to
- // the class definition of the imported message, meaning that the headers
- // must be #included. To get around this, functions that manipulate
- // imported message objects are defined as dependent functions in a base
- // template class. By making them dependent template functions, the
- // function templates will not be instantiated until they are called, so
- // we can defer to those translation units to #include the necessary
- // generated headers.
- //
- // See:
- // http://en.cppreference.com/w/cpp/language/class_template#Implicit_instantiation
- //
- // Most field types don't need this, so the default implementation is empty.
- virtual void GenerateDependentAccessorDeclarations(
- io::Printer* printer) const {}
-
// Generate prototypes for all of the accessor functions related to this
// field. These are placed inside the class definition.
virtual void GenerateAccessorDeclarations(io::Printer* printer) const = 0;
- // Generate inline definitions of depenent accessor functions for this field.
- // These are placed inside the header after all class definitions.
- virtual void GenerateDependentInlineAccessorDefinitions(
- io::Printer* printer) const {}
-
// Generate inline definitions of accessor functions for this field.
// These are placed inside the header after all class definitions.
- // In non-.proto.h mode, this generates dependent accessor functions as well.
virtual void GenerateInlineAccessorDefinitions(
io::Printer* printer) const = 0;
@@ -207,6 +179,11 @@ class FieldGenerator {
// are placed in the message's ByteSize() method.
virtual void GenerateByteSize(io::Printer* printer) const = 0;
+ // Any tags about field layout decisions (such as inlining) to embed in the
+ // offset.
+ virtual uint32 CalculateFieldTag() const { return 0; }
+ virtual bool IsInlined() const { return false; }
+
protected:
const Options& options_;
@@ -217,7 +194,8 @@ class FieldGenerator {
// Convenience class which constructs FieldGenerators for a Descriptor.
class FieldGeneratorMap {
public:
- FieldGeneratorMap(const Descriptor* descriptor, const Options& options);
+ FieldGeneratorMap(const Descriptor* descriptor, const Options& options,
+ SCCAnalyzer* scc_analyzer);
~FieldGeneratorMap();
const FieldGenerator& get(const FieldDescriptor* field) const;
@@ -225,10 +203,11 @@ class FieldGeneratorMap {
private:
const Descriptor* descriptor_;
const Options& options_;
- google::protobuf::scoped_array<google::protobuf::scoped_ptr<FieldGenerator> > field_generators_;
+ std::vector<std::unique_ptr<FieldGenerator>> field_generators_;
static FieldGenerator* MakeGenerator(const FieldDescriptor* field,
- const Options& options);
+ const Options& options,
+ SCCAnalyzer* scc_analyzer);
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
};
diff --git a/src/google/protobuf/compiler/cpp/cpp_file.cc b/src/google/protobuf/compiler/cpp/cpp_file.cc
index a922ee97..02f360bb 100644
--- a/src/google/protobuf/compiler/cpp/cpp_file.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_file.cc
@@ -35,20 +35,17 @@
#include <google/protobuf/compiler/cpp/cpp_file.h>
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <set>
#include <vector>
#include <google/protobuf/compiler/cpp/cpp_enum.h>
-#include <google/protobuf/compiler/cpp/cpp_service.h>
#include <google/protobuf/compiler/cpp/cpp_extension.h>
+#include <google/protobuf/compiler/cpp/cpp_field.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_message.h>
-#include <google/protobuf/compiler/cpp/cpp_field.h>
-#include <google/protobuf/io/printer.h>
+#include <google/protobuf/compiler/cpp/cpp_service.h>
#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
@@ -61,11 +58,11 @@ FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options)
options_(options),
scc_analyzer_(options),
enum_generators_owner_(
- new google::protobuf::scoped_ptr<EnumGenerator>[file->enum_type_count()]),
+ new std::unique_ptr<EnumGenerator>[file->enum_type_count()]),
service_generators_owner_(
- new google::protobuf::scoped_ptr<ServiceGenerator>[file->service_count()]),
+ new std::unique_ptr<ServiceGenerator>[file->service_count()]),
extension_generators_owner_(
- new google::protobuf::scoped_ptr<ExtensionGenerator>[file->extension_count()]) {
+ new std::unique_ptr<ExtensionGenerator>[file->extension_count()]) {
std::vector<const Descriptor*> msgs = FlattenMessagesInFile(file);
for (int i = 0; i < msgs.size(); i++) {
// Deleted in destructor
@@ -141,6 +138,9 @@ void FileGenerator::GenerateHeader(io::Printer* printer) {
printer->Print(
"// @@protoc_insertion_point(includes)\n");
+ printer->Print("#define PROTOBUF_INTERNAL_EXPORT_$filename$ $export$\n",
+ "filename", FileLevelNamespace(file_),
+ "export", options_.dllexport_decl);
GenerateMacroUndefs(printer);
GenerateGlobalStateFunctionDeclarations(printer);
@@ -223,8 +223,9 @@ void FileGenerator::GeneratePBHeader(io::Printer* printer,
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", StripProto(file_->name()));
+ "basename", target_basename);
} else {
GenerateLibraryIncludes(printer);
}
@@ -256,9 +257,10 @@ void FileGenerator::GeneratePBHeader(io::Printer* printer,
}
void FileGenerator::GenerateSourceIncludes(io::Printer* printer) {
+ string target_basename = StripProto(file_->name());
const bool use_system_include = IsWellKnownMessage(file_);
- string header =
- StripProto(file_->name()) + (options_.proto_h ? ".proto.h" : ".pb.h");
+
+ 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"
@@ -269,7 +271,6 @@ void FileGenerator::GenerateSourceIncludes(io::Printer* printer) {
"\n"
"#include <google/protobuf/stubs/common.h>\n"
"#include <google/protobuf/stubs/port.h>\n"
- "#include <google/protobuf/stubs/once.h>\n"
"#include <google/protobuf/io/coded_stream.h>\n"
"#include <google/protobuf/wire_format_lite_inl.h>\n",
"filename", file_->name(),
@@ -296,7 +297,8 @@ void FileGenerator::GenerateSourceIncludes(io::Printer* printer) {
for (int i = 0; i < file_->dependency_count(); i++) {
const FileDescriptor* dep = file_->dependency(i);
const char* extension = ".proto.h";
- string dependency = StripProto(dep->name()) + extension;
+ string basename = StripProto(dep->name());
+ string dependency = basename + extension;
printer->Print(
"#include \"$dependency$\"\n",
"dependency", dependency);
@@ -338,33 +340,34 @@ namespace {
// Generates weak symbol declarations for types that are to be considered weakly
// referenced.
-void GenerateWeakDeclarations(
- const FileDescriptor* file, const Options& options,
- SCCAnalyzer* scc_analyzer,
- io::Printer* printer) {
- std::vector<const FieldDescriptor*> fields;
- ListAllFields(file, &fields);
-
+void GenerateInternalForwardDeclarations(
+ const std::vector<const FieldDescriptor*>& fields, const Options& options,
+ SCCAnalyzer* scc_analyzer, io::Printer* 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<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];
- bool is_weak = IsImplicitWeakField(field, options);
+ 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());
+ string weak_attr;
if (is_weak) {
- const Descriptor* msg = field->message_type();
- string flns = FileLevelNamespace(msg);
- string repr = ClassName(scc_analyzer->GetSCC(msg)->GetRepresentative());
- inits.insert(std::make_pair(flns, "InitDefaults" + repr));
inits.insert(std::make_pair(flns, "AddDescriptors"));
messages.insert(std::make_pair(Namespace(msg), ClassName(msg)));
+ weak_attr = " __attribute__((weak))";
}
- }
-
- if (messages.empty()) {
- return;
+ 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");
@@ -384,13 +387,33 @@ void GenerateWeakDeclarations(
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());
+ }
}
} // namespace
void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) {
GenerateSourceIncludes(printer);
- GenerateWeakDeclarations(file_, options_, &scc_analyzer_, printer);
+
+ // Generate weak declarations. We do this for the whole strongly-connected
+ // component (SCC), because we have a single InitDefaults* function for the
+ // SCC.
+ std::vector<const FieldDescriptor*> fields;
+ for (const Descriptor* message :
+ scc_analyzer_.GetSCC(message_generators_[idx]->descriptor_)
+ ->descriptors) {
+ ListAllFields(message, &fields);
+ }
+ GenerateInternalForwardDeclarations(fields, options_, &scc_analyzer_,
+ 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);
@@ -411,12 +434,6 @@ void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) {
"// @@protoc_insertion_point(namespace_scope)\n");
} // end package namespace
- if (IsSCCRepresentative(message_generators_[idx]->descriptor_)) {
- NamespaceOpener ns(FileLevelNamespace(file_), printer);
- GenerateInitForSCC(GetSCC(message_generators_[idx]->descriptor_), printer);
- }
-
-
printer->Print(
"namespace google {\nnamespace protobuf {\n");
message_generators_[idx]->GenerateSourceInProto2Namespace(printer);
@@ -430,15 +447,16 @@ void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) {
void FileGenerator::GenerateGlobalSource(io::Printer* printer) {
GenerateSourceIncludes(printer);
- GenerateWeakDeclarations(file_, options_, &scc_analyzer_, printer);
- // TODO(gerbens) Generate tables here
-
- // Define the code to initialize reflection. This code uses a global
- // constructor to register reflection data with the runtime pre-main.
- if (HasDescriptorMethods(file_, options_)) {
+ {
NamespaceOpener ns(FileLevelNamespace(file_), printer);
- GenerateReflectionInitializationCode(printer);
+ GenerateTables(printer);
+
+ // Define the code to initialize reflection. This code uses a global
+ // constructor to register reflection data with the runtime pre-main.
+ if (HasDescriptorMethods(file_, options_)) {
+ GenerateReflectionInitializationCode(printer);
+ }
}
NamespaceOpener ns(Namespace(file_), printer);
@@ -466,7 +484,10 @@ void FileGenerator::GenerateGlobalSource(io::Printer* printer) {
void FileGenerator::GenerateSource(io::Printer* printer) {
GenerateSourceIncludes(printer);
- GenerateWeakDeclarations(file_, options_, &scc_analyzer_, printer);
+ std::vector<const FieldDescriptor*> fields;
+ ListAllFields(file_, &fields);
+ GenerateInternalForwardDeclarations(fields, options_, &scc_analyzer_,
+ printer);
{
NamespaceOpener ns(Namespace(file_), printer);
@@ -483,9 +504,25 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
{
NamespaceOpener ns(FileLevelNamespace(file_), printer);
- // Define the initialization code to initialize the default instances.
- // This code doesn't use a global constructor.
- GenerateInitializationCode(printer);
+ GenerateTables(printer);
+
+ // Now generate the InitDefaults for each SCC.
+ for (int i = 0; i < message_generators_.size(); i++) {
+ if (IsSCCRepresentative(message_generators_[i]->descriptor_)) {
+ GenerateInitForSCC(GetSCC(message_generators_[i]->descriptor_),
+ printer);
+ }
+ }
+
+ 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.
@@ -560,7 +597,7 @@ class FileGenerator::ForwardDeclarations {
ForwardDeclarations* AddOrGetNamespace(const string& ns_name) {
ForwardDeclarations*& ns = namespaces_[ns_name];
- if (ns == NULL) {
+ if (ns == nullptr) {
ns = new ForwardDeclarations;
}
return ns;
@@ -648,17 +685,12 @@ class FileGenerator::ForwardDeclarations {
end = classes_.end();
it != end; ++it) {
const Descriptor* d = it->second;
- string extra_class_qualifier;
- // "class" is to disambiguate in case there is also a function with this
- // name. There is code out there that does this!
printer->Print(
"template<> "
"$dllexport_decl$"
- "$class$$classname$* Arena::$func$< $class$$classname$>(Arena*);\n",
- "classname", QualifiedClassName(d),
- "func", MessageCreateFunction(d),
- "class", extra_class_qualifier,
- "dllexport_decl",
+ "$classname$* Arena::CreateMaybeMessage<$classname$>"
+ "(Arena*);\n",
+ "classname", QualifiedClassName(d), "dllexport_decl",
options.dllexport_decl.empty() ? "" : options.dllexport_decl + " ");
}
printer->Print(
@@ -758,18 +790,16 @@ 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.
- string message_factory = "NULL";
printer->Print(
- "void protobuf_AssignDescriptors() {\n"
+ "static 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"
- " ::google::protobuf::MessageFactory* factory = $factory$;\n"
" AssignDescriptors(\n"
" \"$filename$\", schemas, file_default_instances, "
- "TableStruct::offsets, factory,\n"
+ "TableStruct::offsets,\n"
" $metadata$, $enum_descriptors$, $service_descriptors$);\n",
"filename", file_->name(), "metadata",
!message_generators_.empty() ? "file_level_metadata" : "NULL",
@@ -778,14 +808,13 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
"service_descriptors",
HasGenericServices(file_, options_) && file_->service_count() > 0
? "file_level_service_descriptors"
- : "NULL",
- "factory", message_factory);
+ : "NULL");
printer->Print(
"}\n"
"\n"
- "void protobuf_AssignDescriptorsOnce() {\n"
- " static GOOGLE_PROTOBUF_DECLARE_ONCE(once);\n"
- " ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);\n"
+ "static 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",
@@ -795,8 +824,7 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
"service_descriptors",
HasGenericServices(file_, options_) && file_->service_count() > 0
? "file_level_service_descriptors"
- : "NULL",
- "factory", message_factory);
+ : "NULL");
// Only here because of useless string reference that we don't want in
// protobuf_AssignDescriptorsOnce, because that is called from all the
@@ -822,7 +850,7 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
// Now generate the AddDescriptors() function.
printer->Print(
- "void AddDescriptorsImpl() {\n"
+ "static void AddDescriptorsImpl() {\n"
" InitDefaults();\n");
printer->Indent();
@@ -891,8 +919,8 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
"}\n"
"\n"
"void AddDescriptors() {\n"
- " static GOOGLE_PROTOBUF_DECLARE_ONCE(once);\n"
- " ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);\n"
+ " static ::google::protobuf::internal::once_flag once;\n"
+ " ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);\n"
"}\n");
printer->Print(
@@ -907,47 +935,16 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) {
const string scc_name = ClassName(scc->GetRepresentative());
+ // We use static and not anonymous namespace because symbol names are
+ // substantially shorter.
printer->Print(
- "void InitDefaults$scc_name$Impl() {\n"
+ "static void InitDefaults$scc_name$() {\n"
" GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n"
- "#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS\n"
- " ::google::protobuf::internal::InitProtobufDefaultsForceUnique();\n"
- "#else\n"
- " ::google::protobuf::internal::InitProtobufDefaults();\n"
- "#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS\n",
- // Force initialization of primitive values we depend on.
+ , // awkward comma due to macro
"scc_name", scc_name);
printer->Indent();
- // Call the InitDefaults() methods for all of our dependencies, to make
- // sure they get added first.
- for (int i = 0; i < scc->children.size(); i++) {
- const SCC* child_scc = scc->children[i];
- const FileDescriptor* dependency = child_scc->GetRepresentative()->file();
- // Print the namespace prefix for the dependency.
- string file_namespace = FileLevelNamespace(dependency);
- std::map<string, string> variables;
- variables["file_namespace"] = file_namespace;
- variables["scc_name"] = ClassName(child_scc->GetRepresentative(), false);
- bool using_weak_fields = UsingImplicitWeakFields(file_, options_);
- if (using_weak_fields) {
- // We're building for lite with implicit weak fields, so we need to handle
- // the possibility that this InitDefaults function is not linked into the
- // binary. Some of these might actually be guaranteed to be non-null since
- // we might have a strong reference to the dependency (via a required
- // field, for example), but it's simplest to just assume that any of them
- // could be null.
- printer->Print(
- variables,
- "if (&$file_namespace$::InitDefaults$scc_name$ != NULL) {\n"
- " $file_namespace$::InitDefaults$scc_name$();\n"
- "}\n");
- } else {
- printer->Print(variables,
- "$file_namespace$::InitDefaults$scc_name$();\n");
- }
- }
// First construct all the necessary default instances.
for (int i = 0; i < message_generators_.size(); i++) {
@@ -982,23 +979,24 @@ void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) {
}
printer->Outdent();
printer->Print("}\n\n");
+
printer->Print(
- "void InitDefaults$scc_name$() {\n"
- " static GOOGLE_PROTOBUF_DECLARE_ONCE(once);\n"
- " ::google::protobuf::GoogleOnceInit(&once, "
- "&InitDefaults$scc_name$Impl);\n"
- "}\n\n",
- "scc_name", scc_name);
+ "$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 + " ");
+ for (const SCC* child : scc->children) {
+ auto repr = child->GetRepresentative();
+ printer->Print("\n &$ns$::scc_info_$child$.base,", "ns",
+ FileLevelNamespace(repr), "child", ClassName(repr));
+ }
+ printer->Print("}};\n\n");
}
-void FileGenerator::GenerateInitializationCode(io::Printer* printer) {
- // Messages depend on the existence of a default instance, which has to
- // initialized properly. The default instances are allocated in the data
- // segment, but we can't quite allocate the type directly. The destructors
- // cannot run at program exit as this could lead to segfaults in a threaded
- // environment. Hence these instances must be inplace constructed at first
- // use.
-
+void FileGenerator::GenerateTables(io::Printer* printer) {
if (options_.table_driven_parsing) {
// TODO(ckennelly): Gate this with the same options flag to enable
// table-driven parsing.
@@ -1105,16 +1103,6 @@ void FileGenerator::GenerateInitializationCode(io::Printer* printer) {
"};\n"
"\n");
}
-
- // -----------------------------------------------------------------
- // All functionality that need private access.
-
- // Now generate the InitDefaults for each SCC.
- for (int i = 0; i < message_generators_.size(); i++) {
- if (IsSCCRepresentative(message_generators_[i]->descriptor_)) {
- GenerateInitForSCC(GetSCC(message_generators_[i]->descriptor_), printer);
- }
- }
}
void FileGenerator::GenerateForwardDeclarations(io::Printer* printer) {
@@ -1145,8 +1133,8 @@ void FileGenerator::GenerateTopHeaderGuard(io::Printer* printer,
"// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
"// source: $filename$\n"
"\n"
- "#ifndef PROTOBUF_$filename_identifier$_INCLUDED\n"
- "#define PROTOBUF_$filename_identifier$_INCLUDED\n"
+ "#ifndef PROTOBUF_INCLUDED_$filename_identifier$\n"
+ "#define PROTOBUF_INCLUDED_$filename_identifier$\n"
"\n"
"#include <string>\n",
"filename", file_->name(), "filename_identifier", filename_identifier);
@@ -1156,7 +1144,7 @@ void FileGenerator::GenerateTopHeaderGuard(io::Printer* printer,
void FileGenerator::GenerateBottomHeaderGuard(
io::Printer* printer, const string& filename_identifier) {
printer->Print(
- "#endif // PROTOBUF_$filename_identifier$_INCLUDED\n",
+ "#endif // PROTOBUF_INCLUDED_$filename_identifier$\n",
"filename_identifier", filename_identifier);
}
@@ -1193,7 +1181,9 @@ void FileGenerator::GenerateLibraryIncludes(io::Printer* printer) {
"#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/generated_message_util.h>\n"
+ "#include <google/protobuf/inlined_string_field.h>\n");
+
if (HasDescriptorMethods(file_, options_)) {
printer->Print(
@@ -1280,11 +1270,12 @@ void FileGenerator::GenerateDependencyIncludes(io::Printer* printer) {
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);
printer->Print(
"#include $left$$dependency$.pb.h$right$$iwyu$\n",
- "dependency", StripProto(name),
+ "dependency", basename,
"iwyu", (public_import) ? " // IWYU pragma: export" : "",
"left", use_system_include ? "<" : "\"",
"right", use_system_include ? ">" : "\"");
@@ -1318,28 +1309,6 @@ void FileGenerator::GenerateGlobalStateFunctionDeclarations(
"void $dllexport_decl$AddDescriptors();\n", "dllexport_decl",
options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " ");
}
- for (int i = 0; i < message_generators_.size(); i++) {
- if (!IsSCCRepresentative(message_generators_[i]->descriptor_)) continue;
- string scc_name = ClassName(message_generators_[i]->descriptor_);
- // TODO(gerbens) Remove the Impl from header. This is solely because
- // it currently still needs to be a friend of the protos.
- printer->Print(
- "void $dllexport_decl$InitDefaults$scc_name$Impl();\n"
- "void $dllexport_decl$InitDefaults$scc_name$();\n",
- "scc_name", scc_name, "dllexport_decl",
- options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " ");
- }
- // TODO(gerbens) This is for proto1 interoperability. Remove when proto1
- // is gone.
- printer->Print(
- "inline void $dllexport_decl$InitDefaults() {\n", "dllexport_decl",
- options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " ");
- for (int i = 0; i < message_generators_.size(); i++) {
- if (!IsSCCRepresentative(message_generators_[i]->descriptor_)) continue;
- string scc_name = ClassName(message_generators_[i]->descriptor_);
- printer->Print(" InitDefaults$scc_name$();\n", "scc_name", scc_name);
- }
- printer->Print("}\n");
printer->Print(
"} // namespace $file_namespace$\n",
"file_namespace", FileLevelNamespace(file_));
@@ -1416,8 +1385,6 @@ void FileGenerator::GenerateInlineFunctionDefinitions(io::Printer* printer) {
printer->Print(kThinSeparator);
printer->Print("\n");
}
- // Methods of the dependent base class must always be inline in the header.
- message_generators_[i]->GenerateDependentInlineMethods(printer);
}
}
diff --git a/src/google/protobuf/compiler/cpp/cpp_file.h b/src/google/protobuf/compiler/cpp/cpp_file.h
index 7e61cbad..94da9a14 100644
--- a/src/google/protobuf/compiler/cpp/cpp_file.h
+++ b/src/google/protobuf/compiler/cpp/cpp_file.h
@@ -37,9 +37,6 @@
#include <algorithm>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <set>
#include <string>
#include <vector>
@@ -97,7 +94,7 @@ class FileGenerator {
void GenerateSourceDefaultInstance(int idx, io::Printer* printer);
void GenerateInitForSCC(const SCC* scc, io::Printer* printer);
- void GenerateInitializationCode(io::Printer* printer);
+ void GenerateTables(io::Printer* printer);
void GenerateReflectionInitializationCode(io::Printer* printer);
// For other imports, generates their forward-declarations.
@@ -176,10 +173,10 @@ class FileGenerator {
// These members are just for owning (and thus proper deleting).
// Nested (enum/extension)_generators are owned by child messages.
- google::protobuf::scoped_array<google::protobuf::scoped_ptr<EnumGenerator> > enum_generators_owner_;
- google::protobuf::scoped_array<google::protobuf::scoped_ptr<ServiceGenerator> >
+ std::unique_ptr<std::unique_ptr<EnumGenerator> []> enum_generators_owner_;
+ std::unique_ptr<std::unique_ptr<ServiceGenerator> []>
service_generators_owner_;
- google::protobuf::scoped_array<google::protobuf::scoped_ptr<ExtensionGenerator> >
+ std::unique_ptr<std::unique_ptr<ExtensionGenerator> []>
extension_generators_owner_;
// E.g. if the package is foo.bar, package_parts_ is {"foo", "bar"}.
diff --git a/src/google/protobuf/compiler/cpp/cpp_generator.cc b/src/google/protobuf/compiler/cpp/cpp_generator.cc
index 5d8ea300..20bb8a1a 100644
--- a/src/google/protobuf/compiler/cpp/cpp_generator.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_generator.cc
@@ -36,17 +36,15 @@
#include <vector>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <utility>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/compiler/cpp/cpp_file.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
+#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
-#include <google/protobuf/descriptor.pb.h>
+
namespace google {
namespace protobuf {
@@ -66,12 +64,6 @@ bool CppGenerator::Generate(const FileDescriptor* file,
// -----------------------------------------------------------------
// parse generator options
- // TODO(kenton): If we ever have more options, we may want to create a
- // class that encapsulates them which we can pass down to all the
- // generator classes. Currently we pass dllexport_decl down to all of
- // them via the constructors, but we don't want to have to add another
- // constructor parameter for every option.
-
// If the dllexport_decl option is passed to the compiler, we need to write
// it in front of every symbol that should be exported if this .proto is
// compiled into a Windows DLL. E.g., if the user invokes the protocol
@@ -127,11 +119,12 @@ bool CppGenerator::Generate(const FileDescriptor* file,
string basename = StripProto(file->name());
+
FileGenerator file_generator(file, file_options);
// Generate header(s).
if (file_options.proto_h) {
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(basename + ".proto.h"));
GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
@@ -143,14 +136,14 @@ bool CppGenerator::Generate(const FileDescriptor* file,
file_generator.GenerateProtoHeader(
&printer, file_options.annotate_headers ? info_path : "");
if (file_options.annotate_headers) {
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output(
+ std::unique_ptr<io::ZeroCopyOutputStream> info_output(
generator_context->Open(info_path));
annotations.SerializeToZeroCopyStream(info_output.get());
}
}
{
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(basename + ".pb.h"));
GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
@@ -162,7 +155,7 @@ bool CppGenerator::Generate(const FileDescriptor* file,
file_generator.GeneratePBHeader(
&printer, file_options.annotate_headers ? info_path : "");
if (file_options.annotate_headers) {
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output(
+ std::unique_ptr<io::ZeroCopyOutputStream> info_output(
generator_context->Open(info_path));
annotations.SerializeToZeroCopyStream(info_output.get());
}
@@ -172,7 +165,7 @@ bool CppGenerator::Generate(const FileDescriptor* file,
if (UsingImplicitWeakFields(file, file_options)) {
{
// This is the global .cc file, containing enum/services/tables/reflection
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(basename + ".pb.cc"));
io::Printer printer(output.get(), '$');
file_generator.GenerateGlobalSource(&printer);
@@ -191,7 +184,7 @@ bool CppGenerator::Generate(const FileDescriptor* file,
}
for (int i = 0; i < num_cc_files; i++) {
// TODO(gerbens) Agree on naming scheme.
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(basename + "." + SimpleItoa(i) + ".cc"));
io::Printer printer(output.get(), '$');
if (i < file_generator.NumMessages()) {
@@ -199,7 +192,7 @@ bool CppGenerator::Generate(const FileDescriptor* file,
}
}
} else {
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(basename + ".pb.cc"));
io::Printer printer(output.get(), '$');
file_generator.GenerateSource(&printer);
diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.cc b/src/google/protobuf/compiler/cpp/cpp_helpers.cc
index 172acedd..163dac0a 100644
--- a/src/google/protobuf/compiler/cpp/cpp_helpers.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_helpers.cc
@@ -42,6 +42,7 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/io/printer.h>
+#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
@@ -73,7 +74,7 @@ const char* const kKeywordList[] = {
"constexpr", "const_cast", "continue", "decltype", "default", "delete", "do",
"double", "dynamic_cast", "else", "enum", "explicit", "export", "extern",
"false", "float", "for", "friend", "goto", "if", "inline", "int", "long",
- "mutable", "namespace", "new", "noexcept", "not", "not_eq", "NULL",
+ "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr",
"operator", "or", "or_eq", "private", "protected", "public", "register",
"reinterpret_cast", "return", "short", "signed", "sizeof", "static",
"static_assert", "static_cast", "struct", "switch", "template", "this",
@@ -219,24 +220,12 @@ string ReferenceFunctionName(const Descriptor* descriptor) {
return QualifiedClassName(descriptor) + "_ReferenceStrong";
}
-string DependentBaseClassTemplateName(const Descriptor* descriptor) {
- return ClassName(descriptor, false) + "_InternalBase";
-}
-
string SuperClassName(const Descriptor* descriptor, const Options& options) {
return HasDescriptorMethods(descriptor->file(), options)
? "::google::protobuf::Message"
: "::google::protobuf::MessageLite";
}
-string DependentBaseDownCast() {
- return "reinterpret_cast<T*>(this)->";
-}
-
-string DependentBaseConstDownCast() {
- return "reinterpret_cast<const T*>(this)->";
-}
-
string FieldName(const FieldDescriptor* field) {
string result = field->name();
LowerString(&result);
@@ -294,60 +283,6 @@ string FieldConstantName(const FieldDescriptor *field) {
return result;
}
-bool IsFieldDependent(const FieldDescriptor* field) {
- if (field->containing_oneof() != NULL &&
- field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
- return true;
- }
- if (field->is_map()) {
- const Descriptor* map_descriptor = field->message_type();
- for (int i = 0; i < map_descriptor->field_count(); i++) {
- if (IsFieldDependent(map_descriptor->field(i))) {
- return true;
- }
- }
- return false;
- }
- if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
- return false;
- }
- if (field->containing_oneof() != NULL) {
- // Oneof fields will always be dependent.
- //
- // This is a unique case for field codegen. Field generators are
- // responsible for generating all the field-specific accessor
- // functions, except for the clear_*() function; instead, field
- // generators produce inline clearing code.
- //
- // For non-oneof fields, the Message class uses the inline clearing
- // code to define the field's clear_*() function, as well as in the
- // destructor. For oneof fields, the Message class generates a much
- // more complicated clear_*() function, which clears only the oneof
- // member that is set, in addition to clearing methods for each of the
- // oneof members individually.
- //
- // Since oneofs do not have their own generator class, the Message code
- // generation logic would be significantly complicated in order to
- // split dependent and non-dependent manipulation logic based on
- // whether the oneof truly needs to be dependent; so, for oneof fields,
- // we just assume it (and its constituents) should be manipulated by a
- // dependent base class function.
- //
- // This is less precise than how dependent message-typed fields are
- // handled, but the cost is limited to only the generated code for the
- // oneof field, which seems like an acceptable tradeoff.
- return true;
- }
- if (field->file() == field->message_type()->file()) {
- return false;
- }
- return true;
-}
-
-string DependentTypeName(const FieldDescriptor* field) {
- return "InternalBase_" + field->name() + "_T";
-}
-
string FieldMessageTypeName(const FieldDescriptor* field) {
// Note: The Google-internal version of Protocol Buffers uses this function
// as a hook point for hacks to support legacy code.
@@ -748,12 +683,17 @@ bool UsingImplicitWeakFields(const FileDescriptor* file,
GetOptimizeFor(file, options) == FileOptions::LITE_RUNTIME;
}
-
-bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options) {
+bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options,
+ SCCAnalyzer* scc_analyzer) {
return UsingImplicitWeakFields(field->file(), options) &&
field->type() == FieldDescriptor::TYPE_MESSAGE &&
!field->is_required() && !field->is_map() &&
- field->containing_oneof() == NULL;
+ field->containing_oneof() == NULL &&
+ !IsWellKnownMessage(field->message_type()->file()) &&
+ // We do not support implicit weak fields between messages in the same
+ // strongly-connected component.
+ scc_analyzer->GetSCC(field->containing_type()) !=
+ scc_analyzer->GetSCC(field->message_type());
}
struct CompareDescriptors {
@@ -920,6 +860,7 @@ void ListAllTypesForServices(const FileDescriptor* fd,
}
}
+
} // namespace cpp
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.h b/src/google/protobuf/compiler/cpp/cpp_helpers.h
index 4026d0ed..eac65124 100644
--- a/src/google/protobuf/compiler/cpp/cpp_helpers.h
+++ b/src/google/protobuf/compiler/cpp/cpp_helpers.h
@@ -38,8 +38,9 @@
#include <map>
#include <string>
#include <google/protobuf/compiler/cpp/cpp_options.h>
-#include <google/protobuf/io/printer.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/stubs/strutil.h>
@@ -53,6 +54,7 @@ namespace cpp {
extern const char kThickSeparator[];
extern const char kThinSeparator[];
+
// Name space of the proto file. This namespace is such that the string
// "<namespace>::some_name" is the correct fully qualified namespace.
// This means if the package is empty the namespace is "", and otherwise
@@ -102,19 +104,9 @@ string DefaultInstanceName(const Descriptor* descriptor);
// fields.
string ReferenceFunctionName(const Descriptor* descriptor);
-// Name of the CRTP class template (for use with proto_h).
-// This is a class name, like "ProtoName_InternalBase".
-string DependentBaseClassTemplateName(const Descriptor* descriptor);
-
-// Name of the base class: either the dependent base class (for use with
-// proto_h) or google::protobuf::Message.
+// Name of the base class: google::protobuf::Message or google::protobuf::MessageLite.
string SuperClassName(const Descriptor* descriptor, const Options& options);
-// Returns a string that down-casts from the dependent base class to the
-// derived class.
-string DependentBaseDownCast();
-string DependentBaseConstDownCast();
-
// 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
@@ -141,20 +133,6 @@ inline const Descriptor* FieldScope(const FieldDescriptor* field) {
field->extension_scope() : field->containing_type();
}
-// Returns true if the given 'field_descriptor' has a message type that is
-// a dependency of the file where the field is defined (i.e., the field
-// type is defined in a different file than the message holding the field).
-//
-// This only applies to Message-typed fields. Enum-typed fields may refer
-// to an enum in a dependency; however, enums are specified and
-// forward-declared with an enum-base, so the definition is not required to
-// manipulate the field value.
-bool IsFieldDependent(const FieldDescriptor* field_descriptor);
-
-// Returns the name that should be used for forcing dependent lookup from a
-// dependent base class.
-string DependentTypeName(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);
@@ -314,6 +292,11 @@ inline string MessageCreateFunction(const Descriptor* d) {
return SupportsArenas(d) ? "CreateMessage" : "Create";
}
+inline string MakeDefaultName(const FieldDescriptor* field) {
+ return "_i_give_permission_to_break_this_code_default_" + FieldName(field) +
+ "_";
+}
+
bool IsAnyMessage(const FileDescriptor* descriptor);
bool IsAnyMessage(const Descriptor* descriptor);
@@ -350,13 +333,6 @@ inline std::vector<const Descriptor*> FlattenMessagesInFile(
bool HasWeakFields(const Descriptor* desc);
bool HasWeakFields(const FileDescriptor* desc);
-// Indicates whether we should use implicit weak fields for this file.
-bool UsingImplicitWeakFields(const FileDescriptor* file,
- const Options& options);
-
-// Indicates whether to treat this field as implicitly weak.
-bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options);
-
// Returns true if the "required" restriction check should be ignored for the
// given field.
inline static bool ShouldIgnoreRequiredFieldCheck(const FieldDescriptor* field,
@@ -462,11 +438,21 @@ class LIBPROTOC_EXPORT SCCAnalyzer {
void AddChildren(SCC* scc);
};
+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,
+ SCCAnalyzer* scc_analyzer);
+
} // namespace cpp
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/cpp/cpp_map_field.cc b/src/google/protobuf/compiler/cpp/cpp_map_field.cc
index b22c0754..0e485cac 100644
--- a/src/google/protobuf/compiler/cpp/cpp_map_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_map_field.cc
@@ -104,9 +104,7 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
MapFieldGenerator::MapFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
- : FieldGenerator(options),
- descriptor_(descriptor),
- dependent_field_(options.proto_h && IsFieldDependent(descriptor)) {
+ : FieldGenerator(options), descriptor_(descriptor) {
SetMessageVariables(descriptor, &variables_, options);
}
@@ -202,7 +200,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
key = "entry->key()";
value = "entry->value()";
printer->Print(variables_,
- "::google::protobuf::scoped_ptr<$map_classname$> entry($name$_.NewEntry());\n");
+ "::std::unique_ptr<$map_classname$> entry($name$_.NewEntry());\n");
printer->Print(variables_,
"{\n"
" ::std::string data;\n"
@@ -258,7 +256,7 @@ static void GenerateSerializationLoop(io::Printer* printer,
const string& ptr,
bool loop_via_iterators) {
printer->Print(variables,
- StrCat("::google::protobuf::scoped_ptr<$map_classname$> entry;\n",
+ StrCat("::std::unique_ptr<$map_classname$> entry;\n",
loop_header, " {\n").c_str());
printer->Indent();
@@ -365,7 +363,7 @@ void MapFieldGenerator::GenerateSerializeWithCachedSizes(
"\n"
"if ($deterministic$ &&\n"
" this->$name$().size() > 1) {\n"
- " ::google::protobuf::scoped_array<SortItem> items(\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"
" size_type n = 0;\n"
@@ -402,7 +400,7 @@ GenerateByteSize(io::Printer* printer) const {
"total_size += $tag_size$ *\n"
" ::google::protobuf::internal::FromIntSize(this->$name$_size());\n"
"{\n"
- " ::google::protobuf::scoped_ptr<$map_classname$> entry;\n"
+ " ::std::unique_ptr<$map_classname$> entry;\n"
" for (::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_iterator\n"
" it = this->$name$().begin();\n"
" it != this->$name$().end(); ++it) {\n");
diff --git a/src/google/protobuf/compiler/cpp/cpp_map_field.h b/src/google/protobuf/compiler/cpp/cpp_map_field.h
index 88e3b464..0d54f0ea 100644
--- a/src/google/protobuf/compiler/cpp/cpp_map_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_map_field.h
@@ -66,7 +66,6 @@ class MapFieldGenerator : public FieldGenerator {
io::Printer* printer, const std::map<string, string>& variables) const;
const FieldDescriptor* descriptor_;
- const bool dependent_field_;
std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator);
diff --git a/src/google/protobuf/compiler/cpp/cpp_message.cc b/src/google/protobuf/compiler/cpp/cpp_message.cc
index 9b2f090e..778fc406 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_message.cc
@@ -38,9 +38,6 @@
#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <utility>
#include <vector>
@@ -49,9 +46,9 @@
#include <google/protobuf/compiler/cpp/cpp_field.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_padding_optimizer.h>
+#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
-#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/map_entry_lite.h>
@@ -60,6 +57,7 @@
#include <google/protobuf/stubs/substitute.h>
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -440,13 +438,12 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor,
index_in_file_messages_(index_in_file_messages),
classname_(ClassName(descriptor, false)),
options_(options),
- field_generators_(descriptor, options),
+ field_generators_(descriptor, options, scc_analyzer),
max_has_bit_index_(0),
enum_generators_(
- new google::protobuf::scoped_ptr<EnumGenerator>[descriptor->enum_type_count()]),
- extension_generators_(new google::protobuf::scoped_ptr<
+ new std::unique_ptr<EnumGenerator>[descriptor->enum_type_count()]),
+ extension_generators_(new std::unique_ptr<
ExtensionGenerator>[descriptor->extension_count()]),
- use_dependent_base_(false),
num_weak_fields_(0),
message_layout_helper_(new PaddingOptimizer()),
scc_analyzer_(scc_analyzer) {
@@ -492,13 +489,6 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor,
if (descriptor->field(i)->is_required()) {
++num_required_fields_;
}
- if (options.proto_h && IsFieldDependent(descriptor->field(i))) {
- use_dependent_base_ = true;
- }
- }
- if (options.proto_h && descriptor->oneof_decl_count() > 0) {
- // Always make oneofs dependent.
- use_dependent_base_ = true;
}
table_driven_ = TableDrivenParsingEnabled(descriptor_, options_);
@@ -539,22 +529,6 @@ void MessageGenerator::FillMessageForwardDeclarations(
}
void MessageGenerator::
-GenerateDependentFieldAccessorDeclarations(io::Printer* printer) {
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor* field = descriptor_->field(i);
-
- PrintFieldComment(printer, field);
-
- std::map<string, string> vars;
- SetCommonFieldVariables(field, &vars, options_);
-
- // Generate type-specific accessor declarations.
- field_generators_.get(field).GenerateDependentAccessorDeclarations(printer);
- printer->Print("\n");
- }
-}
-
-void MessageGenerator::
GenerateFieldAccessorDeclarations(io::Printer* printer) {
// optimized_fields_ does not contain fields where
// field->containing_oneof() != NULL
@@ -585,21 +559,6 @@ GenerateFieldAccessorDeclarations(io::Printer* printer) {
SetCommonFieldVariables(field, &vars, options_);
vars["constant_name"] = FieldConstantName(field);
- bool dependent_field = use_dependent_base_ && IsFieldDependent(field);
- if (dependent_field &&
- field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
- !field->is_map()) {
- // If this field is dependent, the dependent base class determines
- // the message type from the derived class (which is a template
- // parameter). This typedef is for that:
- printer->Print(
- "private:\n"
- "typedef $field_type$ $dependent_type$;\n"
- "public:\n",
- "field_type", FieldMessageTypeName(field),
- "dependent_type", DependentTypeName(field));
- }
-
if (field->is_repeated()) {
printer->Print(vars, "$deprecated_attr$int ${$$name$_size$}$() const;\n");
printer->Annotate("{", "}", field);
@@ -637,6 +596,7 @@ GenerateFieldAccessorDeclarations(io::Printer* printer) {
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
printer->Print(
+ "void clear_$oneof_name$();\n"
"$camel_oneof_name$Case $oneof_name$_case() const;\n",
"camel_oneof_name",
UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true),
@@ -645,32 +605,6 @@ GenerateFieldAccessorDeclarations(io::Printer* printer) {
}
void MessageGenerator::
-GenerateDependentFieldAccessorDefinitions(io::Printer* printer) {
- if (!use_dependent_base_) return;
-
- printer->Print("// $classname$\n\n", "classname",
- DependentBaseClassTemplateName(descriptor_));
-
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor* field = descriptor_->field(i);
-
- if (field->options().weak()) continue;
-
- PrintFieldComment(printer, field);
- // Generate type-specific accessors.
- field_generators_.get(field)
- .GenerateDependentInlineAccessorDefinitions(printer);
-
- printer->Print("\n");
- }
-
- // Generate has_$name$() and clear_has_$name$() functions for oneofs
- // Similar to other has-bits, these must always be in the header if we
- // are using a dependent base class.
- GenerateOneofHasBits(printer);
-}
-
-void MessageGenerator::
GenerateSingularFieldHasBits(const FieldDescriptor* field,
std::map<string, string> vars,
io::Printer* printer) {
@@ -812,18 +746,6 @@ GenerateFieldAccessorDefinitions(io::Printer* printer) {
std::map<string, string> vars;
SetCommonFieldVariables(field, &vars, options_);
- if (use_dependent_base_ && IsFieldDependent(field)) {
- vars["tmpl"] = "template<class T>\n";
- vars["dependent_classname"] =
- DependentBaseClassTemplateName(descriptor_) + "<T>";
- vars["this_message"] = "reinterpret_cast<T*>(this)->";
- vars["this_const_message"] = "reinterpret_cast<const T*>(this)->";
- } else {
- vars["tmpl"] = "";
- vars["dependent_classname"] = vars["classname"];
- vars["this_message"] = "";
- vars["this_const_message"] = "";
- }
// Generate has_$name$() or $name$_size().
if (field->is_repeated()) {
@@ -851,42 +773,8 @@ GenerateFieldAccessorDefinitions(io::Printer* printer) {
printer->Print("\n");
}
- if (!use_dependent_base_) {
- // Generate has_$name$() and clear_has_$name$() functions for oneofs
- // If we aren't using a dependent base, they can be with the other functions
- // that are #ifdef-guarded.
- GenerateOneofHasBits(printer);
- }
-}
-
-void MessageGenerator::
-GenerateDependentBaseClassDefinition(io::Printer* printer) {
- if (!use_dependent_base_) {
- return;
- }
-
- std::map<string, string> vars;
- vars["classname"] = DependentBaseClassTemplateName(descriptor_);
- vars["full_name"] = descriptor_->full_name();
- vars["superclass"] = SuperClassName(descriptor_, options_);
-
- printer->Print(vars,
- "template <class T>\n"
- "class $classname$ : public $superclass$ "
- "/* @@protoc_insertion_point(dep_base_class_definition:$full_name$) */ {\n"
- " public:\n");
- printer->Indent();
-
- printer->Print(vars,
- "$classname$() {}\n"
- "virtual ~$classname$() {}\n"
- "\n");
-
- // Generate dependent accessor methods for all fields.
- GenerateDependentFieldAccessorDeclarations(printer);
-
- printer->Outdent();
- printer->Print("};\n");
+ // Generate has_$name$() and clear_has_$name$() functions for oneofs.
+ GenerateOneofHasBits(printer);
}
void MessageGenerator::
@@ -919,7 +807,7 @@ GenerateClassDefinition(io::Printer* printer) {
"$classname$*>(&_$classname$_default_instance_); }\n");
if (HasDescriptorMethods(descriptor_->file(), options_)) {
printer->Print(
- " void MergeFrom(const ::google::protobuf::Message& other) PROTOBUF_FINAL;\n"
+ " void MergeFrom(const ::google::protobuf::Message& other) final;\n"
" ::google::protobuf::Metadata GetMetadata() const;\n"
"};\n");
} else {
@@ -927,10 +815,6 @@ GenerateClassDefinition(io::Printer* printer) {
}
return;
}
- if (use_dependent_base_) {
- GenerateDependentBaseClassDefinition(printer);
- printer->Print("\n");
- }
std::map<string, string> vars;
vars["classname"] = classname_;
@@ -942,20 +826,12 @@ GenerateClassDefinition(io::Printer* printer) {
} else {
vars["dllexport"] = options_.dllexport_decl + " ";
}
- if (use_dependent_base_) {
- vars["superclass"] =
- DependentBaseClassTemplateName(descriptor_) + "<" + classname_ + ">";
- } else {
- vars["superclass"] = SuperClassName(descriptor_, options_);
- }
+ 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_);
- if (use_dependent_base_) {
- printer->Print(vars, " friend class $superclass$;\n");
- }
printer->Print(" public:\n");
printer->Indent();
@@ -1016,10 +892,10 @@ GenerateClassDefinition(io::Printer* printer) {
// 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 PROTOBUF_FINAL {\n"
+ "inline ::google::protobuf::Arena* GetArena() const final {\n"
" return GetArenaNoVirtual();\n"
"}\n"
- "inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {\n"
+ "inline void* GetMaybeArenaPointer() const final {\n"
" return MaybeArenaPtr();\n"
"}\n");
}
@@ -1071,7 +947,7 @@ GenerateClassDefinition(io::Printer* printer) {
" return reinterpret_cast<const $classname$*>(\n"
" &_$classname$_default_instance_);\n"
"}\n"
- "static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =\n"
+ "static constexpr int kIndexInFileMessages =\n"
" $message_index$;\n"
"\n");
@@ -1091,12 +967,13 @@ GenerateClassDefinition(io::Printer* printer) {
"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");
}
- vars["new_final"] = " PROTOBUF_FINAL";
+ vars["new_final"] = " final";
- vars["create_func"] = MessageCreateFunction(descriptor_);
printer->Print(vars,
"void Swap($classname$* other);\n"
"friend void swap($classname$& a, $classname$& b) {\n"
@@ -1106,32 +983,32 @@ GenerateClassDefinition(io::Printer* printer) {
"// implements Message ----------------------------------------------\n"
"\n"
"inline $classname$* New() const$new_final$ {\n"
- " return ::google::protobuf::Arena::$create_func$<$classname$>(NULL);\n"
+ " return CreateMaybeMessage<$classname$>(NULL);\n"
"}\n"
"\n"
"$classname$* New(::google::protobuf::Arena* arena) const$new_final$ {\n"
- " return ::google::protobuf::Arena::$create_func$<$classname$>(arena);\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_) ?
- " PROTOBUF_FINAL" : "";
+ " final" : "";
if (HasGeneratedMethods(descriptor_->file(), options_)) {
if (HasDescriptorMethods(descriptor_->file(), options_)) {
printer->Print(vars,
- "void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;\n"
- "void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;\n");
+ "void CopyFrom(const ::google::protobuf::Message& from) final;\n"
+ "void MergeFrom(const ::google::protobuf::Message& from) final;\n");
} else {
printer->Print(vars,
"void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)\n"
- " PROTOBUF_FINAL;\n");
+ " final;\n");
}
- vars["clear_final"] = " PROTOBUF_FINAL";
- vars["is_initialized_final"] = " PROTOBUF_FINAL";
- vars["merge_partial_final"] = " PROTOBUF_FINAL";
+ vars["clear_final"] = " final";
+ vars["is_initialized_final"] = " final";
+ vars["merge_partial_final"] = " final";
printer->Print(
vars,
@@ -1140,7 +1017,7 @@ GenerateClassDefinition(io::Printer* printer) {
"void Clear()$clear_final$;\n"
"bool IsInitialized() const$is_initialized_final$;\n"
"\n"
- "size_t ByteSizeLong() const PROTOBUF_FINAL;\n"
+ "size_t ByteSizeLong() const final;\n"
"bool MergePartialFromCodedStream(\n"
" ::google::protobuf::io::CodedInputStream* input)$merge_partial_final$;\n");
if (!options_.table_driven_serialization ||
@@ -1148,7 +1025,7 @@ GenerateClassDefinition(io::Printer* printer) {
printer->Print(
"void SerializeWithCachedSizes(\n"
" ::google::protobuf::io::CodedOutputStream* output) const "
- "PROTOBUF_FINAL;\n");
+ "final;\n");
}
// DiscardUnknownFields() is implemented in message.cc using reflections. We
// need to implement this function in generated code for messages.
@@ -1160,19 +1037,18 @@ GenerateClassDefinition(io::Printer* printer) {
if (HasFastArraySerialization(descriptor_->file(), options_)) {
printer->Print(
"::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(\n"
- " bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;\n");
+ " bool deterministic, ::google::protobuf::uint8* target) const final;\n");
}
}
printer->Print(
- "int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }\n"
- "private:\n"
- "void SharedCtor();\n"
- "void SharedDtor();\n"
- "void SetCachedSize(int size) const$final$;\n"
- "void InternalSwap($classname$* other);\n",
- "classname", classname_,
- "final", use_final);
+ "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);
if (SupportsArenas(descriptor_)) {
printer->Print(
// TODO(gerbens) Make this private! Currently people are deriving from
@@ -1212,11 +1088,11 @@ GenerateClassDefinition(io::Printer* printer) {
if (HasDescriptorMethods(descriptor_->file(), options_)) {
printer->Print(
- "::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;\n"
+ "::google::protobuf::Metadata GetMetadata() const final;\n"
"\n");
} else {
printer->Print(
- "::std::string GetTypeName() const PROTOBUF_FINAL;\n"
+ "::std::string GetTypeName() const final;\n"
"\n");
}
@@ -1295,7 +1171,6 @@ GenerateClassDefinition(io::Printer* printer) {
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
printer->Print(
"inline bool has_$oneof_name$() const;\n"
- "void clear_$oneof_name$();\n"
"inline void clear_has_$oneof_name$();\n\n",
"oneof_name", descriptor_->oneof_decl(i)->name());
}
@@ -1313,7 +1188,8 @@ GenerateClassDefinition(io::Printer* printer) {
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 int _cached_size_;\n";
+ const string cached_size_decl =
+ "mutable ::google::protobuf::internal::CachedSize _cached_size_;\n";
const size_t sizeof_has_bits = HasBitsSize();
const string has_bits_decl = sizeof_has_bits == 0 ? "" :
@@ -1423,13 +1299,10 @@ GenerateClassDefinition(io::Printer* printer) {
// The TableStruct struct needs access to the private parts, in order to
// construct the offsets of all members.
- // TODO(gerbens) Remove the friend for InitDefaults.
- printer->Print(
- "friend struct ::$file_namespace$::TableStruct;\n"
- "friend void ::$file_namespace$::InitDefaults$scc_name$Impl();\n",
- // Vars.
- "scc_name", scc_name_, "file_namespace",
- FileLevelNamespace(descriptor_));
+ printer->Print("friend struct ::$file_namespace$::TableStruct;\n",
+ // Vars.
+ "scc_name", scc_name_, "file_namespace",
+ FileLevelNamespace(descriptor_));
printer->Outdent();
printer->Print("};");
@@ -1437,18 +1310,6 @@ GenerateClassDefinition(io::Printer* printer) {
}
void MessageGenerator::
-GenerateDependentInlineMethods(io::Printer* printer) {
- if (IsMapEntryMessage(descriptor_)) return;
- for (int i = 0; i < descriptor_->field_count(); i++) {
- if (descriptor_->field(i)->options().weak()) {
- field_generators_.get(descriptor_->field(i))
- .GenerateDependentInlineAccessorDefinitions(printer);
- }
- }
- GenerateDependentFieldAccessorDefinitions(printer);
-}
-
-void MessageGenerator::
GenerateInlineMethods(io::Printer* printer) {
if (IsMapEntryMessage(descriptor_)) return;
GenerateFieldAccessorDefinitions(printer);
@@ -1603,7 +1464,8 @@ uint32 CalculateType(uint32 type, uint32 type_class) {
return (type - 1) + type_class * 20;
}
-uint32 CalcFieldNum(const FieldDescriptor* field, const Options& options) {
+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()) {
@@ -1624,9 +1486,16 @@ uint32 CalcFieldNum(const FieldDescriptor* field, const Options& options) {
#else
// We need to calculate for each field what function the table driven code
// should use to serialize it. This returns the index in a lookup table.
-uint32 CalcFieldNum(const FieldDescriptor* field, const Options& options) {
+uint32 CalcFieldNum(const FieldGenerator& generator,
+ const FieldDescriptor* field, const Options& options) {
bool is_a_map = IsMapEntryMessage(field->containing_type());
int type = field->type();
+ if (type == FieldDescriptor::TYPE_STRING ||
+ type == FieldDescriptor::TYPE_BYTES) {
+ if (generator.IsInlined()) {
+ type = internal::FieldMetadata::kInlinedType;
+ }
+ }
if (field->containing_oneof()) {
return internal::FieldMetadata::CalculateType(
type, internal::FieldMetadata::kOneOf);
@@ -1668,6 +1537,8 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) {
if (IsMapEntryMessage(descriptor_)) {
for (int i = 0; i < 2; i++) {
const FieldDescriptor* field = sorted[i];
+ const FieldGenerator& generator = field_generators_.get(field);
+
uint32 tag = internal::WireFormatLite::MakeTag(
field->number(), WireFormat::WireTypeForFieldType(field->type()));
@@ -1676,7 +1547,7 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) {
vars["field_name"] = FieldName(field);
vars["tag"] = SimpleItoa(tag);
vars["hasbit"] = SimpleItoa(i);
- vars["type"] = SimpleItoa(CalcFieldNum(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()));
@@ -1765,7 +1636,9 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) {
SimpleItoa(FindMessageIndexInFile(field->message_type()));
}
}
- vars["type"] = SimpleItoa(CalcFieldNum(field, options_));
+
+ const FieldGenerator& generator = field_generators_.get(field);
+ vars["type"] = SimpleItoa(CalcFieldNum(generator, field, options_));
if (field->options().weak()) {
@@ -1912,6 +1785,11 @@ GenerateClassMethods(io::Printer* printer) {
"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_);
}
@@ -2049,16 +1927,26 @@ 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)) {
case FieldOptions::STRING:
- default:
+ default: {
+ if (generator.IsInlined()) {
+ processing_type = internal::TYPE_STRING_INLINED;
+ break;
+ }
break;
+ }
}
} else if (field->type() == FieldDescriptor::TYPE_BYTES) {
switch (EffectiveStringCType(field)) {
case FieldOptions::STRING:
default:
+ if (generator.IsInlined()) {
+ processing_type = internal::TYPE_BYTES_INLINED;
+ break;
+ }
break;
}
}
@@ -2093,7 +1981,7 @@ size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) {
"{\n"
" GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n"
" $classname$, $name$_),\n"
- " static_cast< ::google::protobuf::uint32>($presence$),\n"
+ " static_cast<::google::protobuf::uint32>($presence$),\n"
" $nwtype$, $pwtype$, $ptype$, $tag_size$\n"
"},\n");
}
@@ -2150,20 +2038,7 @@ size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) {
printer->Print(
vars,
"{::google::protobuf::internal::AuxillaryParseTableField::message_aux{\n"
- " &$ns$::_$classname$_default_instance_,\n");
-
- bool dont_emit_table =
- !TableDrivenParsingEnabled(field->message_type(), options_);
-
- if (dont_emit_table) {
- printer->Print(" NULL,\n");
- } else {
- printer->Print(vars,
- " ::$file_namespace$::TableStruct::schema +\n"
- " $ns$::$classname$::kIndexInFileMessages,\n");
- }
-
- printer->Print("}},\n");
+ " &$ns$::_$classname$_default_instance_}},\n");
last_field_number++;
break;
}
@@ -2174,7 +2049,7 @@ size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) {
field->default_value_string().empty()
? "&::google::protobuf::internal::fixed_address_empty_string"
: "&" + Namespace(field) + " ::" + classname_ +
- "::_default_" + FieldName(field) + "_";
+ "::" + MakeDefaultName(field);
break;
case FieldOptions::CORD:
case FieldOptions::STRING_PIECE:
@@ -2245,14 +2120,20 @@ std::pair<size_t, size_t> MessageGenerator::GenerateOffsets(
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
if (field->containing_oneof() || field->options().weak()) {
- printer->Print("offsetof($classname$DefaultTypeInternal, $name$_),\n",
+ printer->Print("offsetof($classname$DefaultTypeInternal, $name$_)",
"classname", full_classname, "name", FieldName(field));
} else {
printer->Print(
- "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, "
- "$name$_),\n",
+ "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_)",
"classname", full_classname, "name", FieldName(field));
}
+
+ uint32 tag = field_generators_.get(field).CalculateFieldTag();
+ if (tag != 0) {
+ printer->Print(" | $tag$", "tag", SimpleItoa(tag));
+ }
+
+ printer->Print(",\n");
}
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
@@ -2286,15 +2167,6 @@ GenerateSharedConstructorCode(io::Printer* printer) {
"classname", classname_);
printer->Indent();
- bool need_to_clear_cached_size = true;
- // We reproduce the logic used for laying out _cached_sized_ in the class
- // definition, as to initialize it in-order.
- if (HasFieldPresence(descriptor_->file()) &&
- (HasBitsSize() % 8) != 0) {
- printer->Print("_cached_size_ = 0;\n");
- need_to_clear_cached_size = false;
- }
-
std::vector<bool> processed(optimized_order_.size(), false);
GenerateConstructorBody(printer, processed, false);
@@ -2304,10 +2176,6 @@ GenerateSharedConstructorCode(io::Printer* printer) {
"oneof_name", descriptor_->oneof_decl(i)->name());
}
- if (need_to_clear_cached_size) {
- printer->Print("_cached_size_ = 0;\n");
- }
-
printer->Outdent();
printer->Print("}\n\n");
}
@@ -2412,7 +2280,7 @@ GenerateArenaDestructorCode(io::Printer* printer) {
"classname", classname_);
} else {
printer->Print(
- "void $classname$::RegisterArenaDtor(::google::protobuf::Arena* arena) {\n"
+ "void $classname$::RegisterArenaDtor(::google::protobuf::Arena*) {\n"
"}\n",
"classname", classname_);
}
@@ -2491,12 +2359,7 @@ void MessageGenerator::GenerateConstructorBody(io::Printer* printer,
void MessageGenerator::
GenerateStructors(io::Printer* printer) {
string superclass;
- if (use_dependent_base_) {
- superclass =
- DependentBaseClassTemplateName(descriptor_) + "<" + classname_ + ">";
- } else {
- superclass = SuperClassName(descriptor_, options_);
- }
+ superclass = SuperClassName(descriptor_, options_);
string initializer_with_arena = superclass + "()";
if (descriptor_->extension_range_count() > 0) {
@@ -2528,15 +2391,14 @@ GenerateStructors(io::Printer* printer) {
initializer_null += ", _any_metadata_(&type_url_, &value_)";
}
if (num_weak_fields_ > 0) {
- initializer_null += ", _weak_field_map_(NULL)";
+ initializer_null += ", _weak_field_map_(nullptr)";
}
printer->Print(
"$classname$::$classname$()\n"
" : $initializer$ {\n"
- " if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {\n"
- " ::$file_namespace$::InitDefaults$scc_name$();\n"
- " }\n"
+ " ::google::protobuf::internal::InitSCC(\n"
+ " &$file_namespace$::scc_info_$scc_name$.base);\n"
" SharedCtor();\n"
" // @@protoc_insertion_point(constructor:$full_name$)\n"
"}\n",
@@ -2548,7 +2410,9 @@ GenerateStructors(io::Printer* printer) {
printer->Print(
"$classname$::$classname$(::google::protobuf::Arena* arena)\n"
" : $initializer$ {\n"
- " ::$file_namespace$::InitDefaults$scc_name$();\n"
+ " "
+ "::google::protobuf::internal::InitSCC(&$file_namespace$::scc_info_$scc_name$."
+ "base);\n"
" SharedCtor();\n"
" RegisterArenaDtor(arena);\n"
" // @@protoc_insertion_point(arena_constructor:$full_name$)\n"
@@ -2589,16 +2453,6 @@ GenerateStructors(io::Printer* printer) {
printer->Print(",\n_has_bits_(from._has_bits_)");
}
- bool need_to_emit_cached_size = true;
- const string cached_size_decl = ",\n_cached_size_(0)";
- // We reproduce the logic used for laying out _cached_sized_ in the class
- // definition, as to initialize it in-order.
- if (HasFieldPresence(descriptor_->file()) &&
- (HasBitsSize() % 8) != 0) {
- printer->Print(cached_size_decl.c_str());
- need_to_emit_cached_size = false;
- }
-
std::vector<bool> processed(optimized_order_.size(), false);
for (int i = 0; i < optimized_order_.size(); ++i) {
const FieldDescriptor* field = optimized_order_[i];
@@ -2613,11 +2467,6 @@ GenerateStructors(io::Printer* printer) {
"name", FieldName(field));
}
- if (need_to_emit_cached_size) {
- printer->Print(cached_size_decl.c_str());
- need_to_emit_cached_size = false;
- }
-
if (IsAnyMessage(descriptor_)) {
printer->Print(",\n_any_metadata_(&type_url_, &value_)");
}
@@ -2702,12 +2551,10 @@ GenerateStructors(io::Printer* printer) {
// Generate SetCachedSize.
printer->Print(
- "void $classname$::SetCachedSize(int size) const {\n"
- " GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
- " _cached_size_ = size;\n"
- " GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
- "}\n",
- "classname", classname_);
+ "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_) &&
@@ -2726,7 +2573,9 @@ GenerateStructors(io::Printer* printer) {
printer->Print(
"const $classname$& $classname$::default_instance() {\n"
- " ::$file_namespace$::InitDefaults$scc_name$();\n"
+ " "
+ "::google::protobuf::internal::InitSCC(&$file_namespace$::scc_info_$scc_name$.base)"
+ ";\n"
" return *internal_default_instance();\n"
"}\n\n",
"classname", classname_, "scc_name", scc_name_, "file_namespace",
@@ -2737,7 +2586,7 @@ void MessageGenerator::GenerateSourceInProto2Namespace(io::Printer* printer) {
printer->Print(
"template<> "
"GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE "
- "$classname$* Arena::$create_func$< $classname$ >(Arena* arena) {\n"
+ "$classname$* Arena::CreateMaybeMessage< $classname$ >(Arena* arena) {\n"
" return Arena::$create_func$Internal< $classname$ >(arena);\n"
"}\n",
"classname", QualifiedClassName(descriptor_),
@@ -2823,10 +2672,10 @@ GenerateClear(io::Printer* printer) {
chunks.push_back(chunks_frag[i]);
const FieldDescriptor* field = chunks_frag[i].front();
const FieldDescriptor* next_field =
- (i + 1) < chunks_frag.size() ? chunks_frag[i + 1].front() : NULL;
+ (i + 1) < chunks_frag.size() ? chunks_frag[i + 1].front() : nullptr;
if (CanInitializeByZeroing(field) &&
(chunks_frag[i].size() == 1 || unconditional_budget < 0) &&
- next_field != NULL &&
+ next_field != nullptr &&
has_bit_indices_[field->index()] / 8 ==
has_bit_indices_[next_field->index()] / 8) {
GOOGLE_CHECK(!CanInitializeByZeroing(next_field));
@@ -3111,7 +2960,6 @@ GenerateSwap(io::Printer* printer) {
printer->Print("_internal_metadata_.Swap(&other->_internal_metadata_);\n");
- printer->Print("swap(_cached_size_, other->_cached_size_);\n");
if (descriptor_->extension_range_count() > 0) {
printer->Print("_extensions_.Swap(&other->_extensions_);\n");
}
@@ -3492,8 +3340,12 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
printer->Print("for (;;) {\n");
printer->Indent();
- uint32 maxtag = descriptor_->field_count() == 0 ? 0 :
- WireFormat::MakeTag(ordered_fields[descriptor_->field_count() - 1]);
+ // 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
+ // field is a packable repeated field, so to simplify things we assume the
+ // highest possible wire type of 5.
+ uint32 maxtag =
+ ordered_fields.empty() ? 0 : ordered_fields.back()->number() * 8 + 5;
const int kCutoff0 = 127; // fits in 1-byte varint
const int kCutoff1 = (127 << 7) + 127; // fits in 2-byte varint
@@ -3511,6 +3363,15 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
break;
}
}
+
+ for (int i = 0; i < parent->extension_count(); i++) {
+ const FieldDescriptor* field = parent->extension(i);
+ if (field->type() == FieldDescriptor::TYPE_GROUP &&
+ field->message_type() == descriptor_) {
+ capture_last_tag = true;
+ break;
+ }
+ }
}
for (int i = 0; i < descriptor_->file()->extension_count(); i++) {
@@ -3522,7 +3383,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
}
}
- printer->Print("::std::pair< ::google::protobuf::uint32, bool> p = "
+ 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",
@@ -3621,7 +3482,6 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
printer->Outdent();
printer->Print("}\n\n");
}
-
printer->Print("default: {\n");
printer->Indent();
}
@@ -4012,7 +3872,7 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
// Merge the fields and the extension ranges, both sorted by field number.
{
LazySerializerEmitter e(this, printer, to_array);
- const FieldDescriptor* last_weak_field = NULL;
+ const FieldDescriptor* last_weak_field = nullptr;
int i, j;
for (i = 0, j = 0;
i < ordered_fields.size() || j < sorted_extensions.size();) {
@@ -4024,16 +3884,16 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
last_weak_field = field;
PrintFieldComment(printer, field);
} else {
- if (last_weak_field != NULL) {
+ if (last_weak_field != nullptr) {
e.Emit(last_weak_field);
- last_weak_field = NULL;
+ last_weak_field = nullptr;
}
e.Emit(field);
}
} else {
- if (last_weak_field != NULL) {
+ if (last_weak_field != nullptr) {
e.Emit(last_weak_field);
- last_weak_field = NULL;
+ last_weak_field = nullptr;
}
e.Flush();
GenerateSerializeOneExtensionRange(printer,
@@ -4041,7 +3901,7 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
to_array);
}
}
- if (last_weak_field != NULL) {
+ if (last_weak_field != nullptr) {
e.Emit(last_weak_field);
}
}
@@ -4103,8 +3963,9 @@ static string ConditionalToCheckBitmasks(const std::vector<uint32>& masks) {
}
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";
}
@@ -4117,20 +3978,19 @@ GenerateByteSize(io::Printer* printer) {
SetUnknkownFieldsVariable(descriptor_, options_, &vars);
vars["classname"] = classname_;
vars["full_name"] = descriptor_->full_name();
- printer->Print(vars,
- "size_t $classname$::ByteSizeLong() const {\n"
- "// @@protoc_insertion_point(message_set_byte_size_start:$full_name$)\n"
- " size_t total_size = _extensions_.MessageSetByteSize();\n"
- " if ($have_unknown_fields$) {\n"
- " total_size += ::google::protobuf::internal::WireFormat::\n"
- " ComputeUnknownMessageSetItemsSize($unknown_fields$);\n"
- " }\n"
- " int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n"
- " GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
- " _cached_size_ = cached_size;\n"
- " GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
- " return total_size;\n"
- "}\n");
+ printer->Print(
+ vars,
+ "size_t $classname$::ByteSizeLong() const {\n"
+ "// @@protoc_insertion_point(message_set_byte_size_start:$full_name$)\n"
+ " size_t total_size = _extensions_.MessageSetByteSize();\n"
+ " if ($have_unknown_fields$) {\n"
+ " total_size += ::google::protobuf::internal::WireFormat::\n"
+ " ComputeUnknownMessageSetItemsSize($unknown_fields$);\n"
+ " }\n"
+ " int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n"
+ " SetCachedSize(cached_size);\n"
+ " return total_size;\n"
+ "}\n");
return;
}
@@ -4362,17 +4222,18 @@ GenerateByteSize(io::Printer* printer) {
printer->Print("total_size += _weak_field_map_.ByteSizeLong();\n");
}
- // We update _cached_size_ even though this is a const method. In theory,
- // this is not thread-compatible, because concurrent writes have undefined
- // results. In practice, since any concurrent writes will be writing the
- // exact same value, it works on all common processors. In a future version
- // of C++, _cached_size_ should be made into an atomic<int>.
+ // We update _cached_size_ even though this is a const method. Because
+ // const methods might be called concurrently this needs to be atomic
+ // operations or the program is undefined. In practice, since any concurrent
+ // writes will be writing the exact same value, normal writes will work on
+ // all common processors. We use a dedicated wrapper class to abstract away
+ // 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"
- "GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
- "_cached_size_ = cached_size;\n"
- "GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
- "return total_size;\n");
+ "int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n"
+ "SetCachedSize(cached_size);\n"
+ "return total_size;\n");
printer->Outdent();
printer->Print("}\n");
@@ -4421,7 +4282,7 @@ GenerateIsInitialized(io::Printer* printer) {
!ShouldIgnoreRequiredFieldCheck(field, options_) &&
scc_analyzer_->HasRequiredFields(field->message_type())) {
if (field->is_repeated()) {
- if (IsImplicitWeakField(field, options_)) {
+ if (IsImplicitWeakField(field, options_, scc_analyzer_)) {
printer->Print(
"if (!::google::protobuf::internal::AllAreInitializedWeak(this->$name$_))"
" return false;\n",
diff --git a/src/google/protobuf/compiler/cpp/cpp_message.h b/src/google/protobuf/compiler/cpp/cpp_message.h
index 06e2030b..ca2ca2c9 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message.h
+++ b/src/google/protobuf/compiler/cpp/cpp_message.h
@@ -36,9 +36,6 @@
#define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <set>
#include <string>
#include <google/protobuf/compiler/cpp/cpp_field.h>
@@ -87,9 +84,6 @@ class MessageGenerator {
// file).
void GenerateInlineMethods(io::Printer* printer);
- // Dependent methods are always inline.
- void GenerateDependentInlineMethods(io::Printer* printer);
-
// Source file stuff.
// Generate extra fields
@@ -111,10 +105,7 @@ class MessageGenerator {
private:
// Generate declarations and definitions of accessors for fields.
- void GenerateDependentBaseClassDefinition(io::Printer* printer);
- void GenerateDependentFieldAccessorDeclarations(io::Printer* printer);
void GenerateFieldAccessorDeclarations(io::Printer* printer);
- void GenerateDependentFieldAccessorDefinitions(io::Printer* printer);
void GenerateFieldAccessorDefinitions(io::Printer* printer);
// Generate the table-driven parsing array. Returns the number of entries
@@ -222,15 +213,14 @@ class MessageGenerator {
std::vector<const FieldDescriptor *> optimized_order_;
std::vector<int> has_bit_indices_;
int max_has_bit_index_;
- google::protobuf::scoped_array<google::protobuf::scoped_ptr<EnumGenerator> > enum_generators_;
- google::protobuf::scoped_array<google::protobuf::scoped_ptr<ExtensionGenerator> > extension_generators_;
+ std::unique_ptr<std::unique_ptr<EnumGenerator> []> enum_generators_;
+ std::unique_ptr<std::unique_ptr<ExtensionGenerator> []> extension_generators_;
int num_required_fields_;
- bool use_dependent_base_;
int num_weak_fields_;
// table_driven_ indicates the generated message uses table-driven parsing.
bool table_driven_;
- google::protobuf::scoped_ptr<MessageLayoutHelper> message_layout_helper_;
+ std::unique_ptr<MessageLayoutHelper> message_layout_helper_;
SCCAnalyzer* scc_analyzer_;
string scc_name_;
diff --git a/src/google/protobuf/compiler/cpp/cpp_message_field.cc b/src/google/protobuf/compiler/cpp/cpp_message_field.cc
index 530a6392..c1e15c52 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_message_field.cc
@@ -70,17 +70,16 @@ string ReinterpretCast(const string& type, const string& expression,
}
void SetMessageVariables(const FieldDescriptor* descriptor,
- std::map<string, string>* variables,
- const Options& options) {
+ const Options& options, bool implicit_weak,
+ std::map<string, string>* variables) {
SetCommonFieldVariables(descriptor, variables, options);
(*variables)["type"] = FieldMessageTypeName(descriptor);
- (*variables)["casted_member"] =
- ReinterpretCast((*variables)["type"] + "*", (*variables)["name"] + "_",
- IsImplicitWeakField(descriptor, options));
+ (*variables)["casted_member"] = ReinterpretCast(
+ (*variables)["type"] + "*", (*variables)["name"] + "_", implicit_weak);
(*variables)["type_default_instance"] =
DefaultInstanceName(descriptor->message_type());
(*variables)["type_reference_function"] =
- IsImplicitWeakField(descriptor, options)
+ implicit_weak
? (" " + ReferenceFunctionName(descriptor->message_type()) + "();\n")
: "";
(*variables)["stream_writer"] =
@@ -94,8 +93,6 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
SafeFunctionName(descriptor->containing_type(),
descriptor, "release_");
(*variables)["full_name"] = descriptor->full_name();
- (*variables)["create_func"] =
- MessageCreateFunction(descriptor->message_type());
}
} // namespace
@@ -103,11 +100,13 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
// ===================================================================
MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor,
- const Options& options)
+ const Options& options,
+ SCCAnalyzer* scc_analyzer)
: FieldGenerator(options),
descriptor_(descriptor),
- implicit_weak_field_(IsImplicitWeakField(descriptor, options)) {
- SetMessageVariables(descriptor, &variables_, options);
+ implicit_weak_field_(
+ IsImplicitWeakField(descriptor, options, scc_analyzer)) {
+ SetMessageVariables(descriptor, options, implicit_weak_field_, &variables_);
}
MessageFieldGenerator::~MessageFieldGenerator() {}
@@ -115,7 +114,7 @@ MessageFieldGenerator::~MessageFieldGenerator() {}
void MessageFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
if (implicit_weak_field_) {
- printer->Print(variables_, "google::protobuf::MessageLite* $name$_;\n");
+ printer->Print(variables_, "::google::protobuf::MessageLite* $name$_;\n");
} else {
printer->Print(variables_, "$type$* $name$_;\n");
}
@@ -129,8 +128,16 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
// 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"
+ "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_,
@@ -162,22 +169,22 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions(
io::Printer* printer) const {
if (implicit_weak_field_) {
printer->Print(variables_,
- "const google::protobuf::MessageLite& $classname$::_internal_$name$() const {\n"
+ "const ::google::protobuf::MessageLite& $classname$::_internal_$name$() const {\n"
" if ($name$_ != NULL) {\n"
" return *$name$_;\n"
" } else if (&$type_default_instance$ != NULL) {\n"
- " return *reinterpret_cast<const google::protobuf::MessageLite*>(\n"
+ " return *reinterpret_cast<const ::google::protobuf::MessageLite*>(\n"
" &$type_default_instance$);\n"
" } else {\n"
- " return *reinterpret_cast<const google::protobuf::MessageLite*>(\n"
- " &::google::protobuf::internal::implicit_weak_message_default_instance);\n"
+ " return "
+ "*::google::protobuf::internal::ImplicitWeakMessage::default_instance();\n"
" }\n"
"}\n");
}
if (SupportsArenas(descriptor_)) {
if (implicit_weak_field_) {
printer->Print(variables_,
- "google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n"
+ "::google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n"
" $set_hasbit$\n"
" if ($name$_ == NULL) {\n"
" if (&$type_default_instance$ == NULL) {\n"
@@ -185,7 +192,7 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions(
" ::google::protobuf::internal::ImplicitWeakMessage>(\n"
" GetArenaNoVirtual());\n"
" } else {\n"
- " $name$_ = reinterpret_cast<const google::protobuf::MessageLite*>(\n"
+ " $name$_ = reinterpret_cast<const ::google::protobuf::MessageLite*>(\n"
" &$type_default_instance$)->New(GetArenaNoVirtual());\n"
" }\n"
" }\n"
@@ -212,13 +219,13 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions(
"}\n");
} else if (implicit_weak_field_) {
printer->Print(variables_,
- "google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n"
+ "::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"
+ " $name$_ = reinterpret_cast<const ::google::protobuf::MessageLite*>(\n"
" &$type_default_instance$)->New();\n"
" }\n"
" }\n"
@@ -229,9 +236,14 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions(
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"
+ "}\n");
+ }
printer->Print(variables_,
"inline const $type$& $classname$::$name$() const {\n"
- "$type_reference_function$"
" const $type$* p = $casted_member$;\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return p != NULL ? *p : *reinterpret_cast<const $type$*>(\n"
@@ -247,7 +259,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
if (SupportsArenas(descriptor_)) {
printer->Print(variables_,
" if (GetArenaNoVirtual() != NULL) {\n"
- " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);\n"
+ " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);\n"
" }\n");
}
printer->Print(variables_,
@@ -269,16 +281,15 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$* $classname$::mutable_$name$() {\n"
- "$type_reference_function$"
" $set_hasbit$\n"
- " if ($name$_ == NULL) {\n");
+ " if ($name$_ == NULL) {\n"
+ " auto* p = CreateMaybeMessage<$type$>(GetArenaNoVirtual());\n");
if (implicit_weak_field_) {
printer->Print(variables_,
- " _internal_mutable_$name$();\n");
+ " $name$_ = reinterpret_cast<::google::protobuf::MessageLite*>(p);\n");
} else {
printer->Print(variables_,
- " $name$_ = ::google::protobuf::Arena::$create_func$< $type$ >(\n"
- " GetArenaNoVirtual());\n");
+ " $name$_ = p;\n");
}
printer->Print(variables_,
" }\n"
@@ -309,7 +320,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
// isn't defined in this file.
printer->Print(variables_,
" ::google::protobuf::Arena* submessage_arena =\n"
- " reinterpret_cast< ::google::protobuf::MessageLite*>($name$)->GetArena();\n");
+ " reinterpret_cast<::google::protobuf::MessageLite*>($name$)->GetArena();\n");
} else if (!SupportsArenas(descriptor_->message_type())) {
printer->Print(variables_,
" ::google::protobuf::Arena* submessage_arena = NULL;\n");
@@ -436,7 +447,7 @@ void MessageFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
printer->Print(variables_,
"::google::protobuf::internal::WireFormatLite::Write$stream_writer$(\n"
- " $number$, *$field_member$, output);\n");
+ " $number$, this->_internal_$name$(), output);\n");
}
void MessageFieldGenerator::
@@ -444,7 +455,7 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
printer->Print(variables_,
"target = ::google::protobuf::internal::WireFormatLite::\n"
" InternalWrite$declared_type$ToArray(\n"
- " $number$, *$field_member$, deterministic, target);\n");
+ " $number$, this->_internal_$name$(), deterministic, target);\n");
}
void MessageFieldGenerator::
@@ -457,11 +468,10 @@ GenerateByteSize(io::Printer* printer) const {
// ===================================================================
-MessageOneofFieldGenerator::
-MessageOneofFieldGenerator(const FieldDescriptor* descriptor,
- const Options& options)
- : MessageFieldGenerator(descriptor, options),
- dependent_base_(options.proto_h) {
+MessageOneofFieldGenerator::MessageOneofFieldGenerator(
+ const FieldDescriptor* descriptor, const Options& options,
+ SCCAnalyzer* scc_analyzer)
+ : MessageFieldGenerator(descriptor, options, scc_analyzer) {
SetCommonOneofFieldVariables(descriptor, &variables_);
}
@@ -480,7 +490,7 @@ void MessageOneofFieldGenerator::GenerateNonInlineAccessorDefinitions(
// isn't defined in this file.
printer->Print(variables_,
" ::google::protobuf::Arena* submessage_arena =\n"
- " reinterpret_cast< ::google::protobuf::MessageLite*>($name$)->GetArena();\n");
+ " reinterpret_cast<::google::protobuf::MessageLite*>($name$)->GetArena();\n");
} else if (!SupportsArenas(descriptor_->message_type())) {
printer->Print(variables_,
" ::google::protobuf::Arena* submessage_arena = NULL;\n");
@@ -503,6 +513,12 @@ void MessageOneofFieldGenerator::GenerateNonInlineAccessorDefinitions(
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"
@@ -512,7 +528,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
if (SupportsArenas(descriptor_)) {
printer->Print(variables_,
" if (GetArenaNoVirtual() != NULL) {\n"
- " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);\n"
+ " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);\n"
" }\n");
}
printer->Print(variables_,
@@ -565,7 +581,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
- " $field_member$ = ::google::protobuf::Arena::$create_func$< $type$ >(\n"
+ " $field_member$ = CreateMaybeMessage< $type$ >(\n"
" GetArenaNoVirtual());\n"
" }\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
@@ -611,12 +627,13 @@ GenerateConstructorCode(io::Printer* printer) const {
// ===================================================================
RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator(
- const FieldDescriptor* descriptor, const Options& options)
+ const FieldDescriptor* descriptor, const Options& options,
+ SCCAnalyzer* scc_analyzer)
: FieldGenerator(options),
descriptor_(descriptor),
- dependent_field_(options.proto_h && IsFieldDependent(descriptor)),
- implicit_weak_field_(IsImplicitWeakField(descriptor, options)) {
- SetMessageVariables(descriptor, &variables_, options);
+ implicit_weak_field_(
+ IsImplicitWeakField(descriptor, options, scc_analyzer)) {
+ SetMessageVariables(descriptor, options, implicit_weak_field_, &variables_);
}
RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() {}
@@ -628,19 +645,6 @@ GeneratePrivateMembers(io::Printer* printer) const {
}
void RepeatedMessageFieldGenerator::
-InternalGenerateTypeDependentAccessorDeclarations(io::Printer* printer) const {
- printer->Print(variables_, "$deprecated_attr$$type$* ${$add_$name$$}$();\n");
- printer->Annotate("{", "}", descriptor_);
-}
-
-void RepeatedMessageFieldGenerator::
-GenerateDependentAccessorDeclarations(io::Printer* printer) const {
- if (dependent_field_) {
- InternalGenerateTypeDependentAccessorDeclarations(printer);
- }
-}
-
-void RepeatedMessageFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
"$deprecated_attr$$type$* ${$mutable_$name$$}$(int index);\n");
@@ -653,9 +657,8 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
"$deprecated_attr$const $type$& $name$(int index) const;\n");
printer->Annotate("name", descriptor_);
- if (!dependent_field_) {
- InternalGenerateTypeDependentAccessorDeclarations(printer);
- }
+ 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");
@@ -663,29 +666,6 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
}
void RepeatedMessageFieldGenerator::
-GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const {
- if (!dependent_field_) {
- return;
- }
- std::map<string, string> variables(variables_);
- // For the CRTP base class, all mutation methods are dependent, and so
- // they must be in the header.
- variables["dependent_classname"] =
- DependentBaseClassTemplateName(descriptor_->containing_type()) + "<T>";
- variables["this_message"] = DependentBaseDownCast();
- variables["this_const_message"] = DependentBaseConstDownCast();
-
- // Generate per-element accessors:
- printer->Print(variables,
- "template <class T>\n"
- "inline $type$* $dependent_classname$::add_$name$() {\n"
- " // @@protoc_insertion_point(field_add:$full_name$)\n"
- "$type_reference_function$"
- " return $this_message$$name$_.Add();\n"
- "}\n");
-}
-
-void RepeatedMessageFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$* $classname$::mutable_$name$(int index) {\n"
@@ -705,7 +685,6 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
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$_.InternalCheckedGet(index,\n"
" *reinterpret_cast<const $type$*>(&$type_default_instance$));\n"
"}\n");
@@ -718,14 +697,11 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"}\n");
}
- if (!dependent_field_) {
- printer->Print(variables_,
- "inline $type$* $classname$::add_$name$() {\n"
- " // @@protoc_insertion_point(field_add:$full_name$)\n"
- "$type_reference_function$"
- " return $name$_.Add();\n"
- "}\n");
- }
+ printer->Print(variables_,
+ "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"
diff --git a/src/google/protobuf/compiler/cpp/cpp_message_field.h b/src/google/protobuf/compiler/cpp/cpp_message_field.h
index e165404f..6879539c 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_message_field.h
@@ -38,18 +38,17 @@
#include <map>
#include <string>
#include <google/protobuf/compiler/cpp/cpp_field.h>
+#include <google/protobuf/compiler/cpp/cpp_helpers.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
-bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options);
-
class MessageFieldGenerator : public FieldGenerator {
public:
MessageFieldGenerator(const FieldDescriptor* descriptor,
- const Options& options);
+ const Options& options, SCCAnalyzer* scc_analyzer);
~MessageFieldGenerator();
// implements FieldGenerator ---------------------------------------
@@ -81,7 +80,7 @@ class MessageFieldGenerator : public FieldGenerator {
class MessageOneofFieldGenerator : public MessageFieldGenerator {
public:
MessageOneofFieldGenerator(const FieldDescriptor* descriptor,
- const Options& options);
+ const Options& options, SCCAnalyzer* scc_analyzer);
~MessageOneofFieldGenerator();
// implements FieldGenerator ---------------------------------------
@@ -97,21 +96,19 @@ class MessageOneofFieldGenerator : public MessageFieldGenerator {
void GenerateConstructorCode(io::Printer* printer) const;
private:
- const bool dependent_base_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageOneofFieldGenerator);
};
class RepeatedMessageFieldGenerator : public FieldGenerator {
public:
RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor,
- const Options& options);
+ const Options& options,
+ SCCAnalyzer* scc_analyzer);
~RepeatedMessageFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
- void GenerateDependentAccessorDeclarations(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
- void GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
@@ -124,11 +121,7 @@ class RepeatedMessageFieldGenerator : public FieldGenerator {
void GenerateByteSize(io::Printer* printer) const;
private:
- void InternalGenerateTypeDependentAccessorDeclarations(
- io::Printer* printer) const;
-
const FieldDescriptor* descriptor_;
- const bool dependent_field_;
const bool implicit_weak_field_;
std::map<string, string> variables_;
diff --git a/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc
index f72a7d60..eb7cd1c7 100644
--- a/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc
@@ -34,7 +34,7 @@
#include <gtest/gtest.h>
#if LANG_CXX11
-#include <google/protobuf/stubs/type_traits.h>
+#include <type_traits>
#endif
namespace google {
diff --git a/src/google/protobuf/compiler/cpp/cpp_options.h b/src/google/protobuf/compiler/cpp/cpp_options.h
index b0dd8836..f09885be 100644
--- a/src/google/protobuf/compiler/cpp/cpp_options.h
+++ b/src/google/protobuf/compiler/cpp/cpp_options.h
@@ -54,6 +54,7 @@ struct Options {
table_driven_parsing(false),
table_driven_serialization(false),
lite_implicit_weak_fields(false),
+ bootstrap(false),
num_cc_files(0),
access_info_map(NULL) {}
@@ -66,6 +67,7 @@ struct Options {
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;
diff --git a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h b/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h
index 9641ba40..42a3b5cd 100644
--- a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h
+++ b/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h
@@ -50,10 +50,10 @@ namespace cpp {
class PaddingOptimizer : public MessageLayoutHelper {
public:
PaddingOptimizer() {}
- ~PaddingOptimizer() {}
+ ~PaddingOptimizer() override {}
void OptimizeLayout(std::vector<const FieldDescriptor*>* fields,
- const Options& options);
+ const Options& options) override;
};
} // namespace cpp
diff --git a/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc
index ceb2270e..ff6ba0f8 100644
--- a/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc
@@ -35,9 +35,6 @@
// worth.
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/compiler/cpp/cpp_generator.h>
#include <google/protobuf/compiler/command_line_interface.h>
@@ -172,7 +169,7 @@ class TestGenerator : public CodeGenerator {
void TryInsert(const string& filename, const string& insertion_point,
GeneratorContext* context) const {
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
context->OpenForInsert(filename, insertion_point));
io::Printer printer(output.get(), '$');
printer.Print("// inserted $name$\n", "name", insertion_point);
diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.cc b/src/google/protobuf/compiler/cpp/cpp_string_field.cc
index c9901e84..cf6c4b33 100644
--- a/src/google/protobuf/compiler/cpp/cpp_string_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_string_field.cc
@@ -34,8 +34,8 @@
#include <google/protobuf/compiler/cpp/cpp_string_field.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
-#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
@@ -53,7 +53,7 @@ void SetStringVariables(const FieldDescriptor* descriptor,
(*variables)["default"] = DefaultValue(descriptor);
(*variables)["default_length"] =
SimpleItoa(descriptor->default_value_string().length());
- string default_variable_string = "_default_" + FieldName(descriptor) + "_";
+ string default_variable_string = MakeDefaultName(descriptor);
(*variables)["default_variable_name"] = default_variable_string;
(*variables)["default_variable"] =
descriptor->default_value_string().empty()
@@ -82,8 +82,24 @@ void SetStringVariables(const FieldDescriptor* descriptor,
StringFieldGenerator::StringFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
- : FieldGenerator(options), descriptor_(descriptor),
- lite_(!HasDescriptorMethods(descriptor->file(), options)) {
+ : FieldGenerator(options),
+ descriptor_(descriptor),
+ lite_(!HasDescriptorMethods(descriptor->file(), options)),
+ inlined_(false) {
+
+ // TODO(ckennelly): Handle inlining for any.proto.
+ if (IsAnyMessage(descriptor_->containing_type())) {
+ inlined_ = false;
+ }
+ if (descriptor_->containing_type()->options().map_entry()) {
+ inlined_ = false;
+ }
+
+ // Limit to proto2, as we rely on has bits to distinguish field presence for
+ // release_$name$. On proto3, we cannot use the address of the string
+ // instance when the field has been inlined.
+ inlined_ = inlined_ && HasFieldPresence(descriptor_->file());
+
SetStringVariables(descriptor, &variables_, options);
}
@@ -91,27 +107,36 @@ StringFieldGenerator::~StringFieldGenerator() {}
void StringFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
- // N.B. that we continue to use |ArenaStringPtr| instead of |string*| for
- // string fields, even when SupportArenas(descriptor_) == false. Why?
- // The simple answer is to avoid unmaintainable complexity. The reflection
- // code assumes ArenaStringPtrs. These are *almost* in-memory-compatible with
- // string*, except for the pointer tags and related ownership semantics. We
- // could modify the runtime code to use string* for the not-supporting-arenas
- // case, but this would require a way to detect which type of class was
- // generated (adding overhead and complexity to GeneratedMessageReflection)
- // and littering the runtime code paths with 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");
+ if (inlined_) {
+ printer->Print(variables_,
+ "::google::protobuf::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
+ // simple answer is to avoid unmaintainable complexity. The reflection code
+ // assumes ArenaStringPtrs. These are *almost* in-memory-compatible with
+ // string*, except for the pointer tags and related ownership semantics. We
+ // could modify the runtime code to use string* for the
+ // not-supporting-arenas case, but this would require a way to detect which
+ // type of class was generated (adding overhead and complexity to
+ // GeneratedMessageReflection) and littering the runtime code paths with
+ // 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");
+ }
}
void StringFieldGenerator::
GenerateStaticMembers(io::Printer* printer) const {
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");
+ " $default_variable_name$;\n"
+ "private:\n");
}
}
@@ -246,9 +271,23 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" return $name$_.Mutable($default_variable$, GetArenaNoVirtual());\n"
"}\n"
"inline ::std::string* $classname$::$release_name$() {\n"
- " // @@protoc_insertion_point(field_release:$full_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");
+ } else {
+ printer->Print(variables_,
" $clear_hasbit$\n"
- " return $name$_.Release($default_variable$, GetArenaNoVirtual());\n"
+ " return $name$_.Release($default_variable$, GetArenaNoVirtual());\n");
+ }
+
+ printer->Print(variables_,
"}\n"
"inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if ($name$ != NULL) {\n"
@@ -322,9 +361,22 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" return $name$_.MutableNoArena($default_variable$);\n"
"}\n"
"inline ::std::string* $classname$::$release_name$() {\n"
- " // @@protoc_insertion_point(field_release:$full_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$_.ReleaseNoArena($default_variable$);\n"
+ " return $name$_.ReleaseNonDefaultNoArena($default_variable$);\n");
+ } else {
+ printer->Print(variables_,
+ " $clear_hasbit$\n"
+ " return $name$_.ReleaseNoArena($default_variable$);\n");
+ }
+
+ printer->Print(variables_,
"}\n"
"inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if ($name$ != NULL) {\n"
@@ -343,7 +395,7 @@ GenerateNonInlineAccessorDefinitions(io::Printer* printer) const {
if (!descriptor_->default_value_string().empty()) {
// Initialized in GenerateDefaultInstanceAllocator.
printer->Print(variables_,
- "::google::protobuf::internal::ExplicitlyConstructed< ::std::string> "
+ "::google::protobuf::internal::ExplicitlyConstructed<::std::string> "
"$classname$::$default_variable_name$;\n");
}
}
@@ -383,18 +435,34 @@ GenerateMessageClearingCode(io::Printer* printer) const {
// If we have field presence, then the Clear() method of the protocol buffer
// will have checked that this field is set. If so, we can avoid redundant
// checks against default_variable.
- const bool must_be_present = HasFieldPresence(descriptor_->file());
-
- if (must_be_present) {
+ const bool must_be_present =
+ HasFieldPresence(descriptor_->file());
+
+ if (inlined_ && must_be_present) {
+ // Calling mutable_$name$() gives us a string reference and sets the has bit
+ // for $name$ (in proto2). We may get here when the string field is inlined
+ // but the string's contents have not been changed by the user, so we cannot
+ // make an assertion about the contents of the string and could never make
+ // an assertion about the string instance.
+ //
+ // 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");
}
if (SupportsArenas(descriptor_)) {
if (descriptor_->default_value_string().empty()) {
- printer->Print(variables_,
- "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n");
+ if (must_be_present) {
+ printer->Print(variables_,
+ "$name$_.ClearNonDefaultToEmpty();\n");
+ } else {
+ printer->Print(variables_,
+ "$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");
}
@@ -402,7 +470,7 @@ GenerateMessageClearingCode(io::Printer* printer) const {
// 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$_.UnsafeMutablePointer()->clear();\n");
+ printer->Print(variables_, "$name$_.ClearNonDefaultToEmptyNoArena();\n");
} else {
printer->Print(
variables_,
@@ -433,13 +501,29 @@ GenerateMergingCode(io::Printer* printer) const {
void StringFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.Swap(&other->$name$_);\n");
+ if (inlined_) {
+ printer->Print(
+ variables_,
+ "$name$_.Swap(&other->$name$_);\n");
+ } else {
+ printer->Print(
+ variables_,
+ "$name$_.Swap(&other->$name$_, $default_variable$,\n"
+ " GetArenaNoVirtual());\n");
+ }
}
void StringFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
+ // TODO(ckennelly): Construct non-empty strings as part of the initializer
+ // list.
+ if (inlined_ && descriptor_->default_value_string().empty()) {
+ // Automatic initialization will construct the string.
+ return;
+ }
+
printer->Print(variables_,
- "$name$_.UnsafeSetDefault($default_variable$);\n");
+ "$name$_.UnsafeSetDefault($default_variable$);\n");
}
void StringFieldGenerator::
@@ -472,8 +556,23 @@ GenerateCopyConstructorCode(io::Printer* printer) const {
void StringFieldGenerator::
GenerateDestructorCode(io::Printer* printer) const {
+ if (inlined_) {
+ // The destructor is automatically invoked.
+ return;
+ }
+
+ printer->Print(variables_, "$name$_.DestroyNoArena($default_variable$);\n");
+}
+
+bool StringFieldGenerator::GenerateArenaDestructorCode(
+ io::Printer* printer) const {
+ if (!inlined_) {
+ return false;
+ }
+
printer->Print(variables_,
- "$name$_.DestroyNoArena($default_variable$);\n");
+ "_this->$name$_.DestroyNoArena($default_variable$);\n");
+ return true;
}
void StringFieldGenerator::
@@ -544,13 +643,17 @@ GenerateByteSize(io::Printer* printer) const {
" this->$name$());\n");
}
+uint32 StringFieldGenerator::CalculateFieldTag() const {
+ return inlined_ ? 1 : 0;
+}
+
// ===================================================================
-StringOneofFieldGenerator::
-StringOneofFieldGenerator(const FieldDescriptor* descriptor,
- const Options& options)
- : StringFieldGenerator(descriptor, options),
- dependent_field_(options.proto_h) {
+StringOneofFieldGenerator::StringOneofFieldGenerator(
+ const FieldDescriptor* descriptor, const Options& options)
+ : StringFieldGenerator(descriptor, options) {
+ inlined_ = false;
+
SetCommonOneofFieldVariables(descriptor, &variables_);
}
diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.h b/src/google/protobuf/compiler/cpp/cpp_string_field.h
index 0c6e9ced..6cbf722f 100644
--- a/src/google/protobuf/compiler/cpp/cpp_string_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_string_field.h
@@ -63,11 +63,14 @@ class StringFieldGenerator : public FieldGenerator {
void GenerateConstructorCode(io::Printer* printer) const;
void GenerateCopyConstructorCode(io::Printer* printer) const;
void GenerateDestructorCode(io::Printer* printer) const;
+ bool GenerateArenaDestructorCode(io::Printer* printer) const;
void GenerateDefaultInstanceAllocator(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
void GenerateByteSize(io::Printer* printer) const;
+ uint32 CalculateFieldTag() const;
+ bool IsInlined() const { return inlined_; }
bool MergeFromCodedStreamNeedsArena() const;
@@ -75,6 +78,7 @@ class StringFieldGenerator : public FieldGenerator {
const FieldDescriptor* descriptor_;
std::map<string, string> variables_;
const bool lite_;
+ bool inlined_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringFieldGenerator);
@@ -99,7 +103,6 @@ class StringOneofFieldGenerator : public StringFieldGenerator {
void GenerateMergeFromCodedStream(io::Printer* printer) const;
private:
- const bool dependent_field_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringOneofFieldGenerator);
};
diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_unittest.cc
index 2ad7ea4e..22b759a9 100644
--- a/src/google/protobuf/compiler/cpp/cpp_unittest.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_unittest.cc
@@ -46,40 +46,26 @@
#include <google/protobuf/compiler/cpp/cpp_unittest.h>
-#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
-#include <vector>
-
#include <google/protobuf/unittest.pb.h>
-#include <google/protobuf/unittest_no_arena.pb.h>
#include <google/protobuf/unittest_optimize_for.pb.h>
#include <google/protobuf/unittest_embed_optimize_for.pb.h>
-#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER)
-// We exclude this large proto from cmake build because it's too large for
-// visual studio to compile (report internal errors).
-#include <google/protobuf/unittest_enormous_descriptor.pb.h>
-#endif
-#include <google/protobuf/unittest_no_generic_services.pb.h>
+
#include <google/protobuf/test_util.h>
-#include <google/protobuf/compiler/cpp/cpp_helpers.h>
-#include <google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.h>
-#include <google/protobuf/compiler/importer.h>
-#include <google/protobuf/io/coded_stream.h>
-#include <google/protobuf/io/zero_copy_stream_impl.h>
-#include <google/protobuf/arena.h>
-#include <google/protobuf/descriptor.h>
-#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/dynamic_message.h>
-#include <google/protobuf/stubs/callback.h>
-#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/substitute.h>
-#include <google/protobuf/testing/googletest.h>
-#include <gtest/gtest.h>
-#include <google/protobuf/stubs/stl_util.h>
+#define MESSAGE_TEST_NAME MessageTest
+#define GENERATED_DESCRIPTOR_TEST_NAME GeneratedDescriptorTest
+#define GENERATED_MESSAGE_TEST_NAME GeneratedMessageTest
+#define GENERATED_ENUM_TEST_NAME GeneratedEnumTest
+#define GENERATED_SERVICE_TEST_NAME GeneratedServiceTest
+#define HELPERS_TEST_NAME HelpersTest
+#define DESCRIPTOR_INIT_TEST_NAME DescriptorInitializationTest
+
+#define UNITTEST_PROTO_PATH "google/protobuf/unittest.proto"
+#define UNITTEST ::protobuf_unittest
+#define UNITTEST_IMPORT ::protobuf_unittest_import
+
+// Must include after the above macros.
+#include <google/protobuf/compiler/cpp/cpp_unittest.inc>
namespace google {
namespace protobuf {
@@ -91,848 +77,14 @@ namespace cpp_unittest {
namespace protobuf_unittest = ::protobuf_unittest;
-
-class MockErrorCollector : public MultiFileErrorCollector {
- public:
- MockErrorCollector() {}
- ~MockErrorCollector() {}
-
- string text_;
-
- // implements ErrorCollector ---------------------------------------
- void AddError(const string& filename, int line, int column,
- const string& message) {
- strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
- filename, line, column, message);
- }
-};
-
-#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
-
-// Test that generated code has proper descriptors:
-// Parse a descriptor directly (using google::protobuf::compiler::Importer) and
-// compare it to the one that was produced by generated code.
-TEST(GeneratedDescriptorTest, IdenticalDescriptors) {
- const FileDescriptor* generated_descriptor =
- unittest::TestAllTypes::descriptor()->file();
-
- // Set up the Importer.
- MockErrorCollector error_collector;
- DiskSourceTree source_tree;
- source_tree.MapPath("", TestSourceDir());
- Importer importer(&source_tree, &error_collector);
-
- // Import (parse) unittest.proto.
- const FileDescriptor* parsed_descriptor =
- importer.Import("google/protobuf/unittest.proto");
- EXPECT_EQ("", error_collector.text_);
- ASSERT_TRUE(parsed_descriptor != NULL);
-
- // Test that descriptors are generated correctly by converting them to
- // FileDescriptorProtos and comparing.
- FileDescriptorProto generated_descriptor_proto, parsed_descriptor_proto;
- generated_descriptor->CopyTo(&generated_descriptor_proto);
- parsed_descriptor->CopyTo(&parsed_descriptor_proto);
-
- EXPECT_EQ(parsed_descriptor_proto.DebugString(),
- generated_descriptor_proto.DebugString());
-}
-
-#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER)
-// Test that generated code has proper descriptors:
-// Touch a descriptor generated from an enormous message to validate special
-// handling for descriptors exceeding the C++ standard's recommended minimum
-// limit for string literal size
-TEST(GeneratedDescriptorTest, EnormousDescriptor) {
- const Descriptor* generated_descriptor =
- TestEnormousDescriptor::descriptor();
-
- EXPECT_TRUE(generated_descriptor != NULL);
-}
-#endif
-
-#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
-
-// ===================================================================
-
-TEST(GeneratedMessageTest, Defaults) {
- // Check that all default values are set correctly in the initial message.
- unittest::TestAllTypes message;
-
- TestUtil::ExpectClear(message);
-
- // Messages should return pointers to default instances until first use.
- // (This is not checked by ExpectClear() since it is not actually true after
- // the fields have been set and then cleared.)
- EXPECT_EQ(&unittest::TestAllTypes::OptionalGroup::default_instance(),
- &message.optionalgroup());
- EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(),
- &message.optional_nested_message());
- EXPECT_EQ(&unittest::ForeignMessage::default_instance(),
- &message.optional_foreign_message());
- EXPECT_EQ(&unittest_import::ImportMessage::default_instance(),
- &message.optional_import_message());
-}
-
-#ifndef PROTOBUF_USE_DLLS
-TEST(GeneratedMessageTest, Int32StringConversion) {
- EXPECT_EQ("971", Int32ToString(971));
- EXPECT_EQ("(~0x7fffffff)", Int32ToString(kint32min));
- EXPECT_EQ("2147483647", Int32ToString(kint32max));
-}
-
-TEST(GeneratedMessageTest, 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(GeneratedMessageTest, FloatingPointDefaults) {
- const unittest::TestExtremeDefaultValues& extreme_default =
- unittest::TestExtremeDefaultValues::default_instance();
-
- EXPECT_EQ(0.0f, extreme_default.zero_float());
- EXPECT_EQ(1.0f, extreme_default.one_float());
- EXPECT_EQ(1.5f, extreme_default.small_float());
- EXPECT_EQ(-1.0f, extreme_default.negative_one_float());
- EXPECT_EQ(-1.5f, extreme_default.negative_float());
- EXPECT_EQ(2.0e8f, extreme_default.large_float());
- EXPECT_EQ(-8e-28f, extreme_default.small_negative_float());
- EXPECT_EQ(std::numeric_limits<double>::infinity(),
- extreme_default.inf_double());
- EXPECT_EQ(-std::numeric_limits<double>::infinity(),
- extreme_default.neg_inf_double());
- EXPECT_TRUE(extreme_default.nan_double() != extreme_default.nan_double());
- EXPECT_EQ(std::numeric_limits<float>::infinity(),
- extreme_default.inf_float());
- EXPECT_EQ(-std::numeric_limits<float>::infinity(),
- extreme_default.neg_inf_float());
- EXPECT_TRUE(extreme_default.nan_float() != extreme_default.nan_float());
-}
-
-TEST(GeneratedMessageTest, Trigraph) {
- const unittest::TestExtremeDefaultValues& extreme_default =
- unittest::TestExtremeDefaultValues::default_instance();
-
- EXPECT_EQ("? ? ?? ?? ??? ?\?/ ?\?-", extreme_default.cpp_trigraph());
-}
-
-TEST(GeneratedMessageTest, ExtremeSmallIntegerDefault) {
- const unittest::TestExtremeDefaultValues& extreme_default =
- unittest::TestExtremeDefaultValues::default_instance();
- EXPECT_EQ(~0x7fffffff, kint32min);
- EXPECT_EQ(GOOGLE_LONGLONG(~0x7fffffffffffffff), kint64min);
- EXPECT_EQ(kint32min, extreme_default.really_small_int32());
- EXPECT_EQ(kint64min, extreme_default.really_small_int64());
-}
-
-TEST(GeneratedMessageTest, Accessors) {
- // Set every field to a unique value then go back and check all those
- // values.
- unittest::TestAllTypes message;
-
- TestUtil::SetAllFields(&message);
- TestUtil::ExpectAllFieldsSet(message);
-
- TestUtil::ModifyRepeatedFields(&message);
- TestUtil::ExpectRepeatedFieldsModified(message);
-}
-
-TEST(GeneratedMessageTest, MutableStringDefault) {
- // mutable_foo() for a string should return a string initialized to its
- // default value.
- unittest::TestAllTypes message;
-
- EXPECT_EQ("hello", *message.mutable_default_string());
-
- // Note that the first time we call mutable_foo(), we get a newly-allocated
- // string, but if we clear it and call it again, we get the same object again.
- // We should verify that it has its default value in both cases.
- message.set_default_string("blah");
- message.Clear();
-
- EXPECT_EQ("hello", *message.mutable_default_string());
-}
-
-TEST(GeneratedMessageTest, StringDefaults) {
- unittest::TestExtremeDefaultValues message;
- // Check if '\000' can be used in default string value.
- EXPECT_EQ(string("hel\000lo", 6), message.string_with_zero());
- EXPECT_EQ(string("wor\000ld", 6), message.bytes_with_zero());
-}
-
-TEST(GeneratedMessageTest, ReleaseString) {
- // Check that release_foo() starts out NULL, and gives us a value
- // that we can delete after it's been set.
- unittest::TestAllTypes message;
-
- EXPECT_EQ(NULL, message.release_default_string());
- EXPECT_FALSE(message.has_default_string());
- EXPECT_EQ("hello", message.default_string());
-
- message.set_default_string("blah");
- EXPECT_TRUE(message.has_default_string());
- google::protobuf::scoped_ptr<string> str(message.release_default_string());
- EXPECT_FALSE(message.has_default_string());
- ASSERT_TRUE(str != NULL);
- EXPECT_EQ("blah", *str);
-
- EXPECT_EQ(NULL, message.release_default_string());
- EXPECT_FALSE(message.has_default_string());
- EXPECT_EQ("hello", message.default_string());
-}
-
-TEST(GeneratedMessageTest, ReleaseMessage) {
- // Check that release_foo() starts out NULL, and gives us a value
- // that we can delete after it's been set.
- unittest::TestAllTypes message;
-
- EXPECT_EQ(NULL, message.release_optional_nested_message());
- EXPECT_FALSE(message.has_optional_nested_message());
-
- message.mutable_optional_nested_message()->set_bb(1);
- google::protobuf::scoped_ptr<unittest::TestAllTypes::NestedMessage> nest(
- message.release_optional_nested_message());
- EXPECT_FALSE(message.has_optional_nested_message());
- ASSERT_TRUE(nest != NULL);
- EXPECT_EQ(1, nest->bb());
-
- EXPECT_EQ(NULL, message.release_optional_nested_message());
- EXPECT_FALSE(message.has_optional_nested_message());
-}
-
-TEST(GeneratedMessageTest, SetAllocatedString) {
- // Check that set_allocated_foo() works for strings.
- unittest::TestAllTypes message;
-
- EXPECT_FALSE(message.has_optional_string());
- const string kHello("hello");
- message.set_optional_string(kHello);
- EXPECT_TRUE(message.has_optional_string());
-
- message.set_allocated_optional_string(NULL);
- EXPECT_FALSE(message.has_optional_string());
- EXPECT_EQ("", message.optional_string());
-
- message.set_allocated_optional_string(new string(kHello));
- EXPECT_TRUE(message.has_optional_string());
- EXPECT_EQ(kHello, message.optional_string());
-}
-
-TEST(GeneratedMessageTest, SetAllocatedMessage) {
- // Check that set_allocated_foo() can be called in all cases.
- unittest::TestAllTypes message;
-
- EXPECT_FALSE(message.has_optional_nested_message());
-
- message.mutable_optional_nested_message()->set_bb(1);
- EXPECT_TRUE(message.has_optional_nested_message());
-
- message.set_allocated_optional_nested_message(NULL);
- EXPECT_FALSE(message.has_optional_nested_message());
- EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(),
- &message.optional_nested_message());
-
- message.mutable_optional_nested_message()->set_bb(1);
- unittest::TestAllTypes::NestedMessage* nest =
- message.release_optional_nested_message();
- ASSERT_TRUE(nest != NULL);
- EXPECT_FALSE(message.has_optional_nested_message());
-
- message.set_allocated_optional_nested_message(nest);
- EXPECT_TRUE(message.has_optional_nested_message());
- EXPECT_EQ(1, message.optional_nested_message().bb());
-}
-
-TEST(GeneratedMessageTest, Clear) {
- // Set every field to a unique value, clear the message, then check that
- // it is cleared.
- unittest::TestAllTypes message;
-
- TestUtil::SetAllFields(&message);
- message.Clear();
- TestUtil::ExpectClear(message);
-
- // Unlike with the defaults test, we do NOT expect that requesting embedded
- // messages will return a pointer to the default instance. Instead, they
- // should return the objects that were created when mutable_blah() was
- // called.
- EXPECT_NE(&unittest::TestAllTypes::OptionalGroup::default_instance(),
- &message.optionalgroup());
- EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(),
- &message.optional_nested_message());
- EXPECT_NE(&unittest::ForeignMessage::default_instance(),
- &message.optional_foreign_message());
- EXPECT_NE(&unittest_import::ImportMessage::default_instance(),
- &message.optional_import_message());
-}
-
-TEST(GeneratedMessageTest, EmbeddedNullsInBytesCharStar) {
- unittest::TestAllTypes message;
-
- const char* value = "\0lalala\0\0";
- message.set_optional_bytes(value, 9);
- ASSERT_EQ(9, message.optional_bytes().size());
- EXPECT_EQ(0, memcmp(value, message.optional_bytes().data(), 9));
-
- message.add_repeated_bytes(value, 9);
- ASSERT_EQ(9, message.repeated_bytes(0).size());
- EXPECT_EQ(0, memcmp(value, message.repeated_bytes(0).data(), 9));
-}
-
-TEST(GeneratedMessageTest, ClearOneField) {
- // Set every field to a unique value, then clear one value and insure that
- // only that one value is cleared.
- unittest::TestAllTypes message;
-
- TestUtil::SetAllFields(&message);
- int64 original_value = message.optional_int64();
-
- // Clear the field and make sure it shows up as cleared.
- message.clear_optional_int64();
- EXPECT_FALSE(message.has_optional_int64());
- EXPECT_EQ(0, message.optional_int64());
-
- // Other adjacent fields should not be cleared.
- EXPECT_TRUE(message.has_optional_int32());
- EXPECT_TRUE(message.has_optional_uint32());
-
- // Make sure if we set it again, then all fields are set.
- message.set_optional_int64(original_value);
- TestUtil::ExpectAllFieldsSet(message);
-}
-
-TEST(GeneratedMessageTest, StringCharStarLength) {
- // Verify that we can use a char*,length to set one of the string fields.
- unittest::TestAllTypes message;
- message.set_optional_string("abcdef", 3);
- EXPECT_EQ("abc", message.optional_string());
-
- // Verify that we can use a char*,length to add to a repeated string field.
- message.add_repeated_string("abcdef", 3);
- EXPECT_EQ(1, message.repeated_string_size());
- EXPECT_EQ("abc", message.repeated_string(0));
-
- // Verify that we can use a char*,length to set a repeated string field.
- message.set_repeated_string(0, "wxyz", 2);
- EXPECT_EQ("wx", message.repeated_string(0));
-}
-
-#if LANG_CXX11
-TEST(GeneratedMessageTest, StringMove) {
- // Verify that we trigger the move behavior on a scalar setter.
- protobuf_unittest_no_arena::TestAllTypes message;
- {
- string tmp(32, 'a');
-
- const char* old_data = tmp.data();
- message.set_optional_string(std::move(tmp));
- const char* new_data = message.optional_string().data();
-
- EXPECT_EQ(old_data, new_data);
- EXPECT_EQ(string(32, 'a'), message.optional_string());
-
- string tmp2(32, 'b');
- old_data = tmp2.data();
- message.set_optional_string(std::move(tmp2));
- new_data = message.optional_string().data();
-
- EXPECT_EQ(old_data, new_data);
- EXPECT_EQ(string(32, 'b'), message.optional_string());
- }
-
- // Verify that we trigger the move behavior on a oneof setter.
- {
- string tmp(32, 'a');
-
- const char* old_data = tmp.data();
- message.set_oneof_string(std::move(tmp));
- const char* new_data = message.oneof_string().data();
-
- EXPECT_EQ(old_data, new_data);
- EXPECT_EQ(string(32, 'a'), message.oneof_string());
-
- string tmp2(32, 'b');
- old_data = tmp2.data();
- message.set_oneof_string(std::move(tmp2));
- new_data = message.oneof_string().data();
-
- EXPECT_EQ(old_data, new_data);
- EXPECT_EQ(string(32, 'b'), message.oneof_string());
- }
-
- // Verify that we trigger the move behavior on a repeated setter.
- {
- string tmp(32, 'a');
-
- const char* old_data = tmp.data();
- message.add_repeated_string(std::move(tmp));
- const char* new_data = message.repeated_string(0).data();
-
- EXPECT_EQ(old_data, new_data);
- EXPECT_EQ(string(32, 'a'), message.repeated_string(0));
-
- string tmp2(32, 'b');
- old_data = tmp2.data();
- message.set_repeated_string(0, std::move(tmp2));
- new_data = message.repeated_string(0).data();
-
- EXPECT_EQ(old_data, new_data);
- EXPECT_EQ(string(32, 'b'), message.repeated_string(0));
- }
-}
-#endif
-
-
-TEST(GeneratedMessageTest, CopyFrom) {
- unittest::TestAllTypes message1, message2;
-
- TestUtil::SetAllFields(&message1);
- message2.CopyFrom(message1);
- TestUtil::ExpectAllFieldsSet(message2);
-
- // Copying from self should be a no-op.
- message2.CopyFrom(message2);
- TestUtil::ExpectAllFieldsSet(message2);
-}
-
-
-TEST(GeneratedMessageTest, SwapWithEmpty) {
- unittest::TestAllTypes message1, message2;
- TestUtil::SetAllFields(&message1);
-
- TestUtil::ExpectAllFieldsSet(message1);
- TestUtil::ExpectClear(message2);
- message1.Swap(&message2);
- TestUtil::ExpectAllFieldsSet(message2);
- TestUtil::ExpectClear(message1);
-}
-
-TEST(GeneratedMessageTest, SwapWithSelf) {
- unittest::TestAllTypes message;
- TestUtil::SetAllFields(&message);
- TestUtil::ExpectAllFieldsSet(message);
- message.Swap(&message);
- TestUtil::ExpectAllFieldsSet(message);
-}
-
-TEST(GeneratedMessageTest, SwapWithOther) {
- unittest::TestAllTypes message1, message2;
-
- message1.set_optional_int32(123);
- message1.set_optional_string("abc");
- message1.mutable_optional_nested_message()->set_bb(1);
- message1.set_optional_nested_enum(unittest::TestAllTypes::FOO);
- message1.add_repeated_int32(1);
- message1.add_repeated_int32(2);
- message1.add_repeated_string("a");
- message1.add_repeated_string("b");
- message1.add_repeated_nested_message()->set_bb(7);
- message1.add_repeated_nested_message()->set_bb(8);
- message1.add_repeated_nested_enum(unittest::TestAllTypes::FOO);
- message1.add_repeated_nested_enum(unittest::TestAllTypes::BAR);
-
- message2.set_optional_int32(456);
- message2.set_optional_string("def");
- message2.mutable_optional_nested_message()->set_bb(2);
- message2.set_optional_nested_enum(unittest::TestAllTypes::BAR);
- message2.add_repeated_int32(3);
- message2.add_repeated_string("c");
- message2.add_repeated_nested_message()->set_bb(9);
- message2.add_repeated_nested_enum(unittest::TestAllTypes::BAZ);
-
- message1.Swap(&message2);
-
- EXPECT_EQ(456, message1.optional_int32());
- EXPECT_EQ("def", message1.optional_string());
- EXPECT_EQ(2, message1.optional_nested_message().bb());
- EXPECT_EQ(unittest::TestAllTypes::BAR, message1.optional_nested_enum());
- ASSERT_EQ(1, message1.repeated_int32_size());
- EXPECT_EQ(3, message1.repeated_int32(0));
- ASSERT_EQ(1, message1.repeated_string_size());
- EXPECT_EQ("c", message1.repeated_string(0));
- ASSERT_EQ(1, message1.repeated_nested_message_size());
- EXPECT_EQ(9, message1.repeated_nested_message(0).bb());
- ASSERT_EQ(1, message1.repeated_nested_enum_size());
- EXPECT_EQ(unittest::TestAllTypes::BAZ, message1.repeated_nested_enum(0));
-
- EXPECT_EQ(123, message2.optional_int32());
- EXPECT_EQ("abc", message2.optional_string());
- EXPECT_EQ(1, message2.optional_nested_message().bb());
- EXPECT_EQ(unittest::TestAllTypes::FOO, message2.optional_nested_enum());
- ASSERT_EQ(2, message2.repeated_int32_size());
- EXPECT_EQ(1, message2.repeated_int32(0));
- EXPECT_EQ(2, message2.repeated_int32(1));
- ASSERT_EQ(2, message2.repeated_string_size());
- EXPECT_EQ("a", message2.repeated_string(0));
- EXPECT_EQ("b", message2.repeated_string(1));
- ASSERT_EQ(2, message2.repeated_nested_message_size());
- EXPECT_EQ(7, message2.repeated_nested_message(0).bb());
- EXPECT_EQ(8, message2.repeated_nested_message(1).bb());
- ASSERT_EQ(2, message2.repeated_nested_enum_size());
- EXPECT_EQ(unittest::TestAllTypes::FOO, message2.repeated_nested_enum(0));
- EXPECT_EQ(unittest::TestAllTypes::BAR, message2.repeated_nested_enum(1));
-}
-
-TEST(GeneratedMessageTest, ADLSwap) {
- unittest::TestAllTypes message1, message2;
- TestUtil::SetAllFields(&message1);
-
- // Note the address of one of the repeated fields, to verify it was swapped
- // rather than copied.
- const int32* addr = &message1.repeated_int32().Get(0);
-
- using std::swap;
- swap(message1, message2);
-
- TestUtil::ExpectAllFieldsSet(message2);
- TestUtil::ExpectClear(message1);
-
- EXPECT_EQ(addr, &message2.repeated_int32().Get(0));
-}
-
-TEST(GeneratedMessageTest, CopyConstructor) {
- // All set.
- {
- unittest::TestAllTypes message1;
- TestUtil::SetAllFields(&message1);
-
- unittest::TestAllTypes message2(message1);
- TestUtil::ExpectAllFieldsSet(message2);
- }
-
- // None set.
- {
- unittest::TestAllTypes message1;
- unittest::TestAllTypes message2(message1);
-
- EXPECT_FALSE(message1.has_optional_string());
- EXPECT_FALSE(message2.has_optional_string());
- EXPECT_EQ(&message1.optional_string(),
- &message2.optional_string());
-
- EXPECT_FALSE(message1.has_optional_bytes());
- EXPECT_FALSE(message2.has_optional_bytes());
- EXPECT_EQ(&message1.optional_bytes(),
- &message2.optional_bytes());
-
- EXPECT_FALSE(message1.has_optional_nested_message());
- EXPECT_FALSE(message2.has_optional_nested_message());
- EXPECT_EQ(&message1.optional_nested_message(),
- &message2.optional_nested_message());
-
- EXPECT_FALSE(message1.has_optional_foreign_message());
- EXPECT_FALSE(message2.has_optional_foreign_message());
- EXPECT_EQ(&message1.optional_foreign_message(),
- &message2.optional_foreign_message());
-
- EXPECT_FALSE(message1.has_optional_import_message());
- EXPECT_FALSE(message2.has_optional_import_message());
- EXPECT_EQ(&message1.optional_import_message(),
- &message2.optional_import_message());
-
- EXPECT_FALSE(message1.has_optional_public_import_message());
- EXPECT_FALSE(message2.has_optional_public_import_message());
- EXPECT_EQ(&message1.optional_public_import_message(),
- &message2.optional_public_import_message());
-
- EXPECT_FALSE(message1.has_optional_lazy_message());
- EXPECT_FALSE(message2.has_optional_lazy_message());
- EXPECT_EQ(&message1.optional_lazy_message(),
- &message2.optional_lazy_message());
- }
-}
-
-TEST(GeneratedMessageTest, CopyConstructorWithArenas) {
- Arena arena;
- unittest::TestAllTypes* message1 =
- Arena::CreateMessage<unittest::TestAllTypes>(&arena);
- TestUtil::SetAllFields(message1);
-
- unittest::TestAllTypes message2_stack(*message1);
- TestUtil::ExpectAllFieldsSet(message2_stack);
-
- google::protobuf::scoped_ptr<unittest::TestAllTypes> message2_heap(
- new unittest::TestAllTypes(*message1));
- TestUtil::ExpectAllFieldsSet(*message2_heap);
-
- arena.Reset();
-
- // Verify that the copies are still intact.
- TestUtil::ExpectAllFieldsSet(message2_stack);
- TestUtil::ExpectAllFieldsSet(*message2_heap);
-}
-
-TEST(GeneratedMessageTest, CopyAssignmentOperator) {
- unittest::TestAllTypes message1;
- TestUtil::SetAllFields(&message1);
-
- unittest::TestAllTypes message2;
- message2 = message1;
- TestUtil::ExpectAllFieldsSet(message2);
-
- // Make sure that self-assignment does something sane.
- message2.operator=(message2);
- TestUtil::ExpectAllFieldsSet(message2);
-}
-
-#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \
- !defined(GOOGLE_PROTOBUF_NO_RTTI)
-TEST(GeneratedMessageTest, UpcastCopyFrom) {
- // Test the CopyFrom method that takes in the generic const Message&
- // parameter.
- unittest::TestAllTypes message1, message2;
-
- TestUtil::SetAllFields(&message1);
-
- const Message* source = implicit_cast<const Message*>(&message1);
- message2.CopyFrom(*source);
-
- TestUtil::ExpectAllFieldsSet(message2);
-}
-#endif
-
-#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
-
-TEST(GeneratedMessageTest, DynamicMessageCopyFrom) {
- // Test copying from a DynamicMessage, which must fall back to using
- // reflection.
- unittest::TestAllTypes message2;
-
- // Construct a new version of the dynamic message via the factory.
- DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<Message> message1;
- message1.reset(factory.GetPrototype(
- unittest::TestAllTypes::descriptor())->New());
-
- TestUtil::ReflectionTester reflection_tester(
- unittest::TestAllTypes::descriptor());
- reflection_tester.SetAllFieldsViaReflection(message1.get());
-
- message2.CopyFrom(*message1);
-
- TestUtil::ExpectAllFieldsSet(message2);
-}
-
-#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
-
-TEST(GeneratedMessageTest, NonEmptyMergeFrom) {
- // Test merging with a non-empty message. Code is a modified form
- // of that found in google/protobuf/reflection_ops_unittest.cc.
- unittest::TestAllTypes message1, message2;
-
- TestUtil::SetAllFields(&message1);
-
- // This field will test merging into an empty spot.
- message2.set_optional_int32(message1.optional_int32());
- message1.clear_optional_int32();
-
- // This tests overwriting.
- message2.set_optional_string(message1.optional_string());
- message1.set_optional_string("something else");
-
- // This tests concatenating.
- message2.add_repeated_int32(message1.repeated_int32(1));
- int32 i = message1.repeated_int32(0);
- message1.clear_repeated_int32();
- message1.add_repeated_int32(i);
-
- message1.MergeFrom(message2);
-
- TestUtil::ExpectAllFieldsSet(message1);
-}
-
-
-// Test the generated SerializeWithCachedSizesToArray(),
-TEST(GeneratedMessageTest, SerializationToArray) {
- unittest::TestAllTypes message1, message2;
- string data;
- TestUtil::SetAllFields(&message1);
- int size = message1.ByteSize();
- data.resize(size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
- uint8* end = message1.SerializeWithCachedSizesToArray(start);
- EXPECT_EQ(size, end - start);
- EXPECT_TRUE(message2.ParseFromString(data));
- TestUtil::ExpectAllFieldsSet(message2);
-
-}
-
-TEST(GeneratedMessageTest, PackedFieldsSerializationToArray) {
- unittest::TestPackedTypes packed_message1, packed_message2;
- string packed_data;
- TestUtil::SetPackedFields(&packed_message1);
- int packed_size = packed_message1.ByteSize();
- packed_data.resize(packed_size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&packed_data));
- uint8* end = packed_message1.SerializeWithCachedSizesToArray(start);
- EXPECT_EQ(packed_size, end - start);
- EXPECT_TRUE(packed_message2.ParseFromString(packed_data));
- TestUtil::ExpectPackedFieldsSet(packed_message2);
-}
-
-// Test the generated SerializeWithCachedSizes() by forcing the buffer to write
-// one byte at a time.
-TEST(GeneratedMessageTest, SerializationToStream) {
- unittest::TestAllTypes message1, message2;
- TestUtil::SetAllFields(&message1);
- int size = message1.ByteSize();
- string data;
- 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::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));
- TestUtil::ExpectAllFieldsSet(message2);
-
-}
-
-TEST(GeneratedMessageTest, PackedFieldsSerializationToStream) {
- unittest::TestPackedTypes message1, message2;
- TestUtil::SetPackedFields(&message1);
- int size = message1.ByteSize();
- string data;
- 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::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));
- TestUtil::ExpectPackedFieldsSet(message2);
-}
-
-
-TEST(GeneratedMessageTest, Required) {
- // Test that IsInitialized() returns false if required fields are missing.
- unittest::TestRequired message;
-
- EXPECT_FALSE(message.IsInitialized());
- message.set_a(1);
- EXPECT_FALSE(message.IsInitialized());
- message.set_b(2);
- EXPECT_FALSE(message.IsInitialized());
- message.set_c(3);
- EXPECT_TRUE(message.IsInitialized());
-}
-
-TEST(GeneratedMessageTest, RequiredForeign) {
- // Test that IsInitialized() returns false if required fields in nested
- // messages are missing.
- unittest::TestRequiredForeign message;
-
- EXPECT_TRUE(message.IsInitialized());
-
- message.mutable_optional_message();
- EXPECT_FALSE(message.IsInitialized());
-
- message.mutable_optional_message()->set_a(1);
- message.mutable_optional_message()->set_b(2);
- message.mutable_optional_message()->set_c(3);
- EXPECT_TRUE(message.IsInitialized());
-
- message.add_repeated_message();
- EXPECT_FALSE(message.IsInitialized());
-
- message.mutable_repeated_message(0)->set_a(1);
- message.mutable_repeated_message(0)->set_b(2);
- message.mutable_repeated_message(0)->set_c(3);
- EXPECT_TRUE(message.IsInitialized());
-}
-
-TEST(GeneratedMessageTest, ForeignNested) {
- // Test that TestAllTypes::NestedMessage can be embedded directly into
- // another message.
- unittest::TestForeignNested message;
-
- // If this compiles and runs without crashing, it must work. We have
- // nothing more to test.
- unittest::TestAllTypes::NestedMessage* nested =
- message.mutable_foreign_nested();
- nested->set_bb(1);
-}
-
-TEST(GeneratedMessageTest, ReallyLargeTagNumber) {
- // Test that really large tag numbers don't break anything.
- unittest::TestReallyLargeTagNumber message1, message2;
- string data;
-
- // For the most part, if this compiles and runs then we're probably good.
- // (The most likely cause for failure would be if something were attempting
- // to allocate a lookup table of some sort using tag numbers as the index.)
- // We'll try serializing just for fun.
- message1.set_a(1234);
- message1.set_bb(5678);
- message1.SerializeToString(&data);
- EXPECT_TRUE(message2.ParseFromString(data));
- EXPECT_EQ(1234, message2.a());
- EXPECT_EQ(5678, message2.bb());
-}
-
-TEST(GeneratedMessageTest, MutualRecursion) {
- // Test that mutually-recursive message types work.
- unittest::TestMutualRecursionA message;
- unittest::TestMutualRecursionA* nested = message.mutable_bb()->mutable_a();
- unittest::TestMutualRecursionA* nested2 = nested->mutable_bb()->mutable_a();
-
- // Again, if the above compiles and runs, that's all we really have to
- // test, but just for run we'll check that the system didn't somehow come
- // up with a pointer loop...
- EXPECT_NE(&message, nested);
- EXPECT_NE(&message, nested2);
- EXPECT_NE(nested, nested2);
-}
-
-TEST(GeneratedMessageTest, CamelCaseFieldNames) {
- // This test is mainly checking that the following compiles, which verifies
- // that the field names were coerced to lower-case.
- //
- // Protocol buffers standard style is to use lowercase-with-underscores for
- // field names. Some old proto1 .protos unfortunately used camel-case field
- // names. In proto1, these names were forced to lower-case. So, we do the
- // same thing in proto2.
-
- unittest::TestCamelCaseFieldNames message;
-
- message.set_primitivefield(2);
- message.set_stringfield("foo");
- message.set_enumfield(unittest::FOREIGN_FOO);
- message.mutable_messagefield()->set_c(6);
-
- message.add_repeatedprimitivefield(8);
- message.add_repeatedstringfield("qux");
- message.add_repeatedenumfield(unittest::FOREIGN_BAR);
- message.add_repeatedmessagefield()->set_c(15);
-
- EXPECT_EQ(2, message.primitivefield());
- EXPECT_EQ("foo", message.stringfield());
- EXPECT_EQ(unittest::FOREIGN_FOO, message.enumfield());
- EXPECT_EQ(6, message.messagefield().c());
-
- EXPECT_EQ(8, message.repeatedprimitivefield(0));
- EXPECT_EQ("qux", message.repeatedstringfield(0));
- EXPECT_EQ(unittest::FOREIGN_BAR, message.repeatedenumfield(0));
- EXPECT_EQ(15, message.repeatedmessagefield(0).c());
-}
-
-TEST(GeneratedMessageTest, TestConflictingSymbolNames) {
+TEST(GENERATED_MESSAGE_TEST_NAME, TestConflictingSymbolNames) {
// test_bad_identifiers.proto successfully compiled, then it works. The
// following is just a token usage to insure that the code is, in fact,
// being compiled and linked.
protobuf_unittest::TestConflictingSymbolNames message;
message.set_uint32(1);
- EXPECT_EQ(3, message.ByteSize());
+ EXPECT_EQ(3, message.ByteSizeLong());
message.set_friend_(5);
EXPECT_EQ(5, message.friend_());
@@ -948,7 +100,7 @@ TEST(GeneratedMessageTest, TestConflictingSymbolNames) {
message.GetExtension(ExtensionMessage::repeated_int32_ext, 0));
}
-TEST(GeneratedMessageTest, TestConflictingEnumNames) {
+TEST(GENERATED_MESSAGE_TEST_NAME, TestConflictingEnumNames) {
protobuf_unittest::TestConflictingEnumNames message;
message.set_conflicting_enum(protobuf_unittest::TestConflictingEnumNames_NestedConflictingEnum_and_);
EXPECT_EQ(1, message.conflicting_enum());
@@ -963,1366 +115,7 @@ TEST(GeneratedMessageTest, TestConflictingEnumNames) {
EXPECT_EQ(3, conflicting_enum);
}
-#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
-
-TEST(GeneratedMessageTest, TestOptimizedForSize) {
- // We rely on the tests in reflection_ops_unittest and wire_format_unittest
- // to really test that reflection-based methods work. Here we are mostly
- // just making sure that TestOptimizedForSize actually builds and seems to
- // function.
-
- protobuf_unittest::TestOptimizedForSize message, message2;
- message.set_i(1);
- message.mutable_msg()->set_c(2);
- message2.CopyFrom(message);
- EXPECT_EQ(1, message2.i());
- EXPECT_EQ(2, message2.msg().c());
-}
-
-TEST(GeneratedMessageTest, TestEmbedOptimizedForSize) {
- // Verifies that something optimized for speed can contain something optimized
- // for size.
-
- protobuf_unittest::TestEmbedOptimizedForSize message, message2;
- message.mutable_optional_message()->set_i(1);
- message.add_repeated_message()->mutable_msg()->set_c(2);
- string data;
- message.SerializeToString(&data);
- ASSERT_TRUE(message2.ParseFromString(data));
- EXPECT_EQ(1, message2.optional_message().i());
- EXPECT_EQ(2, message2.repeated_message(0).msg().c());
-}
-
-TEST(GeneratedMessageTest, TestSpaceUsed) {
- unittest::TestAllTypes message1;
- // sizeof provides a lower bound on SpaceUsedLong().
- EXPECT_LE(sizeof(unittest::TestAllTypes), message1.SpaceUsedLong());
- const size_t empty_message_size = message1.SpaceUsedLong();
-
- // Setting primitive types shouldn't affect the space used.
- message1.set_optional_int32(123);
- message1.set_optional_int64(12345);
- message1.set_optional_uint32(123);
- message1.set_optional_uint64(12345);
- EXPECT_EQ(empty_message_size, message1.SpaceUsedLong());
-
- // On some STL implementations, setting the string to a small value should
- // only increase SpaceUsedLong() by the size of a string object, though this
- // is not true everywhere.
- message1.set_optional_string("abc");
- EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsedLong());
-
- // Setting a string to a value larger than the string object itself should
- // increase SpaceUsedLong(), because it cannot store the value internally.
- message1.set_optional_string(string(sizeof(string) + 1, 'x'));
- int min_expected_increase = message1.optional_string().capacity() +
- sizeof(string);
- EXPECT_LE(empty_message_size + min_expected_increase,
- message1.SpaceUsedLong());
-
- size_t previous_size = message1.SpaceUsedLong();
- // Adding an optional message should increase the size by the size of the
- // nested message type. NestedMessage is simple enough (1 int field) that it
- // is equal to sizeof(NestedMessage)
- message1.mutable_optional_nested_message();
- ASSERT_EQ(sizeof(unittest::TestAllTypes::NestedMessage),
- message1.optional_nested_message().SpaceUsedLong());
- EXPECT_EQ(previous_size +
- sizeof(unittest::TestAllTypes::NestedMessage),
- message1.SpaceUsedLong());
-}
-
-TEST(GeneratedMessageTest, TestOneofSpaceUsed) {
- unittest::TestOneof2 message1;
- EXPECT_LE(sizeof(unittest::TestOneof2), message1.SpaceUsedLong());
-
- const size_t empty_message_size = message1.SpaceUsedLong();
- // Setting primitive types shouldn't affect the space used.
- message1.set_foo_int(123);
- message1.set_bar_int(12345);
- EXPECT_EQ(empty_message_size, message1.SpaceUsedLong());
-
- // Setting a string in oneof to a small value should only increase
- // SpaceUsedLong() by the size of a string object.
- message1.set_foo_string("abc");
- EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsedLong());
-
- // Setting a string in oneof to a value larger than the string object itself
- // should increase SpaceUsedLong(), because it cannot store the value
- // internally.
- message1.set_foo_string(string(sizeof(string) + 1, 'x'));
- int min_expected_increase = message1.foo_string().capacity() +
- sizeof(string);
- EXPECT_LE(empty_message_size + min_expected_increase,
- message1.SpaceUsedLong());
-
- // Setting a message in oneof should delete the other fields and increase the
- // size by the size of the nested message type. NestedMessage is simple enough
- // that it is equal to sizeof(NestedMessage)
- message1.mutable_foo_message();
- ASSERT_EQ(sizeof(unittest::TestOneof2::NestedMessage),
- message1.foo_message().SpaceUsedLong());
- EXPECT_EQ(empty_message_size +
- sizeof(unittest::TestOneof2::NestedMessage),
- message1.SpaceUsedLong());
-}
-
-#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
-
-
-TEST(GeneratedMessageTest, FieldConstantValues) {
- unittest::TestRequired message;
- EXPECT_EQ(unittest::TestAllTypes_NestedMessage::kBbFieldNumber, 1);
- EXPECT_EQ(unittest::TestAllTypes::kOptionalInt32FieldNumber, 1);
- EXPECT_EQ(unittest::TestAllTypes::kOptionalgroupFieldNumber, 16);
- EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedMessageFieldNumber, 18);
- EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedEnumFieldNumber, 21);
- EXPECT_EQ(unittest::TestAllTypes::kRepeatedInt32FieldNumber, 31);
- EXPECT_EQ(unittest::TestAllTypes::kRepeatedgroupFieldNumber, 46);
- EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedMessageFieldNumber, 48);
- EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedEnumFieldNumber, 51);
-}
-
-TEST(GeneratedMessageTest, ExtensionConstantValues) {
- EXPECT_EQ(unittest::TestRequired::kSingleFieldNumber, 1000);
- EXPECT_EQ(unittest::TestRequired::kMultiFieldNumber, 1001);
- EXPECT_EQ(unittest::kOptionalInt32ExtensionFieldNumber, 1);
- EXPECT_EQ(unittest::kOptionalgroupExtensionFieldNumber, 16);
- EXPECT_EQ(unittest::kOptionalNestedMessageExtensionFieldNumber, 18);
- EXPECT_EQ(unittest::kOptionalNestedEnumExtensionFieldNumber, 21);
- EXPECT_EQ(unittest::kRepeatedInt32ExtensionFieldNumber, 31);
- EXPECT_EQ(unittest::kRepeatedgroupExtensionFieldNumber, 46);
- EXPECT_EQ(unittest::kRepeatedNestedMessageExtensionFieldNumber, 48);
- EXPECT_EQ(unittest::kRepeatedNestedEnumExtensionFieldNumber, 51);
-}
-
-TEST(GeneratedMessageTest, ParseFromTruncated) {
- const string long_string = string(128, 'q');
- FileDescriptorProto p;
- p.add_extension()->set_name(long_string);
- const string msg = p.SerializeAsString();
- int successful_count = 0;
- for (int i = 0; i <= msg.size(); i++) {
- if (p.ParseFromArray(msg.c_str(), i)) {
- ++successful_count;
- }
- }
- // We don't really care about how often we succeeded.
- // As long as we didn't crash, we're happy.
- EXPECT_GE(successful_count, 1);
-}
-
-// ===================================================================
-
-TEST(GeneratedEnumTest, EnumValuesAsSwitchCases) {
- // Test that our nested enum values can be used as switch cases. This test
- // doesn't actually do anything, the proof that it works is that it
- // compiles.
- int i =0;
- unittest::TestAllTypes::NestedEnum a = unittest::TestAllTypes::BAR;
- switch (a) {
- case unittest::TestAllTypes::FOO:
- i = 1;
- break;
- case unittest::TestAllTypes::BAR:
- i = 2;
- break;
- case unittest::TestAllTypes::BAZ:
- i = 3;
- break;
- case unittest::TestAllTypes::NEG:
- i = -1;
- break;
- // no default case: We want to make sure the compiler recognizes that
- // all cases are covered. (GCC warns if you do not cover all cases of
- // an enum in a switch.)
- }
-
- // Token check just for fun.
- EXPECT_EQ(2, i);
-}
-
-TEST(GeneratedEnumTest, IsValidValue) {
- // Test enum IsValidValue.
- EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(1));
- EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(2));
- EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(3));
-
- EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(0));
- EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(4));
-
- // Make sure it also works when there are dups.
- EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(1));
- EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(2));
- EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(3));
-
- EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(0));
- EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(4));
-}
-
-TEST(GeneratedEnumTest, MinAndMax) {
- EXPECT_EQ(unittest::TestAllTypes::NEG,
- unittest::TestAllTypes::NestedEnum_MIN);
- EXPECT_EQ(unittest::TestAllTypes::BAZ,
- unittest::TestAllTypes::NestedEnum_MAX);
- EXPECT_EQ(4, unittest::TestAllTypes::NestedEnum_ARRAYSIZE);
-
- EXPECT_EQ(unittest::FOREIGN_FOO, unittest::ForeignEnum_MIN);
- EXPECT_EQ(unittest::FOREIGN_BAZ, unittest::ForeignEnum_MAX);
- EXPECT_EQ(7, unittest::ForeignEnum_ARRAYSIZE);
-
- EXPECT_EQ(1, unittest::TestEnumWithDupValue_MIN);
- EXPECT_EQ(3, unittest::TestEnumWithDupValue_MAX);
- EXPECT_EQ(4, unittest::TestEnumWithDupValue_ARRAYSIZE);
-
- EXPECT_EQ(unittest::SPARSE_E, unittest::TestSparseEnum_MIN);
- EXPECT_EQ(unittest::SPARSE_C, unittest::TestSparseEnum_MAX);
- EXPECT_EQ(12589235, unittest::TestSparseEnum_ARRAYSIZE);
-
- // Make sure we can take the address of _MIN, _MAX and _ARRAYSIZE.
- void* null_pointer = 0; // NULL may be integer-type, not pointer-type.
- EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_MIN);
- EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_MAX);
- EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_ARRAYSIZE);
-
- EXPECT_NE(null_pointer, &unittest::ForeignEnum_MIN);
- EXPECT_NE(null_pointer, &unittest::ForeignEnum_MAX);
- EXPECT_NE(null_pointer, &unittest::ForeignEnum_ARRAYSIZE);
-
- // Make sure we can use _MIN and _MAX as switch cases.
- switch (unittest::SPARSE_A) {
- case unittest::TestSparseEnum_MIN:
- case unittest::TestSparseEnum_MAX:
- break;
- default:
- break;
- }
-}
-
-#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
-
-TEST(GeneratedEnumTest, Name) {
- // "Names" in the presence of dup values are a bit arbitrary.
- EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO1));
- EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO2));
-
- EXPECT_EQ("SPARSE_A", unittest::TestSparseEnum_Name(unittest::SPARSE_A));
- EXPECT_EQ("SPARSE_B", unittest::TestSparseEnum_Name(unittest::SPARSE_B));
- EXPECT_EQ("SPARSE_C", unittest::TestSparseEnum_Name(unittest::SPARSE_C));
- EXPECT_EQ("SPARSE_D", unittest::TestSparseEnum_Name(unittest::SPARSE_D));
- EXPECT_EQ("SPARSE_E", unittest::TestSparseEnum_Name(unittest::SPARSE_E));
- EXPECT_EQ("SPARSE_F", unittest::TestSparseEnum_Name(unittest::SPARSE_F));
- EXPECT_EQ("SPARSE_G", unittest::TestSparseEnum_Name(unittest::SPARSE_G));
-}
-
-TEST(GeneratedEnumTest, Parse) {
- unittest::TestEnumWithDupValue dup_value = unittest::FOO1;
- EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO1", &dup_value));
- EXPECT_EQ(unittest::FOO1, dup_value);
- EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO2", &dup_value));
- EXPECT_EQ(unittest::FOO2, dup_value);
- EXPECT_FALSE(unittest::TestEnumWithDupValue_Parse("FOO", &dup_value));
-}
-
-TEST(GeneratedEnumTest, GetEnumDescriptor) {
- EXPECT_EQ(unittest::TestAllTypes::NestedEnum_descriptor(),
- GetEnumDescriptor<unittest::TestAllTypes::NestedEnum>());
- EXPECT_EQ(unittest::ForeignEnum_descriptor(),
- GetEnumDescriptor<unittest::ForeignEnum>());
- EXPECT_EQ(unittest::TestEnumWithDupValue_descriptor(),
- GetEnumDescriptor<unittest::TestEnumWithDupValue>());
- EXPECT_EQ(unittest::TestSparseEnum_descriptor(),
- GetEnumDescriptor<unittest::TestSparseEnum>());
-}
-
-enum NonProtoEnum {
- kFoo = 1,
-};
-
-TEST(GeneratedEnumTest, IsProtoEnumTypeTrait) {
- EXPECT_TRUE(is_proto_enum<unittest::TestAllTypes::NestedEnum>::value);
- EXPECT_TRUE(is_proto_enum<unittest::ForeignEnum>::value);
- EXPECT_TRUE(is_proto_enum<unittest::TestEnumWithDupValue>::value);
- EXPECT_TRUE(is_proto_enum<unittest::TestSparseEnum>::value);
-
- EXPECT_FALSE(is_proto_enum<int>::value);
- EXPECT_FALSE(is_proto_enum<NonProtoEnum>::value);
-}
-
-#endif // PROTOBUF_TEST_NO_DESCRIPTORS
-
-// ===================================================================
-
-#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
-
-// Support code for testing services.
-class GeneratedServiceTest : public testing::Test {
- protected:
- class MockTestService : public unittest::TestService {
- public:
- MockTestService()
- : called_(false),
- method_(""),
- controller_(NULL),
- request_(NULL),
- response_(NULL),
- done_(NULL) {}
-
- ~MockTestService() {}
-
- void Reset() { called_ = false; }
-
- // implements TestService ----------------------------------------
-
- void Foo(RpcController* controller,
- const unittest::FooRequest* request,
- unittest::FooResponse* response,
- Closure* done) {
- ASSERT_FALSE(called_);
- called_ = true;
- method_ = "Foo";
- controller_ = controller;
- request_ = request;
- response_ = response;
- done_ = done;
- }
-
- void Bar(RpcController* controller,
- const unittest::BarRequest* request,
- unittest::BarResponse* response,
- Closure* done) {
- ASSERT_FALSE(called_);
- called_ = true;
- method_ = "Bar";
- controller_ = controller;
- request_ = request;
- response_ = response;
- done_ = done;
- }
-
- // ---------------------------------------------------------------
-
- bool called_;
- string method_;
- RpcController* controller_;
- const Message* request_;
- Message* response_;
- Closure* done_;
- };
-
- class MockRpcChannel : public RpcChannel {
- public:
- MockRpcChannel()
- : called_(false),
- method_(NULL),
- controller_(NULL),
- request_(NULL),
- response_(NULL),
- done_(NULL),
- destroyed_(NULL) {}
-
- ~MockRpcChannel() {
- if (destroyed_ != NULL) *destroyed_ = true;
- }
-
- void Reset() { called_ = false; }
-
- // implements TestService ----------------------------------------
-
- void CallMethod(const MethodDescriptor* method,
- RpcController* controller,
- const Message* request,
- Message* response,
- Closure* done) {
- ASSERT_FALSE(called_);
- called_ = true;
- method_ = method;
- controller_ = controller;
- request_ = request;
- response_ = response;
- done_ = done;
- }
-
- // ---------------------------------------------------------------
-
- bool called_;
- const MethodDescriptor* method_;
- RpcController* controller_;
- const Message* request_;
- Message* response_;
- Closure* done_;
- bool* destroyed_;
- };
-
- class MockController : public RpcController {
- public:
- void Reset() {
- ADD_FAILURE() << "Reset() not expected during this test.";
- }
- bool Failed() const {
- ADD_FAILURE() << "Failed() not expected during this test.";
- return false;
- }
- string ErrorText() const {
- ADD_FAILURE() << "ErrorText() not expected during this test.";
- return "";
- }
- void StartCancel() {
- ADD_FAILURE() << "StartCancel() not expected during this test.";
- }
- void SetFailed(const string& reason) {
- ADD_FAILURE() << "SetFailed() not expected during this test.";
- }
- bool IsCanceled() const {
- ADD_FAILURE() << "IsCanceled() not expected during this test.";
- return false;
- }
- void NotifyOnCancel(Closure* callback) {
- ADD_FAILURE() << "NotifyOnCancel() not expected during this test.";
- }
- };
-
- GeneratedServiceTest()
- : descriptor_(unittest::TestService::descriptor()),
- foo_(descriptor_->FindMethodByName("Foo")),
- bar_(descriptor_->FindMethodByName("Bar")),
- stub_(&mock_channel_),
- done_(::google::protobuf::NewPermanentCallback(&DoNothing)) {}
-
- virtual void SetUp() {
- ASSERT_TRUE(foo_ != NULL);
- ASSERT_TRUE(bar_ != NULL);
- }
-
- const ServiceDescriptor* descriptor_;
- const MethodDescriptor* foo_;
- const MethodDescriptor* bar_;
-
- MockTestService mock_service_;
- MockController mock_controller_;
-
- MockRpcChannel mock_channel_;
- unittest::TestService::Stub stub_;
-
- // Just so we don't have to re-define these with every test.
- unittest::FooRequest foo_request_;
- unittest::FooResponse foo_response_;
- unittest::BarRequest bar_request_;
- unittest::BarResponse bar_response_;
- google::protobuf::scoped_ptr<Closure> done_;
-};
-
-TEST_F(GeneratedServiceTest, GetDescriptor) {
- // Test that GetDescriptor() works.
-
- EXPECT_EQ(descriptor_, mock_service_.GetDescriptor());
-}
-
-TEST_F(GeneratedServiceTest, GetChannel) {
- EXPECT_EQ(&mock_channel_, stub_.channel());
-}
-
-TEST_F(GeneratedServiceTest, OwnsChannel) {
- MockRpcChannel* channel = new MockRpcChannel;
- bool destroyed = false;
- channel->destroyed_ = &destroyed;
-
- {
- unittest::TestService::Stub owning_stub(channel,
- Service::STUB_OWNS_CHANNEL);
- EXPECT_FALSE(destroyed);
- }
-
- EXPECT_TRUE(destroyed);
-}
-
-TEST_F(GeneratedServiceTest, CallMethod) {
- // Test that CallMethod() works.
-
- // Call Foo() via CallMethod().
- mock_service_.CallMethod(foo_, &mock_controller_,
- &foo_request_, &foo_response_, done_.get());
-
- ASSERT_TRUE(mock_service_.called_);
-
- EXPECT_EQ("Foo" , mock_service_.method_ );
- EXPECT_EQ(&mock_controller_, mock_service_.controller_);
- EXPECT_EQ(&foo_request_ , mock_service_.request_ );
- EXPECT_EQ(&foo_response_ , mock_service_.response_ );
- EXPECT_EQ(done_.get() , mock_service_.done_ );
-
- // Try again, but call Bar() instead.
- mock_service_.Reset();
- mock_service_.CallMethod(bar_, &mock_controller_,
- &bar_request_, &bar_response_, done_.get());
-
- ASSERT_TRUE(mock_service_.called_);
- EXPECT_EQ("Bar", mock_service_.method_);
-}
-
-TEST_F(GeneratedServiceTest, CallMethodTypeFailure) {
- // Verify death if we call Foo() with Bar's message types.
-
-#ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet
- EXPECT_DEBUG_DEATH(
- mock_service_.CallMethod(foo_, &mock_controller_,
- &foo_request_, &bar_response_, done_.get()),
- "dynamic_cast");
-
- mock_service_.Reset();
- EXPECT_DEBUG_DEATH(
- mock_service_.CallMethod(foo_, &mock_controller_,
- &bar_request_, &foo_response_, done_.get()),
- "dynamic_cast");
-#endif // PROTOBUF_HAS_DEATH_TEST
-}
-
-TEST_F(GeneratedServiceTest, GetPrototypes) {
- // Test Get{Request,Response}Prototype() methods.
-
- EXPECT_EQ(&unittest::FooRequest::default_instance(),
- &mock_service_.GetRequestPrototype(foo_));
- EXPECT_EQ(&unittest::BarRequest::default_instance(),
- &mock_service_.GetRequestPrototype(bar_));
-
- EXPECT_EQ(&unittest::FooResponse::default_instance(),
- &mock_service_.GetResponsePrototype(foo_));
- EXPECT_EQ(&unittest::BarResponse::default_instance(),
- &mock_service_.GetResponsePrototype(bar_));
-}
-
-TEST_F(GeneratedServiceTest, Stub) {
- // Test that the stub class works.
-
- // Call Foo() via the stub.
- stub_.Foo(&mock_controller_, &foo_request_, &foo_response_, done_.get());
-
- ASSERT_TRUE(mock_channel_.called_);
-
- EXPECT_EQ(foo_ , mock_channel_.method_ );
- EXPECT_EQ(&mock_controller_, mock_channel_.controller_);
- EXPECT_EQ(&foo_request_ , mock_channel_.request_ );
- EXPECT_EQ(&foo_response_ , mock_channel_.response_ );
- EXPECT_EQ(done_.get() , mock_channel_.done_ );
-
- // Call Bar() via the stub.
- mock_channel_.Reset();
- stub_.Bar(&mock_controller_, &bar_request_, &bar_response_, done_.get());
-
- ASSERT_TRUE(mock_channel_.called_);
- EXPECT_EQ(bar_, mock_channel_.method_);
-}
-
-TEST_F(GeneratedServiceTest, NotImplemented) {
- // Test that failing to implement a method of a service causes it to fail
- // with a "not implemented" error message.
-
- // A service which doesn't implement any methods.
- class UnimplementedService : public unittest::TestService {
- public:
- UnimplementedService() {}
- };
-
- UnimplementedService unimplemented_service;
-
- // And a controller which expects to get a "not implemented" error.
- class ExpectUnimplementedController : public MockController {
- public:
- ExpectUnimplementedController() : called_(false) {}
-
- void SetFailed(const string& reason) {
- EXPECT_FALSE(called_);
- called_ = true;
- EXPECT_EQ("Method Foo() not implemented.", reason);
- }
-
- bool called_;
- };
-
- ExpectUnimplementedController controller;
-
- // Call Foo.
- unimplemented_service.Foo(&controller, &foo_request_, &foo_response_,
- done_.get());
-
- EXPECT_TRUE(controller.called_);
-}
-
-// ===================================================================
-
-class OneofTest : public testing::Test {
- protected:
- virtual void SetUp() {
- }
-
- void ExpectEnumCasesWork(const unittest::TestOneof2 &message) {
- switch (message.foo_case()) {
- case unittest::TestOneof2::kFooInt:
- EXPECT_TRUE(message.has_foo_int());
- break;
- case unittest::TestOneof2::kFooString:
- EXPECT_TRUE(message.has_foo_string());
- break;
- case unittest::TestOneof2::kFooCord:
- EXPECT_TRUE(message.has_foo_cord());
- break;
- case unittest::TestOneof2::kFooStringPiece:
- EXPECT_TRUE(message.has_foo_string_piece());
- break;
- case unittest::TestOneof2::kFooBytes:
- EXPECT_TRUE(message.has_foo_bytes());
- break;
- case unittest::TestOneof2::kFooEnum:
- EXPECT_TRUE(message.has_foo_enum());
- break;
- case unittest::TestOneof2::kFooMessage:
- EXPECT_TRUE(message.has_foo_message());
- break;
- case unittest::TestOneof2::kFoogroup:
- EXPECT_TRUE(message.has_foogroup());
- break;
- case unittest::TestOneof2::kFooLazyMessage:
- EXPECT_TRUE(message.has_foo_lazy_message());
- break;
- case unittest::TestOneof2::FOO_NOT_SET:
- break;
- }
- }
-};
-
-TEST_F(OneofTest, SettingOneFieldClearsOthers) {
- unittest::TestOneof2 message;
-
- message.set_foo_int(123);
- EXPECT_TRUE(message.has_foo_int());
- TestUtil::ExpectAtMostOneFieldSetInOneof(message);
-
- message.set_foo_string("foo");
- EXPECT_TRUE(message.has_foo_string());
- TestUtil::ExpectAtMostOneFieldSetInOneof(message);
-
-
- message.set_foo_bytes("qux");
- EXPECT_TRUE(message.has_foo_bytes());
- TestUtil::ExpectAtMostOneFieldSetInOneof(message);
-
- message.set_foo_enum(unittest::TestOneof2::FOO);
- EXPECT_TRUE(message.has_foo_enum());
- TestUtil::ExpectAtMostOneFieldSetInOneof(message);
-
- message.mutable_foo_message()->set_qux_int(234);
- EXPECT_TRUE(message.has_foo_message());
- TestUtil::ExpectAtMostOneFieldSetInOneof(message);
-
- message.mutable_foogroup()->set_a(345);
- EXPECT_TRUE(message.has_foogroup());
- TestUtil::ExpectAtMostOneFieldSetInOneof(message);
-
-
- // we repeat this because we didn't test if this properly clears other fields
- // at the beginning.
- message.set_foo_int(123);
- EXPECT_TRUE(message.has_foo_int());
- TestUtil::ExpectAtMostOneFieldSetInOneof(message);
-}
-
-TEST_F(OneofTest, EnumCases) {
- unittest::TestOneof2 message;
-
- message.set_foo_int(123);
- ExpectEnumCasesWork(message);
- message.set_foo_string("foo");
- ExpectEnumCasesWork(message);
- message.set_foo_bytes("qux");
- ExpectEnumCasesWork(message);
- message.set_foo_enum(unittest::TestOneof2::FOO);
- ExpectEnumCasesWork(message);
- message.mutable_foo_message()->set_qux_int(234);
- ExpectEnumCasesWork(message);
- message.mutable_foogroup()->set_a(345);
- ExpectEnumCasesWork(message);
-}
-
-TEST_F(OneofTest, PrimitiveType) {
- unittest::TestOneof2 message;
- // Unset field returns default value
- EXPECT_EQ(message.foo_int(), 0);
-
- message.set_foo_int(123);
- EXPECT_TRUE(message.has_foo_int());
- EXPECT_EQ(message.foo_int(), 123);
- message.clear_foo_int();
- EXPECT_FALSE(message.has_foo_int());
-}
-
-TEST_F(OneofTest, EnumType) {
- unittest::TestOneof2 message;
- // Unset field returns default value
- EXPECT_EQ(message.foo_enum(), 1);
-
- message.set_foo_enum(unittest::TestOneof2::FOO);
- EXPECT_TRUE(message.has_foo_enum());
- EXPECT_EQ(message.foo_enum(), unittest::TestOneof2::FOO);
- message.clear_foo_enum();
- EXPECT_FALSE(message.has_foo_enum());
-}
-
-TEST_F(OneofTest, SetString) {
- // Check that setting a string field in various ways works
- unittest::TestOneof2 message;
-
- // Unset field returns default value
- EXPECT_EQ(message.foo_string(), "");
-
- message.set_foo_string("foo");
- EXPECT_TRUE(message.has_foo_string());
- EXPECT_EQ(message.foo_string(), "foo");
- message.clear_foo_string();
- EXPECT_FALSE(message.has_foo_string());
-
- message.set_foo_string(string("bar"));
- EXPECT_TRUE(message.has_foo_string());
- EXPECT_EQ(message.foo_string(), "bar");
- message.clear_foo_string();
- EXPECT_FALSE(message.has_foo_string());
-
-
- message.set_foo_string("qux", 3);
- EXPECT_TRUE(message.has_foo_string());
- EXPECT_EQ(message.foo_string(), "qux");
- message.clear_foo_string();
- EXPECT_FALSE(message.has_foo_string());
-
- message.mutable_foo_string()->assign("quux");
- EXPECT_TRUE(message.has_foo_string());
- EXPECT_EQ(message.foo_string(), "quux");
- message.clear_foo_string();
- EXPECT_FALSE(message.has_foo_string());
-
- message.set_foo_string("corge");
- EXPECT_TRUE(message.has_foo_string());
- EXPECT_EQ(message.foo_string(), "corge");
- message.clear_foo_string();
- EXPECT_FALSE(message.has_foo_string());
-}
-
-TEST_F(OneofTest, ReleaseString) {
- // Check that release_foo() starts out NULL, and gives us a value
- // that we can delete after it's been set.
- unittest::TestOneof2 message;
-
- EXPECT_EQ(NULL, message.release_foo_string());
- EXPECT_FALSE(message.has_foo_string());
-
- message.set_foo_string("blah");
- EXPECT_TRUE(message.has_foo_string());
- google::protobuf::scoped_ptr<string> str(message.release_foo_string());
- EXPECT_FALSE(message.has_foo_string());
- ASSERT_TRUE(str != NULL);
- EXPECT_EQ("blah", *str);
-
- EXPECT_EQ(NULL, message.release_foo_string());
- EXPECT_FALSE(message.has_foo_string());
-}
-
-TEST_F(OneofTest, SetAllocatedString) {
- // Check that set_allocated_foo() works for strings.
- unittest::TestOneof2 message;
-
- EXPECT_FALSE(message.has_foo_string());
- const string kHello("hello");
- message.set_foo_string(kHello);
- EXPECT_TRUE(message.has_foo_string());
-
- message.set_allocated_foo_string(NULL);
- EXPECT_FALSE(message.has_foo_string());
- EXPECT_EQ("", message.foo_string());
-
- message.set_allocated_foo_string(new string(kHello));
- EXPECT_TRUE(message.has_foo_string());
- EXPECT_EQ(kHello, message.foo_string());
-}
-
-
-TEST_F(OneofTest, SetMessage) {
- // Check that setting a message field works
- unittest::TestOneof2 message;
-
- // Unset field returns default instance
- EXPECT_EQ(&message.foo_message(),
- &unittest::TestOneof2_NestedMessage::default_instance());
- EXPECT_EQ(message.foo_message().qux_int(), 0);
-
- message.mutable_foo_message()->set_qux_int(234);
- EXPECT_TRUE(message.has_foo_message());
- EXPECT_EQ(message.foo_message().qux_int(), 234);
- message.clear_foo_message();
- EXPECT_FALSE(message.has_foo_message());
-}
-
-TEST_F(OneofTest, ReleaseMessage) {
- // Check that release_foo() starts out NULL, and gives us a value
- // that we can delete after it's been set.
- unittest::TestOneof2 message;
-
- EXPECT_EQ(NULL, message.release_foo_message());
- EXPECT_FALSE(message.has_foo_message());
-
- message.mutable_foo_message()->set_qux_int(1);
- EXPECT_TRUE(message.has_foo_message());
- google::protobuf::scoped_ptr<unittest::TestOneof2_NestedMessage> mes(
- message.release_foo_message());
- EXPECT_FALSE(message.has_foo_message());
- ASSERT_TRUE(mes != NULL);
- EXPECT_EQ(1, mes->qux_int());
-
- EXPECT_EQ(NULL, message.release_foo_message());
- EXPECT_FALSE(message.has_foo_message());
-}
-
-TEST_F(OneofTest, SetAllocatedMessage) {
- // Check that set_allocated_foo() works for messages.
- unittest::TestOneof2 message;
-
- EXPECT_FALSE(message.has_foo_message());
-
- message.mutable_foo_message()->set_qux_int(1);
- EXPECT_TRUE(message.has_foo_message());
-
- message.set_allocated_foo_message(NULL);
- EXPECT_FALSE(message.has_foo_message());
- EXPECT_EQ(&message.foo_message(),
- &unittest::TestOneof2_NestedMessage::default_instance());
-
- message.mutable_foo_message()->set_qux_int(1);
- unittest::TestOneof2_NestedMessage* mes = message.release_foo_message();
- ASSERT_TRUE(mes != NULL);
- EXPECT_FALSE(message.has_foo_message());
-
- message.set_allocated_foo_message(mes);
- EXPECT_TRUE(message.has_foo_message());
- EXPECT_EQ(1, message.foo_message().qux_int());
-}
-
-
-TEST_F(OneofTest, Clear) {
- unittest::TestOneof2 message;
-
- message.set_foo_int(1);
- EXPECT_TRUE(message.has_foo_int());
- message.clear_foo_int();
- EXPECT_FALSE(message.has_foo_int());
-}
-
-TEST_F(OneofTest, Defaults) {
- unittest::TestOneof2 message;
-
- EXPECT_FALSE(message.has_foo_int());
- EXPECT_EQ(message.foo_int(), 0);
-
- EXPECT_FALSE(message.has_foo_string());
- EXPECT_EQ(message.foo_string(), "");
-
-
- EXPECT_FALSE(message.has_foo_bytes());
- EXPECT_EQ(message.foo_bytes(), "");
-
- EXPECT_FALSE(message.has_foo_enum());
- EXPECT_EQ(message.foo_enum(), 1);
-
- EXPECT_FALSE(message.has_foo_message());
- EXPECT_EQ(message.foo_message().qux_int(), 0);
-
- EXPECT_FALSE(message.has_foogroup());
- EXPECT_EQ(message.foogroup().a(), 0);
-
-
- EXPECT_FALSE(message.has_bar_int());
- EXPECT_EQ(message.bar_int(), 5);
-
- EXPECT_FALSE(message.has_bar_string());
- EXPECT_EQ(message.bar_string(), "STRING");
-
-
- EXPECT_FALSE(message.has_bar_bytes());
- EXPECT_EQ(message.bar_bytes(), "BYTES");
-
- EXPECT_FALSE(message.has_bar_enum());
- EXPECT_EQ(message.bar_enum(), 2);
-}
-
-TEST_F(OneofTest, SwapWithEmpty) {
- unittest::TestOneof2 message1, message2;
- message1.set_foo_string("FOO");
- EXPECT_TRUE(message1.has_foo_string());
- message1.Swap(&message2);
- EXPECT_FALSE(message1.has_foo_string());
- EXPECT_TRUE(message2.has_foo_string());
- EXPECT_EQ(message2.foo_string(), "FOO");
-}
-
-TEST_F(OneofTest, SwapWithSelf) {
- unittest::TestOneof2 message;
- message.set_foo_string("FOO");
- EXPECT_TRUE(message.has_foo_string());
- message.Swap(&message);
- EXPECT_TRUE(message.has_foo_string());
- EXPECT_EQ(message.foo_string(), "FOO");
-}
-
-TEST_F(OneofTest, SwapBothHasFields) {
- unittest::TestOneof2 message1, message2;
-
- message1.set_foo_string("FOO");
- EXPECT_TRUE(message1.has_foo_string());
- message2.mutable_foo_message()->set_qux_int(1);
- EXPECT_TRUE(message2.has_foo_message());
-
- message1.Swap(&message2);
- EXPECT_FALSE(message1.has_foo_string());
- EXPECT_FALSE(message2.has_foo_message());
- EXPECT_TRUE(message1.has_foo_message());
- EXPECT_EQ(message1.foo_message().qux_int(), 1);
- EXPECT_TRUE(message2.has_foo_string());
- EXPECT_EQ(message2.foo_string(), "FOO");
-}
-
-TEST_F(OneofTest, CopyConstructor) {
- unittest::TestOneof2 message1;
- message1.set_foo_bytes("FOO");
-
- unittest::TestOneof2 message2(message1);
- EXPECT_TRUE(message2.has_foo_bytes());
- EXPECT_EQ(message2.foo_bytes(), "FOO");
-}
-
-TEST_F(OneofTest, CopyFrom) {
- unittest::TestOneof2 message1, message2;
- message1.set_foo_enum(unittest::TestOneof2::BAR);
- EXPECT_TRUE(message1.has_foo_enum());
-
- message2.CopyFrom(message1);
- EXPECT_TRUE(message2.has_foo_enum());
- EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::BAR);
-
- // Copying from self should be a no-op.
- message2.CopyFrom(message2);
- EXPECT_TRUE(message2.has_foo_enum());
- EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::BAR);
-}
-
-TEST_F(OneofTest, CopyAssignmentOperator) {
- unittest::TestOneof2 message1;
- message1.mutable_foo_message()->set_qux_int(123);
- EXPECT_TRUE(message1.has_foo_message());
-
- unittest::TestOneof2 message2;
- message2 = message1;
- EXPECT_EQ(message2.foo_message().qux_int(), 123);
-
- // Make sure that self-assignment does something sane.
- message2 = message2;
- EXPECT_EQ(message2.foo_message().qux_int(), 123);
-}
-
-TEST_F(OneofTest, UpcastCopyFrom) {
- // Test the CopyFrom method that takes in the generic const Message&
- // parameter.
- unittest::TestOneof2 message1, message2;
- message1.mutable_foogroup()->set_a(123);
- EXPECT_TRUE(message1.has_foogroup());
-
- const Message* source = implicit_cast<const Message*>(&message1);
- message2.CopyFrom(*source);
-
- EXPECT_TRUE(message2.has_foogroup());
- EXPECT_EQ(message2.foogroup().a(), 123);
-}
-
-// Test the generated SerializeWithCachedSizesToArray(),
-// This indirectly tests MergePartialFromCodedStream()
-// We have to test each field type separately because we cannot set them at the
-// same time
-TEST_F(OneofTest, SerializationToArray) {
- // Primitive type
- {
- unittest::TestOneof2 message1, message2;
- string data;
- message1.set_foo_int(123);
- int size = message1.ByteSize();
- data.resize(size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
- uint8* end = message1.SerializeWithCachedSizesToArray(start);
- EXPECT_EQ(size, end - start);
- EXPECT_TRUE(message2.ParseFromString(data));
- EXPECT_EQ(message2.foo_int(), 123);
- }
-
- // String
- {
- unittest::TestOneof2 message1, message2;
- string data;
- message1.set_foo_string("foo");
- int size = message1.ByteSize();
- data.resize(size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
- uint8* end = message1.SerializeWithCachedSizesToArray(start);
- EXPECT_EQ(size, end - start);
- EXPECT_TRUE(message2.ParseFromString(data));
- EXPECT_EQ(message2.foo_string(), "foo");
- }
-
-
- // Bytes
- {
- unittest::TestOneof2 message1, message2;
- string data;
- message1.set_foo_bytes("qux");
- int size = message1.ByteSize();
- data.resize(size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
- uint8* end = message1.SerializeWithCachedSizesToArray(start);
- EXPECT_EQ(size, end - start);
- EXPECT_TRUE(message2.ParseFromString(data));
- EXPECT_EQ(message2.foo_bytes(), "qux");
- }
-
- // Enum
- {
- unittest::TestOneof2 message1, message2;
- string data;
- message1.set_foo_enum(unittest::TestOneof2::FOO);
- int size = message1.ByteSize();
- data.resize(size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
- uint8* end = message1.SerializeWithCachedSizesToArray(start);
- EXPECT_EQ(size, end - start);
- EXPECT_TRUE(message2.ParseFromString(data));
- EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::FOO);
- }
-
- // Message
- {
- unittest::TestOneof2 message1, message2;
- string data;
- message1.mutable_foo_message()->set_qux_int(234);
- int size = message1.ByteSize();
- data.resize(size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
- uint8* end = message1.SerializeWithCachedSizesToArray(start);
- EXPECT_EQ(size, end - start);
- EXPECT_TRUE(message2.ParseFromString(data));
- EXPECT_EQ(message2.foo_message().qux_int(), 234);
- }
-
- // Group
- {
- unittest::TestOneof2 message1, message2;
- string data;
- message1.mutable_foogroup()->set_a(345);
- int size = message1.ByteSize();
- data.resize(size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
- uint8* end = message1.SerializeWithCachedSizesToArray(start);
- EXPECT_EQ(size, end - start);
- EXPECT_TRUE(message2.ParseFromString(data));
- EXPECT_EQ(message2.foogroup().a(), 345);
- }
-
-}
-
-// Test the generated SerializeWithCachedSizes() by forcing the buffer to write
-// one byte at a time.
-// This indirectly tests MergePartialFromCodedStream()
-// We have to test each field type separately because we cannot set them at the
-// same time
-TEST_F(OneofTest, SerializationToStream) {
- // Primitive type
- {
- unittest::TestOneof2 message1, message2;
- string data;
- message1.set_foo_int(123);
- int size = message1.ByteSize();
- 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::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));
- EXPECT_EQ(message2.foo_int(), 123);
- }
-
- // String
- {
- unittest::TestOneof2 message1, message2;
- string data;
- message1.set_foo_string("foo");
- int size = message1.ByteSize();
- 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::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));
- EXPECT_EQ(message2.foo_string(), "foo");
- }
-
-
- // Bytes
- {
- unittest::TestOneof2 message1, message2;
- string data;
- message1.set_foo_bytes("qux");
- int size = message1.ByteSize();
- 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::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));
- EXPECT_EQ(message2.foo_bytes(), "qux");
- }
-
- // Enum
- {
- unittest::TestOneof2 message1, message2;
- string data;
- message1.set_foo_enum(unittest::TestOneof2::FOO);
- int size = message1.ByteSize();
- 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::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));
- EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::FOO);
- }
-
- // Message
- {
- unittest::TestOneof2 message1, message2;
- string data;
- message1.mutable_foo_message()->set_qux_int(234);
- int size = message1.ByteSize();
- 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::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));
- EXPECT_EQ(message2.foo_message().qux_int(), 234);
- }
-
- // Group
- {
- unittest::TestOneof2 message1, message2;
- string data;
- message1.mutable_foogroup()->set_a(345);
- int size = message1.ByteSize();
- 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::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));
- EXPECT_EQ(message2.foogroup().a(), 345);
- }
-
-}
-
-TEST_F(OneofTest, MergeFrom) {
- unittest::TestOneof2 message1, message2;
-
- message1.set_foo_int(123);
- message2.MergeFrom(message1);
- TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
- EXPECT_TRUE(message2.has_foo_int());
- EXPECT_EQ(message2.foo_int(), 123);
-
- message1.set_foo_string("foo");
- message2.MergeFrom(message1);
- TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
- EXPECT_TRUE(message2.has_foo_string());
- EXPECT_EQ(message2.foo_string(), "foo");
-
-
- message1.set_foo_bytes("qux");
- message2.MergeFrom(message1);
- TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
- EXPECT_TRUE(message2.has_foo_bytes());
- EXPECT_EQ(message2.foo_bytes(), "qux");
-
- message1.set_foo_enum(unittest::TestOneof2::FOO);
- message2.MergeFrom(message1);
- TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
- EXPECT_TRUE(message2.has_foo_enum());
- EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::FOO);
-
- message1.mutable_foo_message()->set_qux_int(234);
- message2.MergeFrom(message1);
- TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
- EXPECT_TRUE(message2.has_foo_message());
- EXPECT_EQ(message2.foo_message().qux_int(), 234);
-
- message1.mutable_foogroup()->set_a(345);
- message2.MergeFrom(message1);
- TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
- EXPECT_TRUE(message2.has_foogroup());
- EXPECT_EQ(message2.foogroup().a(), 345);
-
-}
-
-TEST(HelpersTest, TestSCC) {
- protobuf_unittest::TestMutualRecursionA a;
- SCCAnalyzer scc_analyzer((Options()));
- const SCC* scc = scc_analyzer.GetSCC(a.GetDescriptor());
- std::vector<string> names;
- for (int i = 0; i < scc->descriptors.size(); i++) {
- names.push_back(scc->descriptors[i]->full_name());
- }
- ASSERT_EQ(names.size(), 4);
- std::sort(names.begin(), names.end());
- EXPECT_EQ(names[0], "protobuf_unittest.TestMutualRecursionA");
- EXPECT_EQ(names[1], "protobuf_unittest.TestMutualRecursionA.SubGroup");
- EXPECT_EQ(names[2], "protobuf_unittest.TestMutualRecursionA.SubMessage");
- EXPECT_EQ(names[3], "protobuf_unittest.TestMutualRecursionB");
-
- MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
- EXPECT_EQ(result.is_recursive, true);
- EXPECT_EQ(result.contains_required, false);
- EXPECT_EQ(result.contains_cord, true); // TestAllTypes
- EXPECT_EQ(result.contains_extension, false); // TestAllTypes
-}
-
-TEST(HelpersTest, TestSCCAnalysis) {
- {
- protobuf_unittest::TestRecursiveMessage msg;
- SCCAnalyzer scc_analyzer((Options()));
- const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor());
- MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
- EXPECT_EQ(result.is_recursive, true);
- EXPECT_EQ(result.contains_required, false);
- EXPECT_EQ(result.contains_cord, false);
- EXPECT_EQ(result.contains_extension, false);
- }
- {
- protobuf_unittest::TestAllExtensions msg;
- SCCAnalyzer scc_analyzer((Options()));
- const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor());
- MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
- EXPECT_EQ(result.is_recursive, false);
- EXPECT_EQ(result.contains_required, false);
- EXPECT_EQ(result.contains_cord, false);
- EXPECT_EQ(result.contains_extension, true);
- }
- {
- protobuf_unittest::TestRequired msg;
- SCCAnalyzer scc_analyzer((Options()));
- const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor());
- MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
- EXPECT_EQ(result.is_recursive, false);
- EXPECT_EQ(result.contains_required, true);
- EXPECT_EQ(result.contains_cord, false);
- EXPECT_EQ(result.contains_extension, false);
- }
-}
-
-} // namespace cpp_unittest
-} // namespace cpp
-} // namespace compiler
-
-namespace no_generic_services_test {
- // Verify that no class called "TestService" was defined in
- // unittest_no_generic_services.pb.h by defining a different type by the same
- // name. If such a service was generated, this will not compile.
- struct TestService {
- int i;
- };
-}
-
-namespace compiler {
-namespace cpp {
-namespace cpp_unittest {
-
-TEST_F(GeneratedServiceTest, NoGenericServices) {
- // Verify that non-services in unittest_no_generic_services.proto were
- // generated.
- no_generic_services_test::TestMessage message;
- message.set_a(1);
- message.SetExtension(no_generic_services_test::test_extension, 123);
- no_generic_services_test::TestEnum e = no_generic_services_test::FOO;
- EXPECT_EQ(e, 1);
-
- // Verify that a ServiceDescriptor is generated for the service even if the
- // class itself is not.
- const FileDescriptor* file =
- no_generic_services_test::TestMessage::descriptor()->file();
-
- ASSERT_EQ(1, file->service_count());
- EXPECT_EQ("TestService", file->service(0)->name());
- ASSERT_EQ(1, file->service(0)->method_count());
- EXPECT_EQ("Foo", file->service(0)->method(0)->name());
-}
-
-#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
-
-// ===================================================================
-
-// This test must run last. It verifies that descriptors were or were not
-// initialized depending on whether PROTOBUF_TEST_NO_DESCRIPTORS was defined.
-// When this is defined, we skip all tests which are expected to trigger
-// descriptor initialization. This verifies that everything else still works
-// if descriptors are not initialized.
-TEST(DescriptorInitializationTest, Initialized) {
-#ifdef PROTOBUF_TEST_NO_DESCRIPTORS
- bool should_have_descriptors = false;
-#else
- bool should_have_descriptors = true;
-#endif
-
- EXPECT_EQ(should_have_descriptors,
- DescriptorPool::generated_pool()->InternalIsFileLoaded(
- "google/protobuf/unittest.proto"));
-}
-
} // namespace cpp_unittest
-
} // namespace cpp
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.inc b/src/google/protobuf/compiler/cpp/cpp_unittest.inc
new file mode 100644
index 00000000..ff6354f8
--- /dev/null
+++ b/src/google/protobuf/compiler/cpp/cpp_unittest.inc
@@ -0,0 +1,2281 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: kenton@google.com (Kenton Varda)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+//
+// To test the code generator, we actually use it to generate code for
+// google/protobuf/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
+// the output of the C++ generator directly would be very hard. We can't very
+// well just check it against golden files since those files would have to be
+// updated for any small change; such a test would be very brittle and probably
+// not very helpful. What we really want to test is that the code compiles
+// correctly and produces the interfaces we expect, which is why this test
+// is written this way.
+
+#include <google/protobuf/compiler/cpp/cpp_unittest.h>
+
+#include <memory>
+#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).
+#include <google/protobuf/unittest_enormous_descriptor.pb.h>
+#endif
+#include <google/protobuf/compiler/cpp/cpp_helpers.h>
+#include <google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.h>
+#include <google/protobuf/compiler/importer.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>
+#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/arena.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/dynamic_message.h>
+
+#include <google/protobuf/stubs/callback.h>
+#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/stubs/substitute.h>
+#include <google/protobuf/testing/googletest.h>
+#include <gtest/gtest.h>
+#include <google/protobuf/stubs/stl_util.h>
+
+namespace google {
+namespace protobuf {
+namespace compiler {
+namespace cpp {
+
+// Can't use an anonymous namespace here due to brokenness of Tru64 compiler.
+namespace cpp_unittest {
+
+
+class MockErrorCollector : public MultiFileErrorCollector {
+ public:
+ MockErrorCollector() {}
+ ~MockErrorCollector() {}
+
+ string text_;
+
+ // implements ErrorCollector ---------------------------------------
+ void AddError(const string& filename, int line, int column,
+ const string& message) {
+ strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
+ filename, line, column, message);
+ }
+};
+
+#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
+
+// Test that generated code has proper descriptors:
+// Parse a descriptor directly (using google::protobuf::compiler::Importer) and
+// compare it to the one that was produced by generated code.
+TEST(GENERATED_DESCRIPTOR_TEST_NAME, IdenticalDescriptors) {
+ const FileDescriptor* generated_descriptor =
+ UNITTEST::TestAllTypes::descriptor()->file();
+
+ // Set up the Importer.
+ MockErrorCollector error_collector;
+ DiskSourceTree source_tree;
+ source_tree.MapPath("", TestSourceDir());
+ Importer importer(&source_tree, &error_collector);
+
+ // Import (parse) unittest.proto.
+ const FileDescriptor* parsed_descriptor =
+ importer.Import(UNITTEST_PROTO_PATH);
+ EXPECT_EQ("", error_collector.text_);
+ ASSERT_TRUE(parsed_descriptor != NULL);
+
+ // Test that descriptors are generated correctly by converting them to
+ // FileDescriptorProtos and comparing.
+ FileDescriptorProto generated_descriptor_proto, parsed_descriptor_proto;
+ generated_descriptor->CopyTo(&generated_descriptor_proto);
+ parsed_descriptor->CopyTo(&parsed_descriptor_proto);
+
+ EXPECT_EQ(parsed_descriptor_proto.DebugString(),
+ generated_descriptor_proto.DebugString());
+}
+
+#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER)
+// Test that generated code has proper descriptors:
+// Touch a descriptor generated from an enormous message to validate special
+// handling for descriptors exceeding the C++ standard's recommended minimum
+// limit for string literal size
+TEST(GENERATED_DESCRIPTOR_TEST_NAME, EnormousDescriptor) {
+ const Descriptor* generated_descriptor =
+ TestEnormousDescriptor::descriptor();
+
+ EXPECT_TRUE(generated_descriptor != NULL);
+}
+#endif
+
+#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
+
+// ===================================================================
+
+TEST(GENERATED_MESSAGE_TEST_NAME, Defaults) {
+ // Check that all default values are set correctly in the initial message.
+ UNITTEST::TestAllTypes message;
+
+ TestUtil::ExpectClear(message);
+
+ // Messages should return pointers to default instances until first use.
+ // (This is not checked by ExpectClear() since it is not actually true after
+ // the fields have been set and then cleared.)
+ EXPECT_EQ(&UNITTEST::TestAllTypes::OptionalGroup::default_instance(),
+ &message.optionalgroup());
+ EXPECT_EQ(&UNITTEST::TestAllTypes::NestedMessage::default_instance(),
+ &message.optional_nested_message());
+ EXPECT_EQ(&UNITTEST::ForeignMessage::default_instance(),
+ &message.optional_foreign_message());
+ EXPECT_EQ(&UNITTEST_IMPORT::ImportMessage::default_instance(),
+ &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();
+
+ EXPECT_EQ(0.0f, extreme_default.zero_float());
+ EXPECT_EQ(1.0f, extreme_default.one_float());
+ EXPECT_EQ(1.5f, extreme_default.small_float());
+ EXPECT_EQ(-1.0f, extreme_default.negative_one_float());
+ EXPECT_EQ(-1.5f, extreme_default.negative_float());
+ EXPECT_EQ(2.0e8f, extreme_default.large_float());
+ EXPECT_EQ(-8e-28f, extreme_default.small_negative_float());
+ EXPECT_EQ(std::numeric_limits<double>::infinity(),
+ extreme_default.inf_double());
+ EXPECT_EQ(-std::numeric_limits<double>::infinity(),
+ extreme_default.neg_inf_double());
+ EXPECT_TRUE(extreme_default.nan_double() != extreme_default.nan_double());
+ EXPECT_EQ(std::numeric_limits<float>::infinity(),
+ extreme_default.inf_float());
+ EXPECT_EQ(-std::numeric_limits<float>::infinity(),
+ extreme_default.neg_inf_float());
+ EXPECT_TRUE(extreme_default.nan_float() != extreme_default.nan_float());
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, Trigraph) {
+ const UNITTEST::TestExtremeDefaultValues& extreme_default =
+ UNITTEST::TestExtremeDefaultValues::default_instance();
+
+ EXPECT_EQ("? ? ?? ?? ??? ?\?/ ?\?-", extreme_default.cpp_trigraph());
+}
+
+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(kint32min, extreme_default.really_small_int32());
+ EXPECT_EQ(kint64min, extreme_default.really_small_int64());
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, Accessors) {
+ // Set every field to a unique value then go back and check all those
+ // values.
+ UNITTEST::TestAllTypes message;
+
+ TestUtil::SetAllFields(&message);
+ TestUtil::ExpectAllFieldsSet(message);
+
+ TestUtil::ModifyRepeatedFields(&message);
+ TestUtil::ExpectRepeatedFieldsModified(message);
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, MutableStringDefault) {
+ // mutable_foo() for a string should return a string initialized to its
+ // default value.
+ UNITTEST::TestAllTypes message;
+
+ EXPECT_EQ("hello", *message.mutable_default_string());
+
+ // Note that the first time we call mutable_foo(), we get a newly-allocated
+ // string, but if we clear it and call it again, we get the same object again.
+ // We should verify that it has its default value in both cases.
+ message.set_default_string("blah");
+ message.Clear();
+
+ EXPECT_EQ("hello", *message.mutable_default_string());
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, StringDefaults) {
+ UNITTEST::TestExtremeDefaultValues message;
+ // Check if '\000' can be used in default string value.
+ EXPECT_EQ(string("hel\000lo", 6), message.string_with_zero());
+ EXPECT_EQ(string("wor\000ld", 6), message.bytes_with_zero());
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, ReleaseString) {
+ // Check that release_foo() starts out NULL, and gives us a value
+ // that we can delete after it's been set.
+ UNITTEST::TestAllTypes message;
+
+ EXPECT_EQ(NULL, message.release_default_string());
+ EXPECT_FALSE(message.has_default_string());
+ EXPECT_EQ("hello", message.default_string());
+
+ message.set_default_string("blah");
+ EXPECT_TRUE(message.has_default_string());
+ std::unique_ptr<string> str(message.release_default_string());
+ EXPECT_FALSE(message.has_default_string());
+ ASSERT_TRUE(str != NULL);
+ EXPECT_EQ("blah", *str);
+
+ EXPECT_EQ(NULL, message.release_default_string());
+ EXPECT_FALSE(message.has_default_string());
+ EXPECT_EQ("hello", message.default_string());
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, ReleaseMessage) {
+ // Check that release_foo() starts out NULL, and gives us a value
+ // that we can delete after it's been set.
+ UNITTEST::TestAllTypes message;
+
+ EXPECT_EQ(NULL, message.release_optional_nested_message());
+ EXPECT_FALSE(message.has_optional_nested_message());
+
+ message.mutable_optional_nested_message()->set_bb(1);
+ std::unique_ptr<UNITTEST::TestAllTypes::NestedMessage> nest(
+ message.release_optional_nested_message());
+ EXPECT_FALSE(message.has_optional_nested_message());
+ ASSERT_TRUE(nest != NULL);
+ EXPECT_EQ(1, nest->bb());
+
+ EXPECT_EQ(NULL, message.release_optional_nested_message());
+ EXPECT_FALSE(message.has_optional_nested_message());
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, SetAllocatedString) {
+ // Check that set_allocated_foo() works for strings.
+ UNITTEST::TestAllTypes message;
+
+ EXPECT_FALSE(message.has_optional_string());
+ const string kHello("hello");
+ message.set_optional_string(kHello);
+ EXPECT_TRUE(message.has_optional_string());
+
+ message.set_allocated_optional_string(NULL);
+ EXPECT_FALSE(message.has_optional_string());
+ EXPECT_EQ("", message.optional_string());
+
+ message.set_allocated_optional_string(new string(kHello));
+ EXPECT_TRUE(message.has_optional_string());
+ EXPECT_EQ(kHello, message.optional_string());
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, SetAllocatedMessage) {
+ // Check that set_allocated_foo() can be called in all cases.
+ UNITTEST::TestAllTypes message;
+
+ EXPECT_FALSE(message.has_optional_nested_message());
+
+ message.mutable_optional_nested_message()->set_bb(1);
+ EXPECT_TRUE(message.has_optional_nested_message());
+
+ message.set_allocated_optional_nested_message(NULL);
+ EXPECT_FALSE(message.has_optional_nested_message());
+ EXPECT_EQ(&UNITTEST::TestAllTypes::NestedMessage::default_instance(),
+ &message.optional_nested_message());
+
+ message.mutable_optional_nested_message()->set_bb(1);
+ UNITTEST::TestAllTypes::NestedMessage* nest =
+ message.release_optional_nested_message();
+ ASSERT_TRUE(nest != NULL);
+ EXPECT_FALSE(message.has_optional_nested_message());
+
+ message.set_allocated_optional_nested_message(nest);
+ EXPECT_TRUE(message.has_optional_nested_message());
+ EXPECT_EQ(1, message.optional_nested_message().bb());
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, Clear) {
+ // Set every field to a unique value, clear the message, then check that
+ // it is cleared.
+ UNITTEST::TestAllTypes message;
+
+ TestUtil::SetAllFields(&message);
+ message.Clear();
+ TestUtil::ExpectClear(message);
+
+ // Unlike with the defaults test, we do NOT expect that requesting embedded
+ // messages will return a pointer to the default instance. Instead, they
+ // should return the objects that were created when mutable_blah() was
+ // called.
+ EXPECT_NE(&UNITTEST::TestAllTypes::OptionalGroup::default_instance(),
+ &message.optionalgroup());
+ EXPECT_NE(&UNITTEST::TestAllTypes::NestedMessage::default_instance(),
+ &message.optional_nested_message());
+ EXPECT_NE(&UNITTEST::ForeignMessage::default_instance(),
+ &message.optional_foreign_message());
+ EXPECT_NE(&UNITTEST_IMPORT::ImportMessage::default_instance(),
+ &message.optional_import_message());
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, EmbeddedNullsInBytesCharStar) {
+ UNITTEST::TestAllTypes message;
+
+ const char* value = "\0lalala\0\0";
+ message.set_optional_bytes(value, 9);
+ ASSERT_EQ(9, message.optional_bytes().size());
+ EXPECT_EQ(0, memcmp(value, message.optional_bytes().data(), 9));
+
+ message.add_repeated_bytes(value, 9);
+ ASSERT_EQ(9, message.repeated_bytes(0).size());
+ EXPECT_EQ(0, memcmp(value, message.repeated_bytes(0).data(), 9));
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, ClearOneField) {
+ // Set every field to a unique value, then clear one value and insure that
+ // only that one value is cleared.
+ UNITTEST::TestAllTypes message;
+
+ TestUtil::SetAllFields(&message);
+ int64 original_value = message.optional_int64();
+
+ // Clear the field and make sure it shows up as cleared.
+ message.clear_optional_int64();
+ EXPECT_FALSE(message.has_optional_int64());
+ EXPECT_EQ(0, message.optional_int64());
+
+ // Other adjacent fields should not be cleared.
+ EXPECT_TRUE(message.has_optional_int32());
+ EXPECT_TRUE(message.has_optional_uint32());
+
+ // Make sure if we set it again, then all fields are set.
+ message.set_optional_int64(original_value);
+ TestUtil::ExpectAllFieldsSet(message);
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, StringCharStarLength) {
+ // Verify that we can use a char*,length to set one of the string fields.
+ UNITTEST::TestAllTypes message;
+ message.set_optional_string("abcdef", 3);
+ EXPECT_EQ("abc", message.optional_string());
+
+ // Verify that we can use a char*,length to add to a repeated string field.
+ message.add_repeated_string("abcdef", 3);
+ EXPECT_EQ(1, message.repeated_string_size());
+ EXPECT_EQ("abc", message.repeated_string(0));
+
+ // Verify that we can use a char*,length to set a repeated string field.
+ message.set_repeated_string(0, "wxyz", 2);
+ EXPECT_EQ("wx", message.repeated_string(0));
+}
+
+#if LANG_CXX11
+TEST(GENERATED_MESSAGE_TEST_NAME, StringMove) {
+ // Verify that we trigger the move behavior on a scalar setter.
+ protobuf_unittest_no_arena::TestAllTypes message;
+ {
+ string tmp(32, 'a');
+
+ const char* old_data = tmp.data();
+ message.set_optional_string(std::move(tmp));
+ const char* new_data = message.optional_string().data();
+
+ EXPECT_EQ(old_data, new_data);
+ EXPECT_EQ(string(32, 'a'), message.optional_string());
+
+ string tmp2(32, 'b');
+ old_data = tmp2.data();
+ message.set_optional_string(std::move(tmp2));
+ new_data = message.optional_string().data();
+
+ EXPECT_EQ(old_data, new_data);
+ EXPECT_EQ(string(32, 'b'), message.optional_string());
+ }
+
+ // Verify that we trigger the move behavior on a oneof setter.
+ {
+ string tmp(32, 'a');
+
+ const char* old_data = tmp.data();
+ message.set_oneof_string(std::move(tmp));
+ const char* new_data = message.oneof_string().data();
+
+ EXPECT_EQ(old_data, new_data);
+ EXPECT_EQ(string(32, 'a'), message.oneof_string());
+
+ string tmp2(32, 'b');
+ old_data = tmp2.data();
+ message.set_oneof_string(std::move(tmp2));
+ new_data = message.oneof_string().data();
+
+ EXPECT_EQ(old_data, new_data);
+ EXPECT_EQ(string(32, 'b'), message.oneof_string());
+ }
+
+ // Verify that we trigger the move behavior on a repeated setter.
+ {
+ string tmp(32, 'a');
+
+ const char* old_data = tmp.data();
+ message.add_repeated_string(std::move(tmp));
+ const char* new_data = message.repeated_string(0).data();
+
+ EXPECT_EQ(old_data, new_data);
+ EXPECT_EQ(string(32, 'a'), message.repeated_string(0));
+
+ string tmp2(32, 'b');
+ old_data = tmp2.data();
+ message.set_repeated_string(0, std::move(tmp2));
+ new_data = message.repeated_string(0).data();
+
+ EXPECT_EQ(old_data, new_data);
+ EXPECT_EQ(string(32, 'b'), message.repeated_string(0));
+ }
+}
+#endif
+
+
+TEST(GENERATED_MESSAGE_TEST_NAME, CopyFrom) {
+ UNITTEST::TestAllTypes message1, message2;
+
+ TestUtil::SetAllFields(&message1);
+ message2.CopyFrom(message1);
+ TestUtil::ExpectAllFieldsSet(message2);
+
+ // Copying from self should be a no-op.
+ message2.CopyFrom(message2);
+ TestUtil::ExpectAllFieldsSet(message2);
+}
+
+
+TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithEmpty) {
+ UNITTEST::TestAllTypes message1, message2;
+ TestUtil::SetAllFields(&message1);
+
+ TestUtil::ExpectAllFieldsSet(message1);
+ TestUtil::ExpectClear(message2);
+ message1.Swap(&message2);
+ TestUtil::ExpectAllFieldsSet(message2);
+ TestUtil::ExpectClear(message1);
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithSelf) {
+ UNITTEST::TestAllTypes message;
+ TestUtil::SetAllFields(&message);
+ TestUtil::ExpectAllFieldsSet(message);
+ message.Swap(&message);
+ TestUtil::ExpectAllFieldsSet(message);
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithOther) {
+ UNITTEST::TestAllTypes message1, message2;
+
+ message1.set_optional_int32(123);
+ message1.set_optional_string("abc");
+ message1.mutable_optional_nested_message()->set_bb(1);
+ message1.set_optional_nested_enum(UNITTEST::TestAllTypes::FOO);
+ message1.add_repeated_int32(1);
+ message1.add_repeated_int32(2);
+ message1.add_repeated_string("a");
+ message1.add_repeated_string("b");
+ message1.add_repeated_nested_message()->set_bb(7);
+ message1.add_repeated_nested_message()->set_bb(8);
+ message1.add_repeated_nested_enum(UNITTEST::TestAllTypes::FOO);
+ message1.add_repeated_nested_enum(UNITTEST::TestAllTypes::BAR);
+
+ message2.set_optional_int32(456);
+ message2.set_optional_string("def");
+ message2.mutable_optional_nested_message()->set_bb(2);
+ message2.set_optional_nested_enum(UNITTEST::TestAllTypes::BAR);
+ message2.add_repeated_int32(3);
+ message2.add_repeated_string("c");
+ message2.add_repeated_nested_message()->set_bb(9);
+ message2.add_repeated_nested_enum(UNITTEST::TestAllTypes::BAZ);
+
+ message1.Swap(&message2);
+
+ EXPECT_EQ(456, message1.optional_int32());
+ EXPECT_EQ("def", message1.optional_string());
+ EXPECT_EQ(2, message1.optional_nested_message().bb());
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message1.optional_nested_enum());
+ ASSERT_EQ(1, message1.repeated_int32_size());
+ EXPECT_EQ(3, message1.repeated_int32(0));
+ ASSERT_EQ(1, message1.repeated_string_size());
+ EXPECT_EQ("c", message1.repeated_string(0));
+ ASSERT_EQ(1, message1.repeated_nested_message_size());
+ EXPECT_EQ(9, message1.repeated_nested_message(0).bb());
+ ASSERT_EQ(1, message1.repeated_nested_enum_size());
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, message1.repeated_nested_enum(0));
+
+ EXPECT_EQ(123, message2.optional_int32());
+ EXPECT_EQ("abc", message2.optional_string());
+ EXPECT_EQ(1, message2.optional_nested_message().bb());
+ EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message2.optional_nested_enum());
+ ASSERT_EQ(2, message2.repeated_int32_size());
+ EXPECT_EQ(1, message2.repeated_int32(0));
+ EXPECT_EQ(2, message2.repeated_int32(1));
+ ASSERT_EQ(2, message2.repeated_string_size());
+ EXPECT_EQ("a", message2.repeated_string(0));
+ EXPECT_EQ("b", message2.repeated_string(1));
+ ASSERT_EQ(2, message2.repeated_nested_message_size());
+ EXPECT_EQ(7, message2.repeated_nested_message(0).bb());
+ EXPECT_EQ(8, message2.repeated_nested_message(1).bb());
+ ASSERT_EQ(2, message2.repeated_nested_enum_size());
+ EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message2.repeated_nested_enum(0));
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message2.repeated_nested_enum(1));
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, ADLSwap) {
+ UNITTEST::TestAllTypes message1, message2;
+ TestUtil::SetAllFields(&message1);
+
+ // Note the address of one of the repeated fields, to verify it was swapped
+ // rather than copied.
+ const int32* addr = &message1.repeated_int32().Get(0);
+
+ using std::swap;
+ swap(message1, message2);
+
+ TestUtil::ExpectAllFieldsSet(message2);
+ TestUtil::ExpectClear(message1);
+
+ EXPECT_EQ(addr, &message2.repeated_int32().Get(0));
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, CopyConstructor) {
+ // All set.
+ {
+ UNITTEST::TestAllTypes message1;
+ TestUtil::SetAllFields(&message1);
+
+ UNITTEST::TestAllTypes message2(message1);
+ TestUtil::ExpectAllFieldsSet(message2);
+ }
+
+ // None set.
+ {
+ UNITTEST::TestAllTypes message1;
+ UNITTEST::TestAllTypes message2(message1);
+
+ EXPECT_FALSE(message1.has_optional_string());
+ EXPECT_FALSE(message2.has_optional_string());
+ EXPECT_EQ(message1.optional_string(), message2.optional_string());
+
+ EXPECT_FALSE(message1.has_optional_bytes());
+ EXPECT_FALSE(message2.has_optional_bytes());
+ EXPECT_EQ(message1.optional_bytes(), message2.optional_bytes());
+
+ EXPECT_FALSE(message1.has_optional_nested_message());
+ EXPECT_FALSE(message2.has_optional_nested_message());
+ EXPECT_EQ(&message1.optional_nested_message(),
+ &message2.optional_nested_message());
+
+ EXPECT_FALSE(message1.has_optional_foreign_message());
+ EXPECT_FALSE(message2.has_optional_foreign_message());
+ EXPECT_EQ(&message1.optional_foreign_message(),
+ &message2.optional_foreign_message());
+
+ EXPECT_FALSE(message1.has_optional_import_message());
+ EXPECT_FALSE(message2.has_optional_import_message());
+ EXPECT_EQ(&message1.optional_import_message(),
+ &message2.optional_import_message());
+
+ EXPECT_FALSE(message1.has_optional_public_import_message());
+ EXPECT_FALSE(message2.has_optional_public_import_message());
+ EXPECT_EQ(&message1.optional_public_import_message(),
+ &message2.optional_public_import_message());
+
+ EXPECT_FALSE(message1.has_optional_lazy_message());
+ EXPECT_FALSE(message2.has_optional_lazy_message());
+ EXPECT_EQ(&message1.optional_lazy_message(),
+ &message2.optional_lazy_message());
+ }
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, CopyConstructorWithArenas) {
+ Arena arena;
+ UNITTEST::TestAllTypes* message1 =
+ Arena::CreateMessage<UNITTEST::TestAllTypes>(&arena);
+ TestUtil::SetAllFields(message1);
+
+ UNITTEST::TestAllTypes message2_stack(*message1);
+ TestUtil::ExpectAllFieldsSet(message2_stack);
+
+ std::unique_ptr<UNITTEST::TestAllTypes> message2_heap(
+ new UNITTEST::TestAllTypes(*message1));
+ TestUtil::ExpectAllFieldsSet(*message2_heap);
+
+ arena.Reset();
+
+ // Verify that the copies are still intact.
+ TestUtil::ExpectAllFieldsSet(message2_stack);
+ TestUtil::ExpectAllFieldsSet(*message2_heap);
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, CopyAssignmentOperator) {
+ UNITTEST::TestAllTypes message1;
+ TestUtil::SetAllFields(&message1);
+
+ UNITTEST::TestAllTypes message2;
+ message2 = message1;
+ TestUtil::ExpectAllFieldsSet(message2);
+
+ // Make sure that self-assignment does something sane.
+ message2.operator=(message2);
+ TestUtil::ExpectAllFieldsSet(message2);
+}
+
+#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \
+ !defined(GOOGLE_PROTOBUF_NO_RTTI)
+TEST(GENERATED_MESSAGE_TEST_NAME, UpcastCopyFrom) {
+ // Test the CopyFrom method that takes in the generic const Message&
+ // parameter.
+ UNITTEST::TestAllTypes message1, message2;
+
+ TestUtil::SetAllFields(&message1);
+
+ const Message* source = implicit_cast<const Message*>(&message1);
+ message2.CopyFrom(*source);
+
+ TestUtil::ExpectAllFieldsSet(message2);
+}
+#endif
+
+#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
+
+TEST(GENERATED_MESSAGE_TEST_NAME, DynamicMessageCopyFrom) {
+ // Test copying from a DynamicMessage, which must fall back to using
+ // reflection.
+ UNITTEST::TestAllTypes message2;
+
+ // Construct a new version of the dynamic message via the factory.
+ DynamicMessageFactory factory;
+ std::unique_ptr<Message> message1;
+ message1.reset(factory.GetPrototype(
+ UNITTEST::TestAllTypes::descriptor())->New());
+
+ TestUtil::ReflectionTester reflection_tester(
+ UNITTEST::TestAllTypes::descriptor());
+ reflection_tester.SetAllFieldsViaReflection(message1.get());
+
+ message2.CopyFrom(*message1);
+
+ TestUtil::ExpectAllFieldsSet(message2);
+}
+
+#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
+
+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.
+ UNITTEST::TestAllTypes message1, message2;
+
+ TestUtil::SetAllFields(&message1);
+
+ // This field will test merging into an empty spot.
+ message2.set_optional_int32(message1.optional_int32());
+ message1.clear_optional_int32();
+
+ // This tests overwriting.
+ message2.set_optional_string(message1.optional_string());
+ message1.set_optional_string("something else");
+
+ // This tests concatenating.
+ message2.add_repeated_int32(message1.repeated_int32(1));
+ int32 i = message1.repeated_int32(0);
+ message1.clear_repeated_int32();
+ message1.add_repeated_int32(i);
+
+ message1.MergeFrom(message2);
+
+ TestUtil::ExpectAllFieldsSet(message1);
+}
+
+
+// Test the generated SerializeWithCachedSizesToArray(),
+TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToArray) {
+ UNITTEST::TestAllTypes message1, message2;
+ string data;
+ TestUtil::SetAllFields(&message1);
+ int size = message1.ByteSizeLong();
+ data.resize(size);
+ uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* end = message1.SerializeWithCachedSizesToArray(start);
+ EXPECT_EQ(size, end - start);
+ EXPECT_TRUE(message2.ParseFromString(data));
+ TestUtil::ExpectAllFieldsSet(message2);
+
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToArray) {
+ UNITTEST::TestPackedTypes packed_message1, packed_message2;
+ string packed_data;
+ 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* end = packed_message1.SerializeWithCachedSizesToArray(start);
+ EXPECT_EQ(packed_size, end - start);
+ EXPECT_TRUE(packed_message2.ParseFromString(packed_data));
+ TestUtil::ExpectPackedFieldsSet(packed_message2);
+}
+
+// Test the generated SerializeWithCachedSizes() by forcing the buffer to write
+// one byte at a time.
+TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToStream) {
+ UNITTEST::TestAllTypes message1, message2;
+ TestUtil::SetAllFields(&message1);
+ int size = message1.ByteSizeLong();
+ string data;
+ 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::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));
+ TestUtil::ExpectAllFieldsSet(message2);
+
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToStream) {
+ UNITTEST::TestPackedTypes message1, message2;
+ TestUtil::SetPackedFields(&message1);
+ int size = message1.ByteSizeLong();
+ string data;
+ 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::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));
+ TestUtil::ExpectPackedFieldsSet(message2);
+}
+
+
+TEST(GENERATED_MESSAGE_TEST_NAME, Required) {
+ // Test that IsInitialized() returns false if required fields are missing.
+ UNITTEST::TestRequired message;
+
+ EXPECT_FALSE(message.IsInitialized());
+ message.set_a(1);
+ EXPECT_FALSE(message.IsInitialized());
+ message.set_b(2);
+ EXPECT_FALSE(message.IsInitialized());
+ message.set_c(3);
+ EXPECT_TRUE(message.IsInitialized());
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, RequiredForeign) {
+ // Test that IsInitialized() returns false if required fields in nested
+ // messages are missing.
+ UNITTEST::TestRequiredForeign message;
+
+ EXPECT_TRUE(message.IsInitialized());
+
+ message.mutable_optional_message();
+ EXPECT_FALSE(message.IsInitialized());
+
+ message.mutable_optional_message()->set_a(1);
+ message.mutable_optional_message()->set_b(2);
+ message.mutable_optional_message()->set_c(3);
+ EXPECT_TRUE(message.IsInitialized());
+
+ message.add_repeated_message();
+ EXPECT_FALSE(message.IsInitialized());
+
+ message.mutable_repeated_message(0)->set_a(1);
+ message.mutable_repeated_message(0)->set_b(2);
+ message.mutable_repeated_message(0)->set_c(3);
+ EXPECT_TRUE(message.IsInitialized());
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, ForeignNested) {
+ // Test that TestAllTypes::NestedMessage can be embedded directly into
+ // another message.
+ UNITTEST::TestForeignNested message;
+
+ // If this compiles and runs without crashing, it must work. We have
+ // nothing more to test.
+ UNITTEST::TestAllTypes::NestedMessage* nested =
+ message.mutable_foreign_nested();
+ nested->set_bb(1);
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, ReallyLargeTagNumber) {
+ // Test that really large tag numbers don't break anything.
+ UNITTEST::TestReallyLargeTagNumber message1, message2;
+ string data;
+
+ // For the most part, if this compiles and runs then we're probably good.
+ // (The most likely cause for failure would be if something were attempting
+ // to allocate a lookup table of some sort using tag numbers as the index.)
+ // We'll try serializing just for fun.
+ message1.set_a(1234);
+ message1.set_bb(5678);
+ message1.SerializeToString(&data);
+ EXPECT_TRUE(message2.ParseFromString(data));
+ EXPECT_EQ(1234, message2.a());
+ EXPECT_EQ(5678, message2.bb());
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, MutualRecursion) {
+ // Test that mutually-recursive message types work.
+ UNITTEST::TestMutualRecursionA message;
+ UNITTEST::TestMutualRecursionA* nested = message.mutable_bb()->mutable_a();
+ UNITTEST::TestMutualRecursionA* nested2 = nested->mutable_bb()->mutable_a();
+
+ // Again, if the above compiles and runs, that's all we really have to
+ // test, but just for run we'll check that the system didn't somehow come
+ // up with a pointer loop...
+ EXPECT_NE(&message, nested);
+ EXPECT_NE(&message, nested2);
+ EXPECT_NE(nested, nested2);
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, CamelCaseFieldNames) {
+ // This test is mainly checking that the following compiles, which verifies
+ // that the field names were coerced to lower-case.
+ //
+ // Protocol buffers standard style is to use lowercase-with-underscores for
+ // field names. Some old proto1 .protos unfortunately used camel-case field
+ // names. In proto1, these names were forced to lower-case. So, we do the
+ // same thing in proto2.
+
+ UNITTEST::TestCamelCaseFieldNames message;
+
+ message.set_primitivefield(2);
+ message.set_stringfield("foo");
+ message.set_enumfield(UNITTEST::FOREIGN_FOO);
+ message.mutable_messagefield()->set_c(6);
+
+ message.add_repeatedprimitivefield(8);
+ message.add_repeatedstringfield("qux");
+ message.add_repeatedenumfield(UNITTEST::FOREIGN_BAR);
+ message.add_repeatedmessagefield()->set_c(15);
+
+ EXPECT_EQ(2, message.primitivefield());
+ EXPECT_EQ("foo", message.stringfield());
+ EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.enumfield());
+ EXPECT_EQ(6, message.messagefield().c());
+
+ EXPECT_EQ(8, message.repeatedprimitivefield(0));
+ EXPECT_EQ("qux", message.repeatedstringfield(0));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeatedenumfield(0));
+ EXPECT_EQ(15, message.repeatedmessagefield(0).c());
+}
+
+#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
+
+TEST(GENERATED_MESSAGE_TEST_NAME, TestOptimizedForSize) {
+ // We rely on the tests in reflection_ops_unittest and wire_format_unittest
+ // to really test that reflection-based methods work. Here we are mostly
+ // just making sure that TestOptimizedForSize actually builds and seems to
+ // function.
+
+ UNITTEST::TestOptimizedForSize message, message2;
+ message.set_i(1);
+ message.mutable_msg()->set_c(2);
+ message2.CopyFrom(message);
+ EXPECT_EQ(1, message2.i());
+ EXPECT_EQ(2, message2.msg().c());
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, TestEmbedOptimizedForSize) {
+ // Verifies that something optimized for speed can contain something optimized
+ // for size.
+
+ UNITTEST::TestEmbedOptimizedForSize message, message2;
+ message.mutable_optional_message()->set_i(1);
+ message.add_repeated_message()->mutable_msg()->set_c(2);
+ string data;
+ message.SerializeToString(&data);
+ ASSERT_TRUE(message2.ParseFromString(data));
+ EXPECT_EQ(1, message2.optional_message().i());
+ EXPECT_EQ(2, message2.repeated_message(0).msg().c());
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, TestSpaceUsed) {
+ UNITTEST::TestAllTypes message1;
+ // sizeof provides a lower bound on SpaceUsedLong().
+ EXPECT_LE(sizeof(UNITTEST::TestAllTypes), message1.SpaceUsedLong());
+ const size_t empty_message_size = message1.SpaceUsedLong();
+
+ // Setting primitive types shouldn't affect the space used.
+ message1.set_optional_int32(123);
+ message1.set_optional_int64(12345);
+ message1.set_optional_uint32(123);
+ message1.set_optional_uint64(12345);
+ EXPECT_EQ(empty_message_size, message1.SpaceUsedLong());
+
+ // On some STL implementations, setting the string to a small value should
+ // only increase SpaceUsedLong() by the size of a string object, though this
+ // is not true everywhere.
+ message1.set_optional_string("abc");
+ EXPECT_LE(empty_message_size + message1.optional_string().size(),
+ message1.SpaceUsedLong());
+
+ // Setting a string to a value larger than the string object itself should
+ // increase SpaceUsedLong(), because it cannot store the value internally.
+ message1.set_optional_string(string(sizeof(string) + 1, 'x'));
+ int min_expected_increase = message1.optional_string().capacity();
+ EXPECT_LE(empty_message_size + min_expected_increase,
+ message1.SpaceUsedLong());
+
+ size_t previous_size = message1.SpaceUsedLong();
+ // Adding an optional message should increase the size by the size of the
+ // nested message type. NestedMessage is simple enough (1 int field) that it
+ // is equal to sizeof(NestedMessage)
+ message1.mutable_optional_nested_message();
+ ASSERT_EQ(sizeof(UNITTEST::TestAllTypes::NestedMessage),
+ message1.optional_nested_message().SpaceUsedLong());
+ EXPECT_EQ(previous_size +
+ sizeof(UNITTEST::TestAllTypes::NestedMessage),
+ message1.SpaceUsedLong());
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, TestOneofSpaceUsed) {
+ UNITTEST::TestOneof2 message1;
+ EXPECT_LE(sizeof(UNITTEST::TestOneof2), message1.SpaceUsedLong());
+
+ const size_t empty_message_size = message1.SpaceUsedLong();
+ // Setting primitive types shouldn't affect the space used.
+ message1.set_foo_int(123);
+ message1.set_bar_int(12345);
+ EXPECT_EQ(empty_message_size, message1.SpaceUsedLong());
+
+ // Setting a string in oneof to a small value should only increase
+ // SpaceUsedLong() by the size of a string object.
+ message1.set_foo_string("abc");
+ EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsedLong());
+
+ // Setting a string in oneof to a value larger than the string object itself
+ // should increase SpaceUsedLong(), because it cannot store the value
+ // internally.
+ message1.set_foo_string(string(sizeof(string) + 1, 'x'));
+ int min_expected_increase = message1.foo_string().capacity() +
+ sizeof(string);
+ EXPECT_LE(empty_message_size + min_expected_increase,
+ message1.SpaceUsedLong());
+
+ // Setting a message in oneof should delete the other fields and increase the
+ // size by the size of the nested message type. NestedMessage is simple enough
+ // that it is equal to sizeof(NestedMessage)
+ message1.mutable_foo_message();
+ ASSERT_EQ(sizeof(UNITTEST::TestOneof2::NestedMessage),
+ message1.foo_message().SpaceUsedLong());
+ EXPECT_EQ(empty_message_size +
+ sizeof(UNITTEST::TestOneof2::NestedMessage),
+ message1.SpaceUsedLong());
+}
+
+#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
+
+
+TEST(GENERATED_MESSAGE_TEST_NAME, FieldConstantValues) {
+ UNITTEST::TestRequired message;
+ EXPECT_EQ(UNITTEST::TestAllTypes_NestedMessage::kBbFieldNumber, 1);
+ EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalInt32FieldNumber, 1);
+ EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalgroupFieldNumber, 16);
+ EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalNestedMessageFieldNumber, 18);
+ EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalNestedEnumFieldNumber, 21);
+ EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedInt32FieldNumber, 31);
+ EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedgroupFieldNumber, 46);
+ EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedNestedMessageFieldNumber, 48);
+ EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedNestedEnumFieldNumber, 51);
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, ExtensionConstantValues) {
+ EXPECT_EQ(UNITTEST::TestRequired::kSingleFieldNumber, 1000);
+ EXPECT_EQ(UNITTEST::TestRequired::kMultiFieldNumber, 1001);
+ EXPECT_EQ(UNITTEST::kOptionalInt32ExtensionFieldNumber, 1);
+ EXPECT_EQ(UNITTEST::kOptionalgroupExtensionFieldNumber, 16);
+ EXPECT_EQ(UNITTEST::kOptionalNestedMessageExtensionFieldNumber, 18);
+ EXPECT_EQ(UNITTEST::kOptionalNestedEnumExtensionFieldNumber, 21);
+ EXPECT_EQ(UNITTEST::kRepeatedInt32ExtensionFieldNumber, 31);
+ EXPECT_EQ(UNITTEST::kRepeatedgroupExtensionFieldNumber, 46);
+ EXPECT_EQ(UNITTEST::kRepeatedNestedMessageExtensionFieldNumber, 48);
+ EXPECT_EQ(UNITTEST::kRepeatedNestedEnumExtensionFieldNumber, 51);
+}
+
+TEST(GENERATED_MESSAGE_TEST_NAME, ParseFromTruncated) {
+ const string long_string = string(128, 'q');
+ FileDescriptorProto p;
+ p.add_extension()->set_name(long_string);
+ const string msg = p.SerializeAsString();
+ int successful_count = 0;
+ for (int i = 0; i <= msg.size(); i++) {
+ if (p.ParseFromArray(msg.c_str(), i)) {
+ ++successful_count;
+ }
+ }
+ // We don't really care about how often we succeeded.
+ // As long as we didn't crash, we're happy.
+ EXPECT_GE(successful_count, 1);
+}
+
+// ===================================================================
+
+TEST(GENERATED_ENUM_TEST_NAME, EnumValuesAsSwitchCases) {
+ // Test that our nested enum values can be used as switch cases. This test
+ // doesn't actually do anything, the proof that it works is that it
+ // compiles.
+ int i =0;
+ UNITTEST::TestAllTypes::NestedEnum a = UNITTEST::TestAllTypes::BAR;
+ switch (a) {
+ case UNITTEST::TestAllTypes::FOO:
+ i = 1;
+ break;
+ case UNITTEST::TestAllTypes::BAR:
+ i = 2;
+ break;
+ case UNITTEST::TestAllTypes::BAZ:
+ i = 3;
+ break;
+ case UNITTEST::TestAllTypes::NEG:
+ i = -1;
+ break;
+ // no default case: We want to make sure the compiler recognizes that
+ // all cases are covered. (GCC warns if you do not cover all cases of
+ // an enum in a switch.)
+ }
+
+ // Token check just for fun.
+ EXPECT_EQ(2, i);
+}
+
+TEST(GENERATED_ENUM_TEST_NAME, IsValidValue) {
+ // Test enum IsValidValue.
+ EXPECT_TRUE(UNITTEST::TestAllTypes::NestedEnum_IsValid(1));
+ EXPECT_TRUE(UNITTEST::TestAllTypes::NestedEnum_IsValid(2));
+ EXPECT_TRUE(UNITTEST::TestAllTypes::NestedEnum_IsValid(3));
+
+ EXPECT_FALSE(UNITTEST::TestAllTypes::NestedEnum_IsValid(0));
+ EXPECT_FALSE(UNITTEST::TestAllTypes::NestedEnum_IsValid(4));
+
+ // Make sure it also works when there are dups.
+ EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_IsValid(1));
+ EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_IsValid(2));
+ EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_IsValid(3));
+
+ EXPECT_FALSE(UNITTEST::TestEnumWithDupValue_IsValid(0));
+ EXPECT_FALSE(UNITTEST::TestEnumWithDupValue_IsValid(4));
+}
+
+TEST(GENERATED_ENUM_TEST_NAME, MinAndMax) {
+ EXPECT_EQ(UNITTEST::TestAllTypes::NEG,
+ UNITTEST::TestAllTypes::NestedEnum_MIN);
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAZ,
+ UNITTEST::TestAllTypes::NestedEnum_MAX);
+ EXPECT_EQ(4, UNITTEST::TestAllTypes::NestedEnum_ARRAYSIZE);
+
+ EXPECT_EQ(UNITTEST::FOREIGN_FOO, UNITTEST::ForeignEnum_MIN);
+ EXPECT_EQ(UNITTEST::FOREIGN_BAZ, UNITTEST::ForeignEnum_MAX);
+ EXPECT_EQ(7, UNITTEST::ForeignEnum_ARRAYSIZE);
+
+ EXPECT_EQ(1, UNITTEST::TestEnumWithDupValue_MIN);
+ EXPECT_EQ(3, UNITTEST::TestEnumWithDupValue_MAX);
+ EXPECT_EQ(4, UNITTEST::TestEnumWithDupValue_ARRAYSIZE);
+
+ EXPECT_EQ(UNITTEST::SPARSE_E, UNITTEST::TestSparseEnum_MIN);
+ EXPECT_EQ(UNITTEST::SPARSE_C, UNITTEST::TestSparseEnum_MAX);
+ EXPECT_EQ(12589235, UNITTEST::TestSparseEnum_ARRAYSIZE);
+
+ // Make sure we can take the address of _MIN, _MAX and _ARRAYSIZE.
+ void* null_pointer = 0; // NULL may be integer-type, not pointer-type.
+ EXPECT_NE(null_pointer, &UNITTEST::TestAllTypes::NestedEnum_MIN);
+ EXPECT_NE(null_pointer, &UNITTEST::TestAllTypes::NestedEnum_MAX);
+ EXPECT_NE(null_pointer, &UNITTEST::TestAllTypes::NestedEnum_ARRAYSIZE);
+
+ EXPECT_NE(null_pointer, &UNITTEST::ForeignEnum_MIN);
+ EXPECT_NE(null_pointer, &UNITTEST::ForeignEnum_MAX);
+ EXPECT_NE(null_pointer, &UNITTEST::ForeignEnum_ARRAYSIZE);
+
+ // Make sure we can use _MIN and _MAX as switch cases.
+ switch (UNITTEST::SPARSE_A) {
+ case UNITTEST::TestSparseEnum_MIN:
+ case UNITTEST::TestSparseEnum_MAX:
+ break;
+ default:
+ break;
+ }
+}
+
+#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
+
+TEST(GENERATED_ENUM_TEST_NAME, Name) {
+ // "Names" in the presence of dup values are a bit arbitrary.
+ EXPECT_EQ("FOO1", UNITTEST::TestEnumWithDupValue_Name(UNITTEST::FOO1));
+ EXPECT_EQ("FOO1", UNITTEST::TestEnumWithDupValue_Name(UNITTEST::FOO2));
+
+ EXPECT_EQ("SPARSE_A", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_A));
+ EXPECT_EQ("SPARSE_B", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_B));
+ EXPECT_EQ("SPARSE_C", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_C));
+ EXPECT_EQ("SPARSE_D", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_D));
+ EXPECT_EQ("SPARSE_E", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_E));
+ EXPECT_EQ("SPARSE_F", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_F));
+ EXPECT_EQ("SPARSE_G", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_G));
+}
+
+TEST(GENERATED_ENUM_TEST_NAME, Parse) {
+ UNITTEST::TestEnumWithDupValue dup_value = UNITTEST::FOO1;
+ EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_Parse("FOO1", &dup_value));
+ EXPECT_EQ(UNITTEST::FOO1, dup_value);
+ EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_Parse("FOO2", &dup_value));
+ EXPECT_EQ(UNITTEST::FOO2, dup_value);
+ EXPECT_FALSE(UNITTEST::TestEnumWithDupValue_Parse("FOO", &dup_value));
+}
+
+TEST(GENERATED_ENUM_TEST_NAME, GetEnumDescriptor) {
+ EXPECT_EQ(UNITTEST::TestAllTypes::NestedEnum_descriptor(),
+ GetEnumDescriptor<UNITTEST::TestAllTypes::NestedEnum>());
+ EXPECT_EQ(UNITTEST::ForeignEnum_descriptor(),
+ GetEnumDescriptor<UNITTEST::ForeignEnum>());
+ EXPECT_EQ(UNITTEST::TestEnumWithDupValue_descriptor(),
+ GetEnumDescriptor<UNITTEST::TestEnumWithDupValue>());
+ EXPECT_EQ(UNITTEST::TestSparseEnum_descriptor(),
+ GetEnumDescriptor<UNITTEST::TestSparseEnum>());
+}
+
+enum NonProtoEnum {
+ kFoo = 1,
+};
+
+TEST(GENERATED_ENUM_TEST_NAME, IsProtoEnumTypeTrait) {
+ EXPECT_TRUE(is_proto_enum<UNITTEST::TestAllTypes::NestedEnum>::value);
+ EXPECT_TRUE(is_proto_enum<UNITTEST::ForeignEnum>::value);
+ EXPECT_TRUE(is_proto_enum<UNITTEST::TestEnumWithDupValue>::value);
+ EXPECT_TRUE(is_proto_enum<UNITTEST::TestSparseEnum>::value);
+
+ EXPECT_FALSE(is_proto_enum<int>::value);
+ EXPECT_FALSE(is_proto_enum<NonProtoEnum>::value);
+}
+
+#endif // PROTOBUF_TEST_NO_DESCRIPTORS
+
+// ===================================================================
+
+#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
+
+// Support code for testing services.
+class GENERATED_SERVICE_TEST_NAME : public testing::Test {
+ protected:
+ class MockTestService : public UNITTEST::TestService {
+ public:
+ MockTestService()
+ : called_(false),
+ method_(""),
+ controller_(NULL),
+ request_(NULL),
+ response_(NULL),
+ done_(NULL) {}
+
+ ~MockTestService() {}
+
+ void Reset() { called_ = false; }
+
+ // implements TestService ----------------------------------------
+
+ void Foo(RpcController* controller,
+ const UNITTEST::FooRequest* request,
+ UNITTEST::FooResponse* response,
+ Closure* done) {
+ ASSERT_FALSE(called_);
+ called_ = true;
+ method_ = "Foo";
+ controller_ = controller;
+ request_ = request;
+ response_ = response;
+ done_ = done;
+ }
+
+ void Bar(RpcController* controller,
+ const UNITTEST::BarRequest* request,
+ UNITTEST::BarResponse* response,
+ Closure* done) {
+ ASSERT_FALSE(called_);
+ called_ = true;
+ method_ = "Bar";
+ controller_ = controller;
+ request_ = request;
+ response_ = response;
+ done_ = done;
+ }
+
+ // ---------------------------------------------------------------
+
+ bool called_;
+ string method_;
+ RpcController* controller_;
+ const Message* request_;
+ Message* response_;
+ Closure* done_;
+ };
+
+ class MockRpcChannel : public RpcChannel {
+ public:
+ MockRpcChannel()
+ : called_(false),
+ method_(NULL),
+ controller_(NULL),
+ request_(NULL),
+ response_(NULL),
+ done_(NULL),
+ destroyed_(NULL) {}
+
+ ~MockRpcChannel() {
+ if (destroyed_ != NULL) *destroyed_ = true;
+ }
+
+ void Reset() { called_ = false; }
+
+ // implements TestService ----------------------------------------
+
+ void CallMethod(const MethodDescriptor* method,
+ RpcController* controller,
+ const Message* request,
+ Message* response,
+ Closure* done) {
+ ASSERT_FALSE(called_);
+ called_ = true;
+ method_ = method;
+ controller_ = controller;
+ request_ = request;
+ response_ = response;
+ done_ = done;
+ }
+
+ // ---------------------------------------------------------------
+
+ bool called_;
+ const MethodDescriptor* method_;
+ RpcController* controller_;
+ const Message* request_;
+ Message* response_;
+ Closure* done_;
+ bool* destroyed_;
+ };
+
+ class MockController : public RpcController {
+ public:
+ void Reset() {
+ ADD_FAILURE() << "Reset() not expected during this test.";
+ }
+ bool Failed() const {
+ ADD_FAILURE() << "Failed() not expected during this test.";
+ return false;
+ }
+ string ErrorText() const {
+ ADD_FAILURE() << "ErrorText() not expected during this test.";
+ return "";
+ }
+ void StartCancel() {
+ ADD_FAILURE() << "StartCancel() not expected during this test.";
+ }
+ void SetFailed(const string& reason) {
+ ADD_FAILURE() << "SetFailed() not expected during this test.";
+ }
+ bool IsCanceled() const {
+ ADD_FAILURE() << "IsCanceled() not expected during this test.";
+ return false;
+ }
+ void NotifyOnCancel(Closure* callback) {
+ ADD_FAILURE() << "NotifyOnCancel() not expected during this test.";
+ }
+ };
+
+ GENERATED_SERVICE_TEST_NAME()
+ : descriptor_(UNITTEST::TestService::descriptor()),
+ foo_(descriptor_->FindMethodByName("Foo")),
+ bar_(descriptor_->FindMethodByName("Bar")),
+ stub_(&mock_channel_),
+ done_(::google::protobuf::NewPermanentCallback(&DoNothing)) {}
+
+ virtual void SetUp() {
+ ASSERT_TRUE(foo_ != NULL);
+ ASSERT_TRUE(bar_ != NULL);
+ }
+
+ const ServiceDescriptor* descriptor_;
+ const MethodDescriptor* foo_;
+ const MethodDescriptor* bar_;
+
+ MockTestService mock_service_;
+ MockController mock_controller_;
+
+ MockRpcChannel mock_channel_;
+ UNITTEST::TestService::Stub stub_;
+
+ // Just so we don't have to re-define these with every test.
+ UNITTEST::FooRequest foo_request_;
+ UNITTEST::FooResponse foo_response_;
+ UNITTEST::BarRequest bar_request_;
+ UNITTEST::BarResponse bar_response_;
+ std::unique_ptr<Closure> done_;
+};
+
+TEST_F(GENERATED_SERVICE_TEST_NAME, GetDescriptor) {
+ // Test that GetDescriptor() works.
+
+ EXPECT_EQ(descriptor_, mock_service_.GetDescriptor());
+}
+
+TEST_F(GENERATED_SERVICE_TEST_NAME, GetChannel) {
+ EXPECT_EQ(&mock_channel_, stub_.channel());
+}
+
+TEST_F(GENERATED_SERVICE_TEST_NAME, OwnsChannel) {
+ MockRpcChannel* channel = new MockRpcChannel;
+ bool destroyed = false;
+ channel->destroyed_ = &destroyed;
+
+ {
+ UNITTEST::TestService::Stub owning_stub(channel,
+ Service::STUB_OWNS_CHANNEL);
+ EXPECT_FALSE(destroyed);
+ }
+
+ EXPECT_TRUE(destroyed);
+}
+
+TEST_F(GENERATED_SERVICE_TEST_NAME, CallMethod) {
+ // Test that CallMethod() works.
+
+ // Call Foo() via CallMethod().
+ mock_service_.CallMethod(foo_, &mock_controller_,
+ &foo_request_, &foo_response_, done_.get());
+
+ ASSERT_TRUE(mock_service_.called_);
+
+ EXPECT_EQ("Foo" , mock_service_.method_ );
+ EXPECT_EQ(&mock_controller_, mock_service_.controller_);
+ EXPECT_EQ(&foo_request_ , mock_service_.request_ );
+ EXPECT_EQ(&foo_response_ , mock_service_.response_ );
+ EXPECT_EQ(done_.get() , mock_service_.done_ );
+
+ // Try again, but call Bar() instead.
+ mock_service_.Reset();
+ mock_service_.CallMethod(bar_, &mock_controller_,
+ &bar_request_, &bar_response_, done_.get());
+
+ ASSERT_TRUE(mock_service_.called_);
+ EXPECT_EQ("Bar", mock_service_.method_);
+}
+
+TEST_F(GENERATED_SERVICE_TEST_NAME, CallMethodTypeFailure) {
+ // Verify death if we call Foo() with Bar's message types.
+
+#ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet
+ EXPECT_DEBUG_DEATH(
+ mock_service_.CallMethod(foo_, &mock_controller_,
+ &foo_request_, &bar_response_, done_.get()),
+ "dynamic_cast");
+
+ mock_service_.Reset();
+ EXPECT_DEBUG_DEATH(
+ mock_service_.CallMethod(foo_, &mock_controller_,
+ &bar_request_, &foo_response_, done_.get()),
+ "dynamic_cast");
+#endif // PROTOBUF_HAS_DEATH_TEST
+}
+
+TEST_F(GENERATED_SERVICE_TEST_NAME, GetPrototypes) {
+ // Test Get{Request,Response}Prototype() methods.
+
+ EXPECT_EQ(&UNITTEST::FooRequest::default_instance(),
+ &mock_service_.GetRequestPrototype(foo_));
+ EXPECT_EQ(&UNITTEST::BarRequest::default_instance(),
+ &mock_service_.GetRequestPrototype(bar_));
+
+ EXPECT_EQ(&UNITTEST::FooResponse::default_instance(),
+ &mock_service_.GetResponsePrototype(foo_));
+ EXPECT_EQ(&UNITTEST::BarResponse::default_instance(),
+ &mock_service_.GetResponsePrototype(bar_));
+}
+
+TEST_F(GENERATED_SERVICE_TEST_NAME, Stub) {
+ // Test that the stub class works.
+
+ // Call Foo() via the stub.
+ stub_.Foo(&mock_controller_, &foo_request_, &foo_response_, done_.get());
+
+ ASSERT_TRUE(mock_channel_.called_);
+
+ EXPECT_EQ(foo_ , mock_channel_.method_ );
+ EXPECT_EQ(&mock_controller_, mock_channel_.controller_);
+ EXPECT_EQ(&foo_request_ , mock_channel_.request_ );
+ EXPECT_EQ(&foo_response_ , mock_channel_.response_ );
+ EXPECT_EQ(done_.get() , mock_channel_.done_ );
+
+ // Call Bar() via the stub.
+ mock_channel_.Reset();
+ stub_.Bar(&mock_controller_, &bar_request_, &bar_response_, done_.get());
+
+ ASSERT_TRUE(mock_channel_.called_);
+ EXPECT_EQ(bar_, mock_channel_.method_);
+}
+
+TEST_F(GENERATED_SERVICE_TEST_NAME, NotImplemented) {
+ // Test that failing to implement a method of a service causes it to fail
+ // with a "not implemented" error message.
+
+ // A service which doesn't implement any methods.
+ class UnimplementedService : public UNITTEST::TestService {
+ public:
+ UnimplementedService() {}
+ };
+
+ UnimplementedService unimplemented_service;
+
+ // And a controller which expects to get a "not implemented" error.
+ class ExpectUnimplementedController : public MockController {
+ public:
+ ExpectUnimplementedController() : called_(false) {}
+
+ void SetFailed(const string& reason) {
+ EXPECT_FALSE(called_);
+ called_ = true;
+ EXPECT_EQ("Method Foo() not implemented.", reason);
+ }
+
+ bool called_;
+ };
+
+ ExpectUnimplementedController controller;
+
+ // Call Foo.
+ unimplemented_service.Foo(&controller, &foo_request_, &foo_response_,
+ done_.get());
+
+ EXPECT_TRUE(controller.called_);
+}
+
+// ===================================================================
+
+class OneofTest : public testing::Test {
+ protected:
+ virtual void SetUp() {
+ }
+
+ void ExpectEnumCasesWork(const UNITTEST::TestOneof2 &message) {
+ switch (message.foo_case()) {
+ case UNITTEST::TestOneof2::kFooInt:
+ EXPECT_TRUE(message.has_foo_int());
+ break;
+ case UNITTEST::TestOneof2::kFooString:
+ EXPECT_TRUE(message.has_foo_string());
+ break;
+ case UNITTEST::TestOneof2::kFooCord:
+ EXPECT_TRUE(message.has_foo_cord());
+ break;
+ case UNITTEST::TestOneof2::kFooStringPiece:
+ EXPECT_TRUE(message.has_foo_string_piece());
+ break;
+ case UNITTEST::TestOneof2::kFooBytes:
+ EXPECT_TRUE(message.has_foo_bytes());
+ break;
+ case UNITTEST::TestOneof2::kFooEnum:
+ EXPECT_TRUE(message.has_foo_enum());
+ break;
+ case UNITTEST::TestOneof2::kFooMessage:
+ EXPECT_TRUE(message.has_foo_message());
+ break;
+ case UNITTEST::TestOneof2::kFoogroup:
+ EXPECT_TRUE(message.has_foogroup());
+ break;
+ case UNITTEST::TestOneof2::kFooLazyMessage:
+ EXPECT_TRUE(message.has_foo_lazy_message());
+ break;
+ case UNITTEST::TestOneof2::FOO_NOT_SET:
+ break;
+ }
+ }
+};
+
+TEST_F(OneofTest, SettingOneFieldClearsOthers) {
+ UNITTEST::TestOneof2 message;
+
+ message.set_foo_int(123);
+ EXPECT_TRUE(message.has_foo_int());
+ TestUtil::ExpectAtMostOneFieldSetInOneof(message);
+
+ message.set_foo_string("foo");
+ EXPECT_TRUE(message.has_foo_string());
+ TestUtil::ExpectAtMostOneFieldSetInOneof(message);
+
+
+ message.set_foo_bytes("qux");
+ EXPECT_TRUE(message.has_foo_bytes());
+ TestUtil::ExpectAtMostOneFieldSetInOneof(message);
+
+ message.set_foo_enum(UNITTEST::TestOneof2::FOO);
+ EXPECT_TRUE(message.has_foo_enum());
+ TestUtil::ExpectAtMostOneFieldSetInOneof(message);
+
+ message.mutable_foo_message()->set_qux_int(234);
+ EXPECT_TRUE(message.has_foo_message());
+ TestUtil::ExpectAtMostOneFieldSetInOneof(message);
+
+ message.mutable_foogroup()->set_a(345);
+ EXPECT_TRUE(message.has_foogroup());
+ TestUtil::ExpectAtMostOneFieldSetInOneof(message);
+
+
+ // we repeat this because we didn't test if this properly clears other fields
+ // at the beginning.
+ message.set_foo_int(123);
+ EXPECT_TRUE(message.has_foo_int());
+ TestUtil::ExpectAtMostOneFieldSetInOneof(message);
+}
+
+TEST_F(OneofTest, EnumCases) {
+ UNITTEST::TestOneof2 message;
+
+ message.set_foo_int(123);
+ ExpectEnumCasesWork(message);
+ message.set_foo_string("foo");
+ ExpectEnumCasesWork(message);
+ message.set_foo_bytes("qux");
+ ExpectEnumCasesWork(message);
+ message.set_foo_enum(UNITTEST::TestOneof2::FOO);
+ ExpectEnumCasesWork(message);
+ message.mutable_foo_message()->set_qux_int(234);
+ ExpectEnumCasesWork(message);
+ message.mutable_foogroup()->set_a(345);
+ ExpectEnumCasesWork(message);
+}
+
+TEST_F(OneofTest, PrimitiveType) {
+ UNITTEST::TestOneof2 message;
+ // Unset field returns default value
+ EXPECT_EQ(message.foo_int(), 0);
+
+ message.set_foo_int(123);
+ EXPECT_TRUE(message.has_foo_int());
+ EXPECT_EQ(message.foo_int(), 123);
+ message.clear_foo_int();
+ EXPECT_FALSE(message.has_foo_int());
+}
+
+TEST_F(OneofTest, EnumType) {
+ UNITTEST::TestOneof2 message;
+ // Unset field returns default value
+ EXPECT_EQ(message.foo_enum(), 1);
+
+ message.set_foo_enum(UNITTEST::TestOneof2::FOO);
+ EXPECT_TRUE(message.has_foo_enum());
+ EXPECT_EQ(message.foo_enum(), UNITTEST::TestOneof2::FOO);
+ message.clear_foo_enum();
+ EXPECT_FALSE(message.has_foo_enum());
+}
+
+TEST_F(OneofTest, SetString) {
+ // Check that setting a string field in various ways works
+ UNITTEST::TestOneof2 message;
+
+ // Unset field returns default value
+ EXPECT_EQ(message.foo_string(), "");
+
+ message.set_foo_string("foo");
+ EXPECT_TRUE(message.has_foo_string());
+ EXPECT_EQ(message.foo_string(), "foo");
+ message.clear_foo_string();
+ EXPECT_FALSE(message.has_foo_string());
+
+ message.set_foo_string(string("bar"));
+ EXPECT_TRUE(message.has_foo_string());
+ EXPECT_EQ(message.foo_string(), "bar");
+ message.clear_foo_string();
+ EXPECT_FALSE(message.has_foo_string());
+
+
+ message.set_foo_string("qux", 3);
+ EXPECT_TRUE(message.has_foo_string());
+ EXPECT_EQ(message.foo_string(), "qux");
+ message.clear_foo_string();
+ EXPECT_FALSE(message.has_foo_string());
+
+ message.mutable_foo_string()->assign("quux");
+ EXPECT_TRUE(message.has_foo_string());
+ EXPECT_EQ(message.foo_string(), "quux");
+ message.clear_foo_string();
+ EXPECT_FALSE(message.has_foo_string());
+
+ message.set_foo_string("corge");
+ EXPECT_TRUE(message.has_foo_string());
+ EXPECT_EQ(message.foo_string(), "corge");
+ message.clear_foo_string();
+ EXPECT_FALSE(message.has_foo_string());
+}
+
+TEST_F(OneofTest, ReleaseString) {
+ // Check that release_foo() starts out NULL, and gives us a value
+ // that we can delete after it's been set.
+ UNITTEST::TestOneof2 message;
+
+ EXPECT_EQ(NULL, message.release_foo_string());
+ EXPECT_FALSE(message.has_foo_string());
+
+ message.set_foo_string("blah");
+ EXPECT_TRUE(message.has_foo_string());
+ std::unique_ptr<string> str(message.release_foo_string());
+ EXPECT_FALSE(message.has_foo_string());
+ ASSERT_TRUE(str != NULL);
+ EXPECT_EQ("blah", *str);
+
+ EXPECT_EQ(NULL, message.release_foo_string());
+ EXPECT_FALSE(message.has_foo_string());
+}
+
+TEST_F(OneofTest, SetAllocatedString) {
+ // Check that set_allocated_foo() works for strings.
+ UNITTEST::TestOneof2 message;
+
+ EXPECT_FALSE(message.has_foo_string());
+ const string kHello("hello");
+ message.set_foo_string(kHello);
+ EXPECT_TRUE(message.has_foo_string());
+
+ message.set_allocated_foo_string(NULL);
+ EXPECT_FALSE(message.has_foo_string());
+ EXPECT_EQ("", message.foo_string());
+
+ message.set_allocated_foo_string(new string(kHello));
+ EXPECT_TRUE(message.has_foo_string());
+ EXPECT_EQ(kHello, message.foo_string());
+}
+
+
+TEST_F(OneofTest, SetMessage) {
+ // Check that setting a message field works
+ UNITTEST::TestOneof2 message;
+
+ // Unset field returns default instance
+ EXPECT_EQ(&message.foo_message(),
+ &UNITTEST::TestOneof2_NestedMessage::default_instance());
+ EXPECT_EQ(message.foo_message().qux_int(), 0);
+
+ message.mutable_foo_message()->set_qux_int(234);
+ EXPECT_TRUE(message.has_foo_message());
+ EXPECT_EQ(message.foo_message().qux_int(), 234);
+ message.clear_foo_message();
+ EXPECT_FALSE(message.has_foo_message());
+}
+
+TEST_F(OneofTest, ReleaseMessage) {
+ // Check that release_foo() starts out NULL, and gives us a value
+ // that we can delete after it's been set.
+ UNITTEST::TestOneof2 message;
+
+ EXPECT_EQ(NULL, message.release_foo_message());
+ EXPECT_FALSE(message.has_foo_message());
+
+ message.mutable_foo_message()->set_qux_int(1);
+ EXPECT_TRUE(message.has_foo_message());
+ std::unique_ptr<UNITTEST::TestOneof2_NestedMessage> mes(
+ message.release_foo_message());
+ EXPECT_FALSE(message.has_foo_message());
+ ASSERT_TRUE(mes != NULL);
+ EXPECT_EQ(1, mes->qux_int());
+
+ EXPECT_EQ(NULL, message.release_foo_message());
+ EXPECT_FALSE(message.has_foo_message());
+}
+
+TEST_F(OneofTest, SetAllocatedMessage) {
+ // Check that set_allocated_foo() works for messages.
+ UNITTEST::TestOneof2 message;
+
+ EXPECT_FALSE(message.has_foo_message());
+
+ message.mutable_foo_message()->set_qux_int(1);
+ EXPECT_TRUE(message.has_foo_message());
+
+ message.set_allocated_foo_message(NULL);
+ EXPECT_FALSE(message.has_foo_message());
+ EXPECT_EQ(&message.foo_message(),
+ &UNITTEST::TestOneof2_NestedMessage::default_instance());
+
+ message.mutable_foo_message()->set_qux_int(1);
+ UNITTEST::TestOneof2_NestedMessage* mes = message.release_foo_message();
+ ASSERT_TRUE(mes != NULL);
+ EXPECT_FALSE(message.has_foo_message());
+
+ message.set_allocated_foo_message(mes);
+ EXPECT_TRUE(message.has_foo_message());
+ EXPECT_EQ(1, message.foo_message().qux_int());
+}
+
+
+TEST_F(OneofTest, Clear) {
+ UNITTEST::TestOneof2 message;
+
+ message.set_foo_int(1);
+ EXPECT_TRUE(message.has_foo_int());
+ message.clear_foo_int();
+ EXPECT_FALSE(message.has_foo_int());
+}
+
+TEST_F(OneofTest, Defaults) {
+ UNITTEST::TestOneof2 message;
+
+ EXPECT_FALSE(message.has_foo_int());
+ EXPECT_EQ(message.foo_int(), 0);
+
+ EXPECT_FALSE(message.has_foo_string());
+ EXPECT_EQ(message.foo_string(), "");
+
+
+ EXPECT_FALSE(message.has_foo_bytes());
+ EXPECT_EQ(message.foo_bytes(), "");
+
+ EXPECT_FALSE(message.has_foo_enum());
+ EXPECT_EQ(message.foo_enum(), 1);
+
+ EXPECT_FALSE(message.has_foo_message());
+ EXPECT_EQ(message.foo_message().qux_int(), 0);
+
+ EXPECT_FALSE(message.has_foogroup());
+ EXPECT_EQ(message.foogroup().a(), 0);
+
+
+ EXPECT_FALSE(message.has_bar_int());
+ EXPECT_EQ(message.bar_int(), 5);
+
+ EXPECT_FALSE(message.has_bar_string());
+ EXPECT_EQ(message.bar_string(), "STRING");
+
+
+ EXPECT_FALSE(message.has_bar_bytes());
+ EXPECT_EQ(message.bar_bytes(), "BYTES");
+
+ EXPECT_FALSE(message.has_bar_enum());
+ EXPECT_EQ(message.bar_enum(), 2);
+}
+
+TEST_F(OneofTest, SwapWithEmpty) {
+ UNITTEST::TestOneof2 message1, message2;
+ message1.set_foo_string("FOO");
+ EXPECT_TRUE(message1.has_foo_string());
+ message1.Swap(&message2);
+ EXPECT_FALSE(message1.has_foo_string());
+ EXPECT_TRUE(message2.has_foo_string());
+ EXPECT_EQ(message2.foo_string(), "FOO");
+}
+
+TEST_F(OneofTest, SwapWithSelf) {
+ UNITTEST::TestOneof2 message;
+ message.set_foo_string("FOO");
+ EXPECT_TRUE(message.has_foo_string());
+ message.Swap(&message);
+ EXPECT_TRUE(message.has_foo_string());
+ EXPECT_EQ(message.foo_string(), "FOO");
+}
+
+TEST_F(OneofTest, SwapBothHasFields) {
+ UNITTEST::TestOneof2 message1, message2;
+
+ message1.set_foo_string("FOO");
+ EXPECT_TRUE(message1.has_foo_string());
+ message2.mutable_foo_message()->set_qux_int(1);
+ EXPECT_TRUE(message2.has_foo_message());
+
+ message1.Swap(&message2);
+ EXPECT_FALSE(message1.has_foo_string());
+ EXPECT_FALSE(message2.has_foo_message());
+ EXPECT_TRUE(message1.has_foo_message());
+ EXPECT_EQ(message1.foo_message().qux_int(), 1);
+ EXPECT_TRUE(message2.has_foo_string());
+ EXPECT_EQ(message2.foo_string(), "FOO");
+}
+
+TEST_F(OneofTest, CopyConstructor) {
+ UNITTEST::TestOneof2 message1;
+ message1.set_foo_bytes("FOO");
+
+ UNITTEST::TestOneof2 message2(message1);
+ EXPECT_TRUE(message2.has_foo_bytes());
+ EXPECT_EQ(message2.foo_bytes(), "FOO");
+}
+
+TEST_F(OneofTest, CopyFrom) {
+ UNITTEST::TestOneof2 message1, message2;
+ message1.set_foo_enum(UNITTEST::TestOneof2::BAR);
+ EXPECT_TRUE(message1.has_foo_enum());
+
+ message2.CopyFrom(message1);
+ EXPECT_TRUE(message2.has_foo_enum());
+ EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::BAR);
+
+ // Copying from self should be a no-op.
+ message2.CopyFrom(message2);
+ EXPECT_TRUE(message2.has_foo_enum());
+ EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::BAR);
+}
+
+TEST_F(OneofTest, CopyAssignmentOperator) {
+ UNITTEST::TestOneof2 message1;
+ message1.mutable_foo_message()->set_qux_int(123);
+ EXPECT_TRUE(message1.has_foo_message());
+
+ UNITTEST::TestOneof2 message2;
+ message2 = message1;
+ EXPECT_EQ(message2.foo_message().qux_int(), 123);
+
+ // Make sure that self-assignment does something sane.
+ message2 = message2;
+ EXPECT_EQ(message2.foo_message().qux_int(), 123);
+}
+
+TEST_F(OneofTest, UpcastCopyFrom) {
+ // Test the CopyFrom method that takes in the generic const Message&
+ // parameter.
+ UNITTEST::TestOneof2 message1, message2;
+ message1.mutable_foogroup()->set_a(123);
+ EXPECT_TRUE(message1.has_foogroup());
+
+ const Message* source = implicit_cast<const Message*>(&message1);
+ message2.CopyFrom(*source);
+
+ EXPECT_TRUE(message2.has_foogroup());
+ EXPECT_EQ(message2.foogroup().a(), 123);
+}
+
+// Test the generated SerializeWithCachedSizesToArray(),
+// This indirectly tests MergePartialFromCodedStream()
+// We have to test each field type separately because we cannot set them at the
+// same time
+TEST_F(OneofTest, SerializationToArray) {
+ // Primitive type
+ {
+ UNITTEST::TestOneof2 message1, message2;
+ string data;
+ message1.set_foo_int(123);
+ int size = message1.ByteSizeLong();
+ data.resize(size);
+ uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* end = message1.SerializeWithCachedSizesToArray(start);
+ EXPECT_EQ(size, end - start);
+ EXPECT_TRUE(message2.ParseFromString(data));
+ EXPECT_EQ(message2.foo_int(), 123);
+ }
+
+ // String
+ {
+ UNITTEST::TestOneof2 message1, message2;
+ string data;
+ message1.set_foo_string("foo");
+ int size = message1.ByteSizeLong();
+ data.resize(size);
+ uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* end = message1.SerializeWithCachedSizesToArray(start);
+ EXPECT_EQ(size, end - start);
+ EXPECT_TRUE(message2.ParseFromString(data));
+ EXPECT_EQ(message2.foo_string(), "foo");
+ }
+
+
+ // Bytes
+ {
+ UNITTEST::TestOneof2 message1, message2;
+ string data;
+ message1.set_foo_bytes("qux");
+ int size = message1.ByteSizeLong();
+ data.resize(size);
+ uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* end = message1.SerializeWithCachedSizesToArray(start);
+ EXPECT_EQ(size, end - start);
+ EXPECT_TRUE(message2.ParseFromString(data));
+ EXPECT_EQ(message2.foo_bytes(), "qux");
+ }
+
+ // Enum
+ {
+ UNITTEST::TestOneof2 message1, message2;
+ string data;
+ message1.set_foo_enum(UNITTEST::TestOneof2::FOO);
+ int size = message1.ByteSizeLong();
+ data.resize(size);
+ uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* end = message1.SerializeWithCachedSizesToArray(start);
+ EXPECT_EQ(size, end - start);
+ EXPECT_TRUE(message2.ParseFromString(data));
+ EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO);
+ }
+
+ // Message
+ {
+ UNITTEST::TestOneof2 message1, message2;
+ string data;
+ 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* end = message1.SerializeWithCachedSizesToArray(start);
+ EXPECT_EQ(size, end - start);
+ EXPECT_TRUE(message2.ParseFromString(data));
+ EXPECT_EQ(message2.foo_message().qux_int(), 234);
+ }
+
+ // Group
+ {
+ UNITTEST::TestOneof2 message1, message2;
+ string data;
+ message1.mutable_foogroup()->set_a(345);
+ int size = message1.ByteSizeLong();
+ data.resize(size);
+ uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* end = message1.SerializeWithCachedSizesToArray(start);
+ EXPECT_EQ(size, end - start);
+ EXPECT_TRUE(message2.ParseFromString(data));
+ EXPECT_EQ(message2.foogroup().a(), 345);
+ }
+
+}
+
+// Test the generated SerializeWithCachedSizes() by forcing the buffer to write
+// one byte at a time.
+// This indirectly tests MergePartialFromCodedStream()
+// We have to test each field type separately because we cannot set them at the
+// same time
+TEST_F(OneofTest, SerializationToStream) {
+ // Primitive type
+ {
+ UNITTEST::TestOneof2 message1, message2;
+ string data;
+ message1.set_foo_int(123);
+ int size = message1.ByteSizeLong();
+ 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::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));
+ EXPECT_EQ(message2.foo_int(), 123);
+ }
+
+ // String
+ {
+ UNITTEST::TestOneof2 message1, message2;
+ string data;
+ message1.set_foo_string("foo");
+ int size = message1.ByteSizeLong();
+ 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::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));
+ EXPECT_EQ(message2.foo_string(), "foo");
+ }
+
+
+ // Bytes
+ {
+ UNITTEST::TestOneof2 message1, message2;
+ string data;
+ message1.set_foo_bytes("qux");
+ int size = message1.ByteSizeLong();
+ 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::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));
+ EXPECT_EQ(message2.foo_bytes(), "qux");
+ }
+
+ // Enum
+ {
+ UNITTEST::TestOneof2 message1, message2;
+ string data;
+ message1.set_foo_enum(UNITTEST::TestOneof2::FOO);
+ int size = message1.ByteSizeLong();
+ 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::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));
+ EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO);
+ }
+
+ // Message
+ {
+ UNITTEST::TestOneof2 message1, message2;
+ string data;
+ message1.mutable_foo_message()->set_qux_int(234);
+ int size = message1.ByteSizeLong();
+ 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::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));
+ EXPECT_EQ(message2.foo_message().qux_int(), 234);
+ }
+
+ // Group
+ {
+ UNITTEST::TestOneof2 message1, message2;
+ string data;
+ message1.mutable_foogroup()->set_a(345);
+ int size = message1.ByteSizeLong();
+ 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::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));
+ EXPECT_EQ(message2.foogroup().a(), 345);
+ }
+
+}
+
+TEST_F(OneofTest, MergeFrom) {
+ UNITTEST::TestOneof2 message1, message2;
+
+ message1.set_foo_int(123);
+ message2.MergeFrom(message1);
+ TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
+ EXPECT_TRUE(message2.has_foo_int());
+ EXPECT_EQ(message2.foo_int(), 123);
+
+ message1.set_foo_string("foo");
+ message2.MergeFrom(message1);
+ TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
+ EXPECT_TRUE(message2.has_foo_string());
+ EXPECT_EQ(message2.foo_string(), "foo");
+
+
+ message1.set_foo_bytes("qux");
+ message2.MergeFrom(message1);
+ TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
+ EXPECT_TRUE(message2.has_foo_bytes());
+ EXPECT_EQ(message2.foo_bytes(), "qux");
+
+ message1.set_foo_enum(UNITTEST::TestOneof2::FOO);
+ message2.MergeFrom(message1);
+ TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
+ EXPECT_TRUE(message2.has_foo_enum());
+ EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO);
+
+ message1.mutable_foo_message()->set_qux_int(234);
+ message2.MergeFrom(message1);
+ TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
+ EXPECT_TRUE(message2.has_foo_message());
+ EXPECT_EQ(message2.foo_message().qux_int(), 234);
+
+ message1.mutable_foogroup()->set_a(345);
+ message2.MergeFrom(message1);
+ TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
+ EXPECT_TRUE(message2.has_foogroup());
+ EXPECT_EQ(message2.foogroup().a(), 345);
+
+}
+
+TEST(HELPERS_TEST_NAME, TestSCC) {
+ UNITTEST::TestMutualRecursionA a;
+ SCCAnalyzer scc_analyzer((Options()));
+ const SCC* scc = scc_analyzer.GetSCC(a.GetDescriptor());
+ std::vector<string> names;
+ for (int i = 0; i < scc->descriptors.size(); i++) {
+ names.push_back(scc->descriptors[i]->full_name());
+ }
+ string package = a.GetDescriptor()->file()->package();
+ ASSERT_EQ(names.size(), 4);
+ std::sort(names.begin(), names.end());
+ EXPECT_EQ(names[0], package + ".TestMutualRecursionA");
+ EXPECT_EQ(names[1], package + ".TestMutualRecursionA.SubGroup");
+ EXPECT_EQ(names[2], package + ".TestMutualRecursionA.SubMessage");
+ EXPECT_EQ(names[3], package + ".TestMutualRecursionB");
+
+ MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
+ EXPECT_EQ(result.is_recursive, true);
+ EXPECT_EQ(result.contains_required, false);
+ EXPECT_EQ(result.contains_cord, true); // TestAllTypes
+ EXPECT_EQ(result.contains_extension, false); // TestAllTypes
+}
+
+TEST(HELPERS_TEST_NAME, TestSCCAnalysis) {
+ {
+ UNITTEST::TestRecursiveMessage msg;
+ SCCAnalyzer scc_analyzer((Options()));
+ const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor());
+ MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
+ EXPECT_EQ(result.is_recursive, true);
+ EXPECT_EQ(result.contains_required, false);
+ EXPECT_EQ(result.contains_cord, false);
+ EXPECT_EQ(result.contains_extension, false);
+ }
+ {
+ UNITTEST::TestAllExtensions msg;
+ SCCAnalyzer scc_analyzer((Options()));
+ const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor());
+ MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
+ EXPECT_EQ(result.is_recursive, false);
+ EXPECT_EQ(result.contains_required, false);
+ EXPECT_EQ(result.contains_cord, false);
+ EXPECT_EQ(result.contains_extension, true);
+ }
+ {
+ UNITTEST::TestRequired msg;
+ SCCAnalyzer scc_analyzer((Options()));
+ const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor());
+ MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
+ EXPECT_EQ(result.is_recursive, false);
+ EXPECT_EQ(result.contains_required, true);
+ EXPECT_EQ(result.contains_cord, false);
+ EXPECT_EQ(result.contains_extension, false);
+ }
+}
+
+} // namespace cpp_unittest
+} // namespace cpp
+} // namespace compiler
+
+namespace no_generic_services_test {
+ // Verify that no class called "TestService" was defined in
+ // unittest_no_generic_services.pb.h by defining a different type by the same
+ // name. If such a service was generated, this will not compile.
+ struct TestService {
+ int i;
+ };
+}
+
+namespace compiler {
+namespace cpp {
+namespace cpp_unittest {
+
+TEST_F(GENERATED_SERVICE_TEST_NAME, NoGenericServices) {
+ // Verify that non-services in unittest_no_generic_services.proto were
+ // generated.
+ no_generic_services_test::TestMessage message;
+ message.set_a(1);
+ message.SetExtension(no_generic_services_test::test_extension, 123);
+ no_generic_services_test::TestEnum e = no_generic_services_test::FOO;
+ EXPECT_EQ(e, 1);
+
+ // Verify that a ServiceDescriptor is generated for the service even if the
+ // class itself is not.
+ const FileDescriptor* file =
+ no_generic_services_test::TestMessage::descriptor()->file();
+
+ ASSERT_EQ(1, file->service_count());
+ EXPECT_EQ("TestService", file->service(0)->name());
+ ASSERT_EQ(1, file->service(0)->method_count());
+ EXPECT_EQ("Foo", file->service(0)->method(0)->name());
+}
+
+#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
+
+// ===================================================================
+
+// This test must run last. It verifies that descriptors were or were not
+// initialized depending on whether PROTOBUF_TEST_NO_DESCRIPTORS was defined.
+// When this is defined, we skip all tests which are expected to trigger
+// descriptor initialization. This verifies that everything else still works
+// if descriptors are not initialized.
+TEST(DESCRIPTOR_INIT_TEST_NAME, Initialized) {
+#ifdef PROTOBUF_TEST_NO_DESCRIPTORS
+ bool should_have_descriptors = false;
+#else
+ bool should_have_descriptors = true;
+#endif
+
+ EXPECT_EQ(should_have_descriptors,
+ DescriptorPool::generated_pool()->InternalIsFileLoaded(
+ UNITTEST_PROTO_PATH));
+}
+
+} // namespace cpp_unittest
+
+} // namespace cpp
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/compiler/cpp/metadata_test.cc b/src/google/protobuf/compiler/cpp/metadata_test.cc
index 456784c6..2ad4edd2 100644
--- a/src/google/protobuf/compiler/cpp/metadata_test.cc
+++ b/src/google/protobuf/compiler/cpp/metadata_test.cc
@@ -29,9 +29,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_generator.h>
diff --git a/src/google/protobuf/compiler/csharp/csharp_enum.cc b/src/google/protobuf/compiler/csharp/csharp_enum.cc
index 9759e3ef..32c71990 100644
--- a/src/google/protobuf/compiler/csharp/csharp_enum.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_enum.cc
@@ -43,8 +43,6 @@
#include <google/protobuf/compiler/csharp/csharp_helpers.h>
#include <google/protobuf/compiler/csharp/csharp_options.h>
-using google::protobuf::internal::scoped_ptr;
-
namespace google {
namespace protobuf {
namespace compiler {
diff --git a/src/google/protobuf/compiler/csharp/csharp_field_base.cc b/src/google/protobuf/compiler/csharp/csharp_field_base.cc
index ecf29ece..7e737e47 100644
--- a/src/google/protobuf/compiler/csharp/csharp_field_base.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_field_base.cc
@@ -46,8 +46,6 @@
#include <google/protobuf/compiler/csharp/csharp_helpers.h>
#include <google/protobuf/compiler/csharp/csharp_names.h>
-using google::protobuf::internal::scoped_ptr;
-
namespace google {
namespace protobuf {
namespace compiler {
diff --git a/src/google/protobuf/compiler/csharp/csharp_generator.cc b/src/google/protobuf/compiler/csharp/csharp_generator.cc
index 5418127f..0c93fc29 100644
--- a/src/google/protobuf/compiler/csharp/csharp_generator.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_generator.cc
@@ -44,8 +44,6 @@
#include <google/protobuf/compiler/csharp/csharp_options.h>
#include <google/protobuf/compiler/csharp/csharp_reflection_class.h>
-using google::protobuf::internal::scoped_ptr;
-
namespace google {
namespace protobuf {
namespace compiler {
@@ -100,7 +98,7 @@ bool Generator::Generate(
*error = filename_error;
return false;
}
- scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(filename));
io::Printer printer(output.get(), '$');
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_map_field.cc b/src/google/protobuf/compiler/csharp/csharp_map_field.cc
index e6eac6ed..d58514ce 100644
--- a/src/google/protobuf/compiler/csharp/csharp_map_field.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_map_field.cc
@@ -63,9 +63,9 @@ void MapFieldGenerator::GenerateMembers(io::Printer* printer) {
descriptor_->message_type()->FindFieldByName("value");
variables_["key_type_name"] = type_name(key_descriptor);
variables_["value_type_name"] = type_name(value_descriptor);
- scoped_ptr<FieldGeneratorBase> key_generator(
+ std::unique_ptr<FieldGeneratorBase> key_generator(
CreateFieldGenerator(key_descriptor, 1, this->options()));
- scoped_ptr<FieldGeneratorBase> value_generator(
+ std::unique_ptr<FieldGeneratorBase> value_generator(
CreateFieldGenerator(value_descriptor, 2, this->options()));
printer->Print(
diff --git a/src/google/protobuf/compiler/csharp/csharp_message.cc b/src/google/protobuf/compiler/csharp/csharp_message.cc
index 17b4a071..8a4307f1 100644
--- a/src/google/protobuf/compiler/csharp/csharp_message.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_message.cc
@@ -49,8 +49,6 @@
#include <google/protobuf/compiler/csharp/csharp_message.h>
#include <google/protobuf/compiler/csharp/csharp_names.h>
-using google::protobuf::internal::scoped_ptr;
-
namespace google {
namespace protobuf {
namespace compiler {
@@ -184,7 +182,7 @@ void MessageGenerator::Generate(io::Printer* printer) {
"field_name", fieldDescriptor->name(),
"field_constant_name", GetFieldConstantName(fieldDescriptor),
"index", SimpleItoa(fieldDescriptor->number()));
- scoped_ptr<FieldGeneratorBase> generator(
+ std::unique_ptr<FieldGeneratorBase> generator(
CreateFieldGeneratorInternal(fieldDescriptor));
generator->GenerateMembers(printer);
printer->Print("\n");
@@ -293,7 +291,7 @@ void MessageGenerator::GenerateCloningCode(io::Printer* printer) {
// Clone non-oneof fields first
for (int i = 0; i < descriptor_->field_count(); i++) {
if (!descriptor_->field(i)->containing_oneof()) {
- scoped_ptr<FieldGeneratorBase> generator(
+ std::unique_ptr<FieldGeneratorBase> generator(
CreateFieldGeneratorInternal(descriptor_->field(i)));
generator->GenerateCloningCode(printer);
}
@@ -307,7 +305,7 @@ void MessageGenerator::GenerateCloningCode(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);
- scoped_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field));
+ std::unique_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field));
vars["field_property_name"] = GetPropertyName(field);
printer->Print(
vars,
@@ -361,7 +359,7 @@ void MessageGenerator::GenerateFrameworkMethods(io::Printer* printer) {
" }\n");
printer->Indent();
for (int i = 0; i < descriptor_->field_count(); i++) {
- scoped_ptr<FieldGeneratorBase> generator(
+ std::unique_ptr<FieldGeneratorBase> generator(
CreateFieldGeneratorInternal(descriptor_->field(i)));
generator->WriteEquals(printer);
}
@@ -382,7 +380,7 @@ void MessageGenerator::GenerateFrameworkMethods(io::Printer* printer) {
" int hash = 1;\n");
printer->Indent();
for (int i = 0; i < descriptor_->field_count(); i++) {
- scoped_ptr<FieldGeneratorBase> generator(
+ std::unique_ptr<FieldGeneratorBase> generator(
CreateFieldGeneratorInternal(descriptor_->field(i)));
generator->WriteHash(printer);
}
@@ -413,7 +411,7 @@ void MessageGenerator::GenerateMessageSerializationMethods(io::Printer* printer)
// Serialize all the fields
for (int i = 0; i < fields_by_number().size(); i++) {
- scoped_ptr<FieldGeneratorBase> generator(
+ std::unique_ptr<FieldGeneratorBase> generator(
CreateFieldGeneratorInternal(fields_by_number()[i]));
generator->GenerateSerializationCode(printer);
}
@@ -435,7 +433,7 @@ void MessageGenerator::GenerateMessageSerializationMethods(io::Printer* printer)
printer->Indent();
printer->Print("int size = 0;\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
- scoped_ptr<FieldGeneratorBase> generator(
+ std::unique_ptr<FieldGeneratorBase> generator(
CreateFieldGeneratorInternal(descriptor_->field(i)));
generator->GenerateSerializedSizeCode(printer);
}
@@ -469,7 +467,7 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) {
// Merge non-oneof fields
for (int i = 0; i < descriptor_->field_count(); i++) {
if (!descriptor_->field(i)->containing_oneof()) {
- scoped_ptr<FieldGeneratorBase> generator(
+ std::unique_ptr<FieldGeneratorBase> generator(
CreateFieldGeneratorInternal(descriptor_->field(i)));
generator->GenerateMergingCode(printer);
}
@@ -487,7 +485,7 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) {
vars,
"case $property_name$OneofCase.$field_property_name$:\n");
printer->Indent();
- scoped_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field));
+ std::unique_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field));
generator->GenerateMergingCode(printer);
printer->Print("break;\n");
printer->Outdent();
@@ -546,7 +544,7 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) {
printer->Print("case $tag$: {\n", "tag", SimpleItoa(tag));
printer->Indent();
- scoped_ptr<FieldGeneratorBase> generator(
+ std::unique_ptr<FieldGeneratorBase> generator(
CreateFieldGeneratorInternal(field));
generator->GenerateParsingCode(printer);
printer->Print("break;\n");
diff --git a/src/google/protobuf/compiler/csharp/csharp_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_message_field.cc
index 59b7edfb..cf1b4dbf 100644
--- a/src/google/protobuf/compiler/csharp/csharp_message_field.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_message_field.cc
@@ -133,7 +133,7 @@ void MessageFieldGenerator::WriteToString(io::Printer* printer) {
void MessageFieldGenerator::GenerateCloningCode(io::Printer* printer) {
printer->Print(variables_,
- "$property_name$ = other.$has_property_check$ ? other.$property_name$.Clone() : null;\n");
+ "$name$_ = other.$has_property_check$ ? other.$name$_.Clone() : null;\n");
}
void MessageFieldGenerator::GenerateFreezingCode(io::Printer* printer) {
diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc
index 8fa0b050..90af569c 100644
--- a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc
@@ -66,11 +66,11 @@ void RepeatedMessageFieldGenerator::GenerateMembers(io::Printer* printer) {
// "create single field generator for this repeated field"
// function, but it doesn't seem worth it for just this.
if (IsWrapperType(descriptor_)) {
- scoped_ptr<FieldGeneratorBase> single_generator(
+ std::unique_ptr<FieldGeneratorBase> single_generator(
new WrapperFieldGenerator(descriptor_, fieldOrdinal_, this->options()));
single_generator->GenerateCodecCode(printer);
} else {
- scoped_ptr<FieldGeneratorBase> single_generator(
+ std::unique_ptr<FieldGeneratorBase> single_generator(
new MessageFieldGenerator(descriptor_, fieldOrdinal_, this->options()));
single_generator->GenerateCodecCode(printer);
}
diff --git a/src/google/protobuf/compiler/importer.cc b/src/google/protobuf/compiler/importer.cc
index a5341e0d..58498aaa 100644
--- a/src/google/protobuf/compiler/importer.cc
+++ b/src/google/protobuf/compiler/importer.cc
@@ -32,7 +32,6 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
-
#ifdef _MSC_VER
#include <direct.h>
#else
@@ -45,9 +44,6 @@
#include <algorithm>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/compiler/importer.h>
@@ -55,6 +51,8 @@
#include <google/protobuf/io/tokenizer.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/stubs/strutil.h>
+
+
#include <google/protobuf/stubs/io_win32.h>
#ifdef _WIN32
@@ -105,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);
}
@@ -131,7 +129,7 @@ SourceTreeDescriptorDatabase::~SourceTreeDescriptorDatabase() {}
bool SourceTreeDescriptorDatabase::FindFileByName(
const string& filename, FileDescriptorProto* output) {
- google::protobuf::scoped_ptr<io::ZeroCopyInputStream> input(source_tree_->Open(filename));
+ std::unique_ptr<io::ZeroCopyInputStream> input(source_tree_->Open(filename));
if (input == NULL) {
if (error_collector_ != NULL) {
error_collector_->AddError(filename, -1, 0,
@@ -420,7 +418,7 @@ DiskSourceTree::DiskFileToVirtualFile(
// Verify that we can open the file. Note that this also has the side-effect
// of verifying that we are not canonicalizing away any non-existent
// directories.
- google::protobuf::scoped_ptr<io::ZeroCopyInputStream> stream(OpenDiskFile(disk_file));
+ std::unique_ptr<io::ZeroCopyInputStream> stream(OpenDiskFile(disk_file));
if (stream == NULL) {
return CANNOT_OPEN;
}
@@ -430,7 +428,7 @@ DiskSourceTree::DiskFileToVirtualFile(
bool DiskSourceTree::VirtualFileToDiskFile(const string& virtual_file,
string* disk_file) {
- google::protobuf::scoped_ptr<io::ZeroCopyInputStream> stream(
+ std::unique_ptr<io::ZeroCopyInputStream> stream(
OpenVirtualFile(virtual_file, disk_file));
return stream != NULL;
}
diff --git a/src/google/protobuf/compiler/importer.h b/src/google/protobuf/compiler/importer.h
index a4ffcf87..bf6d3de3 100644
--- a/src/google/protobuf/compiler/importer.h
+++ b/src/google/protobuf/compiler/importer.h
@@ -96,12 +96,13 @@ class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabas
}
// implements DescriptorDatabase -----------------------------------
- bool FindFileByName(const string& filename, FileDescriptorProto* output);
+ bool FindFileByName(const string& filename,
+ FileDescriptorProto* output) override;
bool FindFileContainingSymbol(const string& symbol_name,
- FileDescriptorProto* output);
+ FileDescriptorProto*output) override;
bool FindFileContainingExtension(const string& containing_type,
int field_number,
- FileDescriptorProto* output);
+ FileDescriptorProto* output) override;
private:
class SingleFileErrorCollector;
@@ -119,13 +120,13 @@ class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabas
const string& element_name,
const Message* descriptor,
ErrorLocation location,
- const string& message);
+ const string& message) override;
virtual void AddWarning(const string& filename,
const string& element_name,
const Message* descriptor,
ErrorLocation location,
- const string& message);
+ const string& message) override;
private:
SourceTreeDescriptorDatabase* owner_;
@@ -293,9 +294,9 @@ class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree {
bool VirtualFileToDiskFile(const string& virtual_file, string* disk_file);
// implements SourceTree -------------------------------------------
- virtual io::ZeroCopyInputStream* Open(const string& filename);
+ virtual io::ZeroCopyInputStream* Open(const string& filename) override;
- virtual string GetLastErrorMessage();
+ virtual string GetLastErrorMessage() override;
private:
struct Mapping {
diff --git a/src/google/protobuf/compiler/importer_unittest.cc b/src/google/protobuf/compiler/importer_unittest.cc
index a96ac853..73bef3f4 100644
--- a/src/google/protobuf/compiler/importer_unittest.cc
+++ b/src/google/protobuf/compiler/importer_unittest.cc
@@ -36,9 +36,6 @@
#include <google/protobuf/stubs/hash.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -268,7 +265,7 @@ class DiskSourceTreeTest : public testing::Test {
void ExpectFileContents(const string& filename,
const char* expected_contents) {
- google::protobuf::scoped_ptr<io::ZeroCopyInputStream> input(source_tree_.Open(filename));
+ std::unique_ptr<io::ZeroCopyInputStream> input(source_tree_.Open(filename));
ASSERT_FALSE(input == NULL);
@@ -285,7 +282,7 @@ class DiskSourceTreeTest : public testing::Test {
void ExpectCannotOpenFile(const string& filename,
const string& error_message) {
- google::protobuf::scoped_ptr<io::ZeroCopyInputStream> input(source_tree_.Open(filename));
+ std::unique_ptr<io::ZeroCopyInputStream> input(source_tree_.Open(filename));
EXPECT_TRUE(input == NULL);
EXPECT_EQ(error_message, source_tree_.GetLastErrorMessage());
}
diff --git a/src/google/protobuf/compiler/java/java_context.cc b/src/google/protobuf/compiler/java/java_context.cc
index 0771d5e1..2528c2d1 100644
--- a/src/google/protobuf/compiler/java/java_context.cc
+++ b/src/google/protobuf/compiler/java/java_context.cc
@@ -69,14 +69,14 @@ bool IsConflicting(const FieldDescriptor* field1, const string& name1,
// field1 is repeated, and field2 is not.
if (name1 + "Count" == name2) {
*info = "both repeated field \"" + field1->name() + "\" and singular " +
- "field \"" + field2->name() + "\" generates the method \"" +
- "get" + name1 + "Count()\"";
+ "field \"" + field2->name() + "\" generate the method \"" +
+ "get" + name1 + "Count()\"";
return true;
}
if (name1 + "List" == name2) {
*info = "both repeated field \"" + field1->name() + "\" and singular " +
- "field \"" + field2->name() + "\" generates the method \"" +
- "get" + name1 + "List()\"";
+ "field \"" + field2->name() + "\" generate the method \"" +
+ "get" + name1 + "List()\"";
return true;
}
// Well, there are obviously many more conflicting cases, but it probably
diff --git a/src/google/protobuf/compiler/java/java_context.h b/src/google/protobuf/compiler/java/java_context.h
index 9a74c430..9de7415a 100644
--- a/src/google/protobuf/compiler/java/java_context.h
+++ b/src/google/protobuf/compiler/java/java_context.h
@@ -33,9 +33,6 @@
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
#include <google/protobuf/stubs/common.h>
@@ -97,7 +94,7 @@ class Context {
void InitializeFieldGeneratorInfoForFields(
const std::vector<const FieldDescriptor*>& fields);
- google::protobuf::scoped_ptr<ClassNameResolver> name_resolver_;
+ std::unique_ptr<ClassNameResolver> name_resolver_;
std::map<const FieldDescriptor*, FieldGeneratorInfo>
field_generator_info_map_;
std::map<const OneofDescriptor*, OneofGeneratorInfo>
diff --git a/src/google/protobuf/compiler/java/java_enum.cc b/src/google/protobuf/compiler/java/java_enum.cc
index d125ebe5..bef69f1a 100644
--- a/src/google/protobuf/compiler/java/java_enum.cc
+++ b/src/google/protobuf/compiler/java/java_enum.cc
@@ -36,12 +36,12 @@
#include <string>
#include <google/protobuf/compiler/java/java_context.h>
-#include <google/protobuf/compiler/java/java_enum.h>
#include <google/protobuf/compiler/java/java_doc_comment.h>
+#include <google/protobuf/compiler/java/java_enum.h>
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
-#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
diff --git a/src/google/protobuf/compiler/java/java_enum_field.cc b/src/google/protobuf/compiler/java/java_enum_field.cc
index 642cdd36..ef64d88b 100644
--- a/src/google/protobuf/compiler/java/java_enum_field.cc
+++ b/src/google/protobuf/compiler/java/java_enum_field.cc
@@ -305,11 +305,15 @@ GenerateBuildingCode(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
printer->Print(variables_,
"if ($get_has_field_bit_from_local$) {\n"
+ " result.$name$_ = $name$_;\n"
" $set_has_field_bit_to_local$;\n"
+ "} else {\n"
+ " result.$name$_ = $default_number$;\n"
"}\n");
+ } else {
+ printer->Print(variables_,
+ "result.$name$_ = $name$_;\n");
}
- printer->Print(variables_,
- "result.$name$_ = $name$_;\n");
}
void ImmutableEnumFieldGenerator::
@@ -674,8 +678,7 @@ GenerateMembers(io::Printer* printer) const {
printer->Annotate("{", "}", descriptor_);
}
- if (descriptor_->is_packed() &&
- context_->HasGeneratedMethods(descriptor_->containing_type())) {
+ if (descriptor_->is_packed()) {
printer->Print(variables_,
"private int $name$MemoizedSerializedSize;\n");
}
diff --git a/src/google/protobuf/compiler/java/java_enum_field_lite.cc b/src/google/protobuf/compiler/java/java_enum_field_lite.cc
index a4de1e23..f1fe71b0 100644
--- a/src/google/protobuf/compiler/java/java_enum_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_enum_field_lite.cc
@@ -165,6 +165,7 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
@@ -173,6 +174,7 @@ GenerateMembers(io::Printer* printer) const {
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" return $name$_;\n"
"}\n");
@@ -180,6 +182,7 @@ GenerateMembers(io::Printer* printer) const {
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" $type$ result = $type$.forNumber($name$_);\n"
" return result == null ? $unknown$ : result;\n"
@@ -217,6 +220,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
@@ -225,6 +229,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" return instance.get$capitalized_name$Value();\n"
"}\n");
@@ -241,6 +246,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
@@ -378,6 +384,7 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
@@ -386,6 +393,7 @@ GenerateMembers(io::Printer* printer) const {
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return (java.lang.Integer) $oneof_name$_;\n"
@@ -396,6 +404,7 @@ GenerateMembers(io::Printer* printer) const {
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" $type$ result = $type$.forNumber((java.lang.Integer) $oneof_name$_);\n"
@@ -439,6 +448,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
@@ -447,6 +457,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" return instance.get$capitalized_name$Value();\n"
"}\n");
@@ -463,6 +474,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
@@ -611,6 +623,7 @@ GenerateMembers(io::Printer* printer) const {
" java.lang.Integer, $type$> $name$_converter_ =\n"
" new com.google.protobuf.Internal.ListAdapter.Converter<\n"
" java.lang.Integer, $type$>() {\n"
+ " @java.lang.Override\n"
" public $type$ convert(java.lang.Integer from) {\n"
" $type$ result = $type$.forNumber(from);\n"
" return result == null ? $unknown$ : result;\n"
@@ -619,6 +632,7 @@ GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.util.List<$type$> "
"${$get$capitalized_name$List$}$() {\n"
" return new com.google.protobuf.Internal.ListAdapter<\n"
@@ -627,12 +641,14 @@ GenerateMembers(io::Printer* printer) const {
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_converter_.convert($name$_.getInt(index));\n"
"}\n");
@@ -640,6 +656,7 @@ GenerateMembers(io::Printer* printer) const {
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.util.List<java.lang.Integer>\n"
"${$get$capitalized_name$ValueList$}$() {\n"
" return $name$_;\n"
@@ -647,6 +664,7 @@ GenerateMembers(io::Printer* printer) const {
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n"
" return $name$_.getInt(index);\n"
"}\n");
@@ -732,6 +750,7 @@ void RepeatedImmutableEnumFieldLiteGenerator::
GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.util.List<$type$> "
"${$get$capitalized_name$List$}$() {\n"
" return instance.get$capitalized_name$List();\n"
@@ -739,12 +758,14 @@ GenerateBuilderMembers(io::Printer* printer) const {
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return instance.get$capitalized_name$Count();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return instance.get$capitalized_name$(index);\n"
"}\n");
@@ -787,6 +808,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.util.List<java.lang.Integer>\n"
"${$get$capitalized_name$ValueList$}$() {\n"
" return java.util.Collections.unmodifiableList(\n"
@@ -795,6 +817,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n"
" return instance.get$capitalized_name$Value(index);\n"
"}\n");
diff --git a/src/google/protobuf/compiler/java/java_enum_lite.cc b/src/google/protobuf/compiler/java/java_enum_lite.cc
index ab3b3323..806008ee 100644
--- a/src/google/protobuf/compiler/java/java_enum_lite.cc
+++ b/src/google/protobuf/compiler/java/java_enum_lite.cc
@@ -36,12 +36,12 @@
#include <string>
#include <google/protobuf/compiler/java/java_context.h>
-#include <google/protobuf/compiler/java/java_enum_lite.h>
#include <google/protobuf/compiler/java/java_doc_comment.h>
+#include <google/protobuf/compiler/java/java_enum_lite.h>
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
-#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
@@ -135,6 +135,7 @@ void EnumLiteGenerator::Generate(io::Printer* printer) {
printer->Print(
"\n"
+ "@java.lang.Override\n"
"public final int getNumber() {\n");
if (SupportUnknownEnumValue(descriptor_->file())) {
printer->Print(
@@ -182,6 +183,7 @@ void EnumLiteGenerator::Generate(io::Printer* printer) {
"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"
diff --git a/src/google/protobuf/compiler/java/java_extension.cc b/src/google/protobuf/compiler/java/java_extension.cc
index 9b9be55b..3eb1370d 100644
--- a/src/google/protobuf/compiler/java/java_extension.cc
+++ b/src/google/protobuf/compiler/java/java_extension.cc
@@ -141,6 +141,7 @@ void ImmutableExtensionGenerator::Generate(io::Printer* printer) {
" $singular_type$.class,\n"
" $prototype$);\n");
}
+ printer->Annotate("name", descriptor_);
}
int ImmutableExtensionGenerator::GenerateNonNestedInitializationCode(
diff --git a/src/google/protobuf/compiler/java/java_extension_lite.cc b/src/google/protobuf/compiler/java/java_extension_lite.cc
index c48c92e9..70ce8e7d 100644
--- a/src/google/protobuf/compiler/java/java_extension_lite.cc
+++ b/src/google/protobuf/compiler/java/java_extension_lite.cc
@@ -96,6 +96,7 @@ void ImmutableExtensionLiteGenerator::Generate(io::Printer* printer) {
" com.google.protobuf.WireFormat.FieldType.$type_constant$,\n"
" $singular_type$.class);\n");
}
+ printer->Annotate("name", descriptor_);
}
int ImmutableExtensionLiteGenerator::GenerateNonNestedInitializationCode(
diff --git a/src/google/protobuf/compiler/java/java_field.cc b/src/google/protobuf/compiler/java/java_field.cc
index 1ab18629..93de0229 100644
--- a/src/google/protobuf/compiler/java/java_field.cc
+++ b/src/google/protobuf/compiler/java/java_field.cc
@@ -35,9 +35,6 @@
#include <google/protobuf/compiler/java/java_field.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -214,8 +211,7 @@ template <>
FieldGeneratorMap<ImmutableFieldGenerator>::FieldGeneratorMap(
const Descriptor* descriptor, Context* context)
: descriptor_(descriptor),
- field_generators_(new google::protobuf::scoped_ptr<
- ImmutableFieldGenerator>[descriptor->field_count()]) {
+ field_generators_(descriptor->field_count()) {
// Construct all the FieldGenerators and assign them bit indices for their
// bit fields.
@@ -237,8 +233,7 @@ template <>
FieldGeneratorMap<ImmutableFieldLiteGenerator>::FieldGeneratorMap(
const Descriptor* descriptor, Context* context)
: descriptor_(descriptor),
- field_generators_(new google::protobuf::scoped_ptr<
- ImmutableFieldLiteGenerator>[descriptor->field_count()]) {
+ field_generators_(descriptor->field_count()) {
// Construct all the FieldGenerators and assign them bit indices for their
// bit fields.
int messageBitIndex = 0;
diff --git a/src/google/protobuf/compiler/java/java_field.h b/src/google/protobuf/compiler/java/java_field.h
index cc1d83d9..7275c099 100644
--- a/src/google/protobuf/compiler/java/java_field.h
+++ b/src/google/protobuf/compiler/java/java_field.h
@@ -37,9 +37,6 @@
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
#include <google/protobuf/stubs/common.h>
@@ -141,7 +138,7 @@ class FieldGeneratorMap {
const Descriptor* descriptor_;
Context* context_;
ClassNameResolver* name_resolver_;
- google::protobuf::scoped_array<google::protobuf::scoped_ptr<FieldGeneratorType> > field_generators_;
+ std::vector<std::unique_ptr<FieldGeneratorType>> field_generators_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
};
@@ -163,6 +160,14 @@ template<>
FieldGeneratorMap<ImmutableFieldGenerator>::~FieldGeneratorMap();
+template <>
+FieldGeneratorMap<ImmutableFieldLiteGenerator>::FieldGeneratorMap(
+ const Descriptor* descriptor, Context* context);
+
+template <>
+FieldGeneratorMap<ImmutableFieldLiteGenerator>::~FieldGeneratorMap();
+
+
// Field information used in FieldGeneartors.
struct FieldGeneratorInfo {
string name;
diff --git a/src/google/protobuf/compiler/java/java_file.cc b/src/google/protobuf/compiler/java/java_file.cc
index 21133a15..5583b779 100644
--- a/src/google/protobuf/compiler/java/java_file.cc
+++ b/src/google/protobuf/compiler/java/java_file.cc
@@ -35,9 +35,6 @@
#include <google/protobuf/compiler/java/java_file.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <set>
#include <google/protobuf/compiler/java/java_context.h>
@@ -51,9 +48,9 @@
#include <google/protobuf/compiler/java/java_service.h>
#include <google/protobuf/compiler/java/java_shared_code_generator.h>
#include <google/protobuf/compiler/code_generator.h>
+#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
-#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/stubs/strutil.h>
@@ -136,7 +133,7 @@ void CollectExtensions(const FileDescriptorProto& file_proto,
"descriptor.proto is not in the transitive dependencies. "
"This normally should not happen. Please report a bug.";
DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<Message> dynamic_file_proto(
+ std::unique_ptr<Message> dynamic_file_proto(
factory.GetPrototype(file_proto_desc)->New());
GOOGLE_CHECK(dynamic_file_proto.get() != NULL);
GOOGLE_CHECK(dynamic_file_proto->ParseFromString(file_data));
@@ -189,10 +186,8 @@ FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options,
bool immutable_api)
: file_(file),
java_package_(FileJavaPackage(file, immutable_api)),
- message_generators_(
- new google::protobuf::scoped_ptr<MessageGenerator>[file->message_type_count()]),
- extension_generators_(
- new google::protobuf::scoped_ptr<ExtensionGenerator>[file->extension_count()]),
+ message_generators_(file->message_type_count()),
+ extension_generators_(file->extension_count()),
context_(new Context(file, options)),
name_resolver_(context_->GetNameResolver()),
options_(options),
@@ -228,6 +223,16 @@ bool FileGenerator::Validate(string* error) {
"option to specify a different outer class name for the .proto file.");
return false;
}
+ // Print a warning if optimize_for = LITE_RUNTIME is used.
+ if (file_->options().optimize_for() == FileOptions::LITE_RUNTIME) {
+ GOOGLE_LOG(WARNING)
+ << "The optimize_for = LITE_RUNTIME option is no longer supported by "
+ << "protobuf Java code generator and may generate broken code. It "
+ << "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";
+ }
return true;
}
@@ -309,7 +314,7 @@ void FileGenerator::Generate(io::Printer* printer) {
}
if (HasGenericServices(file_, context_->EnforceLite())) {
for (int i = 0; i < file_->service_count(); i++) {
- google::protobuf::scoped_ptr<ServiceGenerator> generator(
+ std::unique_ptr<ServiceGenerator> generator(
generator_factory_->NewServiceGenerator(file_->service(i)));
generator->Generate(printer);
}
@@ -435,7 +440,7 @@ void FileGenerator::GenerateDescriptorInitializationCodeForImmutable(
" com.google.protobuf.ExtensionRegistry.newInstance();\n");
FieldDescriptorSet::iterator it;
for (it = extensions.begin(); it != extensions.end(); it++) {
- google::protobuf::scoped_ptr<ExtensionGenerator> generator(
+ std::unique_ptr<ExtensionGenerator> generator(
generator_factory_->NewExtensionGenerator(*it));
bytecode_estimate += generator->GenerateRegistrationCode(printer);
MaybeRestartJavaMethod(
@@ -588,7 +593,7 @@ static void GenerateSibling(const string& package_dir,
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
&annotations);
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
+ std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
io::Printer printer(output.get(), '$',
annotate_code ? &annotation_collector : NULL);
@@ -607,7 +612,7 @@ static void GenerateSibling(const string& package_dir,
(generator->*pfn)(&printer);
if (annotate_code) {
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output(
+ std::unique_ptr<io::ZeroCopyOutputStream> info_output(
context->Open(info_full_path));
annotations.SerializeToZeroCopyStream(info_output.get());
annotation_list->push_back(info_full_path);
@@ -650,7 +655,7 @@ void FileGenerator::GenerateSiblings(const string& package_dir,
}
if (HasGenericServices(file_, context_->EnforceLite())) {
for (int i = 0; i < file_->service_count(); i++) {
- google::protobuf::scoped_ptr<ServiceGenerator> generator(
+ std::unique_ptr<ServiceGenerator> generator(
generator_factory_->NewServiceGenerator(file_->service(i)));
GenerateSibling<ServiceGenerator>(
package_dir, java_package_, file_->service(i), context, file_list,
diff --git a/src/google/protobuf/compiler/java/java_file.h b/src/google/protobuf/compiler/java/java_file.h
index e95aef09..78833a45 100644
--- a/src/google/protobuf/compiler/java/java_file.h
+++ b/src/google/protobuf/compiler/java/java_file.h
@@ -36,9 +36,6 @@
#define GOOGLE_PROTOBUF_COMPILER_JAVA_FILE_H__
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
#include <vector>
#include <google/protobuf/stubs/common.h>
@@ -101,10 +98,10 @@ class FileGenerator {
string java_package_;
string classname_;
- google::protobuf::scoped_array<google::protobuf::scoped_ptr<MessageGenerator> > message_generators_;
- google::protobuf::scoped_array<google::protobuf::scoped_ptr<ExtensionGenerator> > extension_generators_;
- google::protobuf::scoped_ptr<GeneratorFactory> generator_factory_;
- google::protobuf::scoped_ptr<Context> context_;
+ std::vector<std::unique_ptr<MessageGenerator>> message_generators_;
+ std::vector<std::unique_ptr<ExtensionGenerator>> extension_generators_;
+ std::unique_ptr<GeneratorFactory> generator_factory_;
+ std::unique_ptr<Context> context_;
ClassNameResolver* name_resolver_;
const Options options_;
bool immutable_api_;
diff --git a/src/google/protobuf/compiler/java/java_generator.cc b/src/google/protobuf/compiler/java/java_generator.cc
index 84a3b90d..a5b2e784 100644
--- a/src/google/protobuf/compiler/java/java_generator.cc
+++ b/src/google/protobuf/compiler/java/java_generator.cc
@@ -35,9 +35,6 @@
#include <google/protobuf/compiler/java/java_generator.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/compiler/java/java_file.h>
#include <google/protobuf/compiler/java/java_generator_factory.h>
@@ -45,9 +42,9 @@
#include <google/protobuf/compiler/java/java_name_resolver.h>
#include <google/protobuf/compiler/java/java_options.h>
#include <google/protobuf/compiler/java/java_shared_code_generator.h>
+#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
-#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/stubs/strutil.h>
@@ -144,7 +141,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file,
}
// Generate main java file.
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
context->Open(java_filename));
GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
@@ -160,7 +157,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file,
&all_annotations);
if (file_options.annotate_code) {
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output(
+ std::unique_ptr<io::ZeroCopyOutputStream> info_output(
context->Open(info_full_path));
annotations.SerializeToZeroCopyStream(info_output.get());
}
@@ -175,7 +172,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file,
if (!file_options.output_list_file.empty()) {
// Generate output list. This is just a simple text file placed in a
// deterministic location which lists the .java files being generated.
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> srclist_raw_output(
+ std::unique_ptr<io::ZeroCopyOutputStream> srclist_raw_output(
context->Open(file_options.output_list_file));
io::Printer srclist_printer(srclist_raw_output.get(), '$');
for (int i = 0; i < all_files.size(); i++) {
@@ -186,7 +183,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file,
if (!file_options.annotation_list_file.empty()) {
// Generate output list. This is just a simple text file placed in a
// deterministic location which lists the .java files being generated.
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> annotation_list_raw_output(
+ std::unique_ptr<io::ZeroCopyOutputStream> annotation_list_raw_output(
context->Open(file_options.annotation_list_file));
io::Printer annotation_list_printer(annotation_list_raw_output.get(), '$');
for (int i = 0; i < all_annotations.size(); i++) {
diff --git a/src/google/protobuf/compiler/java/java_helpers.cc b/src/google/protobuf/compiler/java/java_helpers.cc
index dbb86b87..957076cb 100644
--- a/src/google/protobuf/compiler/java/java_helpers.cc
+++ b/src/google/protobuf/compiler/java/java_helpers.cc
@@ -75,6 +75,8 @@ const char* kForbiddenWordList[] = {
"class",
};
+const int kDefaultLookUpStartFieldNumber = 40;
+
bool IsForbidden(const string& field_name) {
for (int i = 0; i < GOOGLE_ARRAYSIZE(kForbiddenWordList); ++i) {
if (field_name == kForbiddenWordList[i]) {
@@ -103,6 +105,20 @@ string FieldName(const FieldDescriptor* field) {
}
+// Judge whether should use table or use look up.
+// Copied from com.google.protobuf.SchemaUtil.shouldUseTableSwitch
+bool ShouldUseTable(int lo, int hi, int number_of_fields) {
+ if (hi < kDefaultLookUpStartFieldNumber) {
+ return true;
+ }
+ int64 table_space_cost = (static_cast<int64>(hi) - lo + 1); // words
+ int64 table_time_cost = 3; // comparisons
+ int64 lookup_space_cost = 3 + 2 * static_cast<int64>(number_of_fields);
+ int64 lookup_time_cost = 3 + number_of_fields;
+ return table_space_cost + 3 * table_time_cost <=
+ lookup_space_cost + 3 * lookup_time_cost;
+}
+
} // namespace
void PrintGeneratedAnnotation(io::Printer* printer, char delimiter,
@@ -915,6 +931,23 @@ void EscapeUtf16ToString(uint16 code, string* output) {
output->append(StringPrintf("\\u%04x", code));
}
}
+
+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 00d683db..dd9b65b8 100644
--- a/src/google/protobuf/compiler/java/java_helpers.h
+++ b/src/google/protobuf/compiler/java/java_helpers.h
@@ -37,8 +37,8 @@
#include <string>
#include <google/protobuf/compiler/java/java_context.h>
-#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.h>
namespace google {
@@ -414,6 +414,11 @@ void EscapeUtf16ToString(uint16 code, string* output);
// bit 3: whether the field is a map field with proto2 enum value.
// bits 4-7: unused
int GetExperimentalJavaFieldType(const FieldDescriptor* field);
+
+// To get the total number of entries need to be built for experimental runtime
+// and the first field number that are not in the table part
+std::pair<int, int> GetTableDrivenNumberOfEntriesAndLookUpStartFieldNumber(
+ const FieldDescriptor** fields, int count);
} // namespace java
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/java/java_lazy_message_field.cc b/src/google/protobuf/compiler/java/java_lazy_message_field.cc
index abf8e55c..6544bea0 100644
--- a/src/google/protobuf/compiler/java/java_lazy_message_field.cc
+++ b/src/google/protobuf/compiler/java/java_lazy_message_field.cc
@@ -233,12 +233,9 @@ void ImmutableLazyMessageFieldGenerator::
GenerateBuildingCode(io::Printer* printer) const {
printer->Print(variables_,
"if ($get_has_field_bit_from_local$) {\n"
+ " result.$name$_.set($name$_);\n"
" $set_has_field_bit_to_local$;\n"
"}\n");
-
- printer->Print(variables_,
- "result.$name$_.set(\n"
- " $name$_);\n");
}
void ImmutableLazyMessageFieldGenerator::
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 f19ec271..e2e68076 100644
--- a/src/google/protobuf/compiler/java/java_map_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_map_field_lite.cc
@@ -301,6 +301,7 @@ GenerateMembers(io::Printer* printer) const {
"}\n");
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public int ${$get$capitalized_name$Count$}$() {\n"
" return internalGet$capitalized_name$().size();\n"
@@ -309,6 +310,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public boolean ${$contains$capitalized_name$$}$(\n"
" $key_type$ key) {\n"
@@ -339,6 +341,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"${$get$capitalized_name$Map$}$() {\n"
@@ -352,6 +355,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
@@ -367,6 +371,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
@@ -385,6 +390,7 @@ GenerateMembers(io::Printer* printer) const {
"/**\n"
" * Use {@link #get$capitalized_name$ValueMap()} instead.\n"
" */\n"
+ "@java.lang.Override\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
"${$get$capitalized_name$Value$}$() {\n"
@@ -394,6 +400,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
"${$get$capitalized_name$ValueMap$}$() {\n"
@@ -404,6 +411,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n"
" $key_type$ key,\n"
@@ -417,6 +425,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n"
" $key_type$ key) {\n"
@@ -436,6 +445,7 @@ GenerateMembers(io::Printer* printer) const {
"/**\n"
" * Use {@link #get$capitalized_name$Map()} instead.\n"
" */\n"
+ "@java.lang.Override\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$type_parameters$> "
"${$get$capitalized_name$$}$() {\n"
@@ -445,6 +455,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public java.util.Map<$type_parameters$> "
"${$get$capitalized_name$Map$}$() {\n"
@@ -455,6 +466,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
@@ -468,6 +480,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
@@ -519,6 +532,7 @@ void ImmutableMapFieldLiteGenerator::
GenerateBuilderMembers(io::Printer* printer) const {
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public int ${$get$capitalized_name$Count$}$() {\n"
" return instance.get$capitalized_name$Map().size();\n"
@@ -527,6 +541,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public boolean ${$contains$capitalized_name$$}$(\n"
" $key_type$ key) {\n"
@@ -570,6 +585,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"${$get$capitalized_name$Map$}$() {\n"
@@ -580,6 +596,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
@@ -595,6 +612,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
@@ -636,6 +654,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
"/**\n"
" * Use {@link #get$capitalized_name$ValueMap()} instead.\n"
" */\n"
+ "@java.lang.Override\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
"${$get$capitalized_name$Value$}$() {\n"
@@ -645,6 +664,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
"${$get$capitalized_name$ValueMap$}$() {\n"
@@ -655,6 +675,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n"
" $key_type$ key,\n"
@@ -668,6 +689,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n"
" $key_type$ key) {\n"
@@ -709,6 +731,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
"/**\n"
" * Use {@link #get$capitalized_name$Map()} instead.\n"
" */\n"
+ "@java.lang.Override\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$type_parameters$> "
"${$get$capitalized_name$$}$() {\n"
@@ -718,6 +741,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$"
"public java.util.Map<$type_parameters$> "
"${$get$capitalized_name$Map$}$() {\n"
@@ -728,6 +752,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
@@ -741,6 +766,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
diff --git a/src/google/protobuf/compiler/java/java_message.cc b/src/google/protobuf/compiler/java/java_message.cc
index 8964f632..209c0b2a 100644
--- a/src/google/protobuf/compiler/java/java_message.cc
+++ b/src/google/protobuf/compiler/java/java_message.cc
@@ -38,9 +38,6 @@
#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
#include <google/protobuf/compiler/java/java_context.h>
@@ -52,9 +49,9 @@
#include <google/protobuf/compiler/java/java_message_builder.h>
#include <google/protobuf/compiler/java/java_message_builder_lite.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
+#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
-#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/strutil.h>
@@ -438,7 +435,8 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
printer->Print(
"$deprecation$$field_name$($field_number$),\n",
- "deprecation", field->options().deprecated() ? "@java.lang.Deprecated " : "",
+ "deprecation",
+ field->options().deprecated() ? "@java.lang.Deprecated " : "",
"field_name", ToUpper(field->name()),
"field_number", SimpleItoa(field->number()));
}
@@ -578,7 +576,7 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
void ImmutableMessageGenerator::
GenerateMessageSerializationMethods(io::Printer* printer) {
- google::protobuf::scoped_array<const FieldDescriptor * > sorted_fields(
+ std::unique_ptr<const FieldDescriptor * []> sorted_fields(
SortFieldsByNumber(descriptor_));
std::vector<const Descriptor::ExtensionRange*> sorted_extensions;
@@ -1216,7 +1214,7 @@ GenerateExtensionRegistrationCode(io::Printer* printer) {
// ===================================================================
void ImmutableMessageGenerator::
GenerateParsingConstructor(io::Printer* printer) {
- google::protobuf::scoped_array<const FieldDescriptor * > sorted_fields(
+ std::unique_ptr<const FieldDescriptor * []> sorted_fields(
SortFieldsByNumber(descriptor_));
printer->Print(
diff --git a/src/google/protobuf/compiler/java/java_message_builder.cc b/src/google/protobuf/compiler/java/java_message_builder.cc
index 43c39b4a..4c67e806 100644
--- a/src/google/protobuf/compiler/java/java_message_builder.cc
+++ b/src/google/protobuf/compiler/java/java_message_builder.cc
@@ -38,9 +38,6 @@
#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
#include <google/protobuf/compiler/java/java_context.h>
@@ -50,9 +47,9 @@
#include <google/protobuf/compiler/java/java_generator_factory.h>
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
+#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
-#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/strutil.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 1ad58c09..f04d394e 100644
--- a/src/google/protobuf/compiler/java/java_message_builder_lite.cc
+++ b/src/google/protobuf/compiler/java/java_message_builder_lite.cc
@@ -38,9 +38,6 @@
#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
#include <google/protobuf/compiler/java/java_context.h>
@@ -50,12 +47,12 @@
#include <google/protobuf/compiler/java/java_generator_factory.h>
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
+#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
-#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/wire_format.h>
-#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
+#include <google/protobuf/stubs/strutil.h>
namespace google {
namespace protobuf {
@@ -109,6 +106,7 @@ Generate(io::Printer* printer) {
// oneofCase() and clearOneof()
printer->Print(vars,
+ "@java.lang.Override\n"
"public $oneof_capitalized_name$Case\n"
" get$oneof_capitalized_name$Case() {\n"
" return instance.get$oneof_capitalized_name$Case();\n"
diff --git a/src/google/protobuf/compiler/java/java_message_field.cc b/src/google/protobuf/compiler/java/java_message_field.cc
index baa7f872..bda4fcc0 100644
--- a/src/google/protobuf/compiler/java/java_message_field.cc
+++ b/src/google/protobuf/compiler/java/java_message_field.cc
@@ -255,7 +255,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
bool support_field_presence = SupportFieldPresence(descriptor_->file());
printer->Print(variables_,
- "private $type$ $name$_ = null;\n");
+ "private $type$ $name$_;\n");
printer->Print(variables_,
// If this builder is non-null, it is used and the other fields are
@@ -444,15 +444,20 @@ void ImmutableMessageFieldGenerator::
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 ($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_,
+ " $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_lite.cc b/src/google/protobuf/compiler/java/java_message_field_lite.cc
index df3e80d4..9cf6f363 100644
--- a/src/google/protobuf/compiler/java/java_message_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_message_field_lite.cc
@@ -147,12 +147,14 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
"}\n");
@@ -160,12 +162,14 @@ GenerateMembers(io::Printer* printer) const {
} else {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $name$_ != null;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
"}\n");
@@ -195,7 +199,11 @@ GenerateMembers(io::Printer* printer) const {
// Field.Builder mergeField(Field value)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.SuppressWarnings({\"ReferenceEquality\"})\n"
"private void merge$capitalized_name$($type$ value) {\n"
+ " if (value == null) {\n"
+ " throw new NullPointerException();\n"
+ " }\n"
" if ($name$_ != null &&\n"
" $name$_ != $type$.getDefaultInstance()) {\n"
" $name$_ =\n"
@@ -223,6 +231,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// boolean hasField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
@@ -231,6 +240,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field getField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
@@ -396,12 +406,14 @@ GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($type$) $oneof_name$_;\n"
@@ -434,6 +446,9 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"private void merge$capitalized_name$($type$ value) {\n"
+ " if (value == null) {\n"
+ " throw new NullPointerException();\n"
+ " }\n"
" if ($has_oneof_case_message$ &&\n"
" $oneof_name$_ != $type$.getDefaultInstance()) {\n"
" $oneof_name$_ = $type$.newBuilder(($type$) $oneof_name$_)\n"
@@ -464,6 +479,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// boolean hasField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
@@ -472,6 +488,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field getField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
@@ -624,6 +641,7 @@ GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.util.List<$type$> "
"${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
@@ -638,12 +656,14 @@ GenerateMembers(io::Printer* printer) const {
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
@@ -761,6 +781,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// List<Field> getRepeatedFieldList()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.util.List<$type$> "
"${$get$capitalized_name$List$}$() {\n"
" return java.util.Collections.unmodifiableList(\n"
@@ -771,6 +792,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// int getRepeatedFieldCount()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return instance.get$capitalized_name$Count();\n"
"}");
@@ -779,6 +801,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field getRepeatedField(int index)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return instance.get$capitalized_name$(index);\n"
"}\n");
diff --git a/src/google/protobuf/compiler/java/java_message_lite.cc b/src/google/protobuf/compiler/java/java_message_lite.cc
index 108504c7..3a512e8d 100644
--- a/src/google/protobuf/compiler/java/java_message_lite.cc
+++ b/src/google/protobuf/compiler/java/java_message_lite.cc
@@ -38,9 +38,6 @@
#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
#include <google/protobuf/compiler/java/java_context.h>
@@ -52,9 +49,9 @@
#include <google/protobuf/compiler/java/java_message_builder.h>
#include <google/protobuf/compiler/java/java_message_builder_lite.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
+#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
-#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/strutil.h>
@@ -310,6 +307,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
" default: return null;\n"
" }\n"
"}\n"
+ "@java.lang.Override\n"
"public int getNumber() {\n"
" return this.value;\n"
"}\n",
@@ -318,6 +316,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
printer->Print("};\n\n");
// oneofCase()
printer->Print(vars,
+ "@java.lang.Override\n"
"public $oneof_capitalized_name$Case\n"
"get$oneof_capitalized_name$Case() {\n"
" return $oneof_capitalized_name$Case.forNumber(\n"
@@ -356,6 +355,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
}
printer->Print(
+ "@java.lang.Override\n"
"@java.lang.SuppressWarnings({\"unchecked\", \"fallthrough\"})\n"
"protected final java.lang.Object dynamicMethod(\n"
" com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,\n"
@@ -369,22 +369,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
printer->Indent();
printer->Indent();
- printer->Print("case IS_INITIALIZED: {\n");
- printer->Indent();
- GenerateDynamicMethodIsInitialized(printer);
- printer->Outdent();
-
- printer->Print("}\n");
-
printer->Print(
- "case MAKE_IMMUTABLE: {\n");
-
- printer->Indent();
- GenerateDynamicMethodMakeImmutable(printer);
- printer->Outdent();
-
- printer->Print(
- "}\n"
"case NEW_BUILDER: {\n");
printer->Indent();
@@ -393,21 +378,38 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
if (!EnableExperimentalRuntimeForLite()) {
printer->Print(
+ "}\n"
+ "case IS_INITIALIZED: {\n");
+ printer->Indent();
+ GenerateDynamicMethodIsInitialized(printer);
+ printer->Outdent();
+
+ printer->Print("}\n");
+
+ printer->Print(
+ "case MAKE_IMMUTABLE: {\n");
+
+ printer->Indent();
+ GenerateDynamicMethodMakeImmutable(printer);
+ printer->Outdent();
+
+ printer->Print(
"}\n"
"case VISIT: {\n");
printer->Indent();
GenerateDynamicMethodVisit(printer);
printer->Outdent();
- }
- printer->Print(
- "}\n"
- "case MERGE_FROM_STREAM: {\n");
+ printer->Print(
+ "}\n"
+ "case MERGE_FROM_STREAM: {\n");
+
+ printer->Indent();
+ GenerateDynamicMethodMergeFromStream(printer);
+ printer->Outdent();
+ }
- printer->Indent();
- GenerateDynamicMethodMergeFromStream(printer);
- printer->Outdent();
printer->Print(
"}\n"
@@ -420,14 +422,20 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
// manipulating static fields but that has exceptional cost on Android as
// it will generate an extra class for every message. Instead, use the
// double-check locking pattern which works just as well.
- " if (PARSER == null) {"
+ //
+ // The "parser" temporary mirrors the "PARSER" field to eliminate a read
+ // at the final return statement.
+ " com.google.protobuf.Parser<$classname$> parser = PARSER;\n"
+ " if (parser == null) {\n"
" synchronized ($classname$.class) {\n"
- " if (PARSER == null) {\n"
- " PARSER = new DefaultInstanceBasedParser(DEFAULT_INSTANCE);\n"
+ " parser = PARSER;\n"
+ " if (parser == null) {\n"
+ " parser = new DefaultInstanceBasedParser(DEFAULT_INSTANCE);\n"
+ " PARSER = parser;\n"
" }\n"
" }\n"
" }\n"
- " return PARSER;\n",
+ " return parser;\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
printer->Outdent();
@@ -475,8 +483,9 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
printer->Print(
"static {\n"
+ " // New instances are implicitly immutable so no need to make\n"
+ " // immutable.\n"
" DEFAULT_INSTANCE = new $classname$();\n"
- " DEFAULT_INSTANCE.makeImmutable();\n"
"}\n"
"\n",
"classname", descriptor_->name());
@@ -491,6 +500,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
"}\n",
"classname", descriptor_->name());
}
+
printer->Print(
"public static $classname$ getDefaultInstance() {\n"
" return DEFAULT_INSTANCE;\n"
@@ -519,6 +529,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
.Generate(printer);
}
+
printer->Outdent();
printer->Print("}\n\n");
}
@@ -528,7 +539,11 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
void ImmutableMessageLiteGenerator::
GenerateMessageSerializationMethods(io::Printer* printer) {
- google::protobuf::scoped_array<const FieldDescriptor * > sorted_fields(
+ if (EnableExperimentalRuntimeForLite()) {
+ return;
+ }
+
+ std::unique_ptr<const FieldDescriptor * []> sorted_fields(
SortFieldsByNumber(descriptor_));
std::vector<const Descriptor::ExtensionRange*> sorted_extensions;
@@ -539,6 +554,7 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
ExtensionRangeOrdering());
printer->Print(
+ "@java.lang.Override\n"
"public void writeTo(com.google.protobuf.CodedOutputStream output)\n"
" throws java.io.IOException {\n");
printer->Indent();
@@ -594,6 +610,7 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
printer->Print(
"}\n"
"\n"
+ "@java.lang.Override\n"
"public int getSerializedSize() {\n"
" int size = memoizedSerializedSize;\n"
" if (size != -1) return size;\n"
@@ -1005,7 +1022,7 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodMergeFromStream(
" done = true;\n"
" break;\n");
- google::protobuf::scoped_array<const FieldDescriptor* > sorted_fields(
+ std::unique_ptr<const FieldDescriptor* []> sorted_fields(
SortFieldsByNumber(descriptor_));
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = sorted_fields[i];
diff --git a/src/google/protobuf/compiler/java/java_plugin_unittest.cc b/src/google/protobuf/compiler/java/java_plugin_unittest.cc
index 3e4910c8..87f687da 100644
--- a/src/google/protobuf/compiler/java/java_plugin_unittest.cc
+++ b/src/google/protobuf/compiler/java/java_plugin_unittest.cc
@@ -35,9 +35,6 @@
// worth.
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/compiler/java/java_generator.h>
#include <google/protobuf/compiler/command_line_interface.h>
@@ -76,7 +73,7 @@ class TestGenerator : public CodeGenerator {
void TryInsert(const string& filename, const string& insertion_point,
GeneratorContext* context) const {
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
context->OpenForInsert(filename, insertion_point));
io::Printer printer(output.get(), '$');
printer.Print("// inserted $name$\n", "name", insertion_point);
diff --git a/src/google/protobuf/compiler/java/java_primitive_field.cc b/src/google/protobuf/compiler/java/java_primitive_field.cc
index 074a6be8..e6ce69c7 100644
--- a/src/google/protobuf/compiler/java/java_primitive_field.cc
+++ b/src/google/protobuf/compiler/java/java_primitive_field.cc
@@ -264,7 +264,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::
@@ -294,11 +296,21 @@ 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");
+ " result.$name$_ = $name$_;\n"
+ " $set_has_field_bit_to_local$;\n");
+ if (IsDefaultValueJavaDefault(descriptor_)) {
+ printer->Print(variables_,
+ "}\n");
+ } else {
+ printer->Print(variables_,
+ "} else {\n"
+ " result.$name$_ = $default$;\n"
+ "}\n");
+ }
+ } else {
+ printer->Print(variables_,
+ "result.$name$_ = $name$_;\n");
}
- printer->Print(variables_,
- "result.$name$_ = $name$_;\n");
}
void ImmutablePrimitiveFieldGenerator::
@@ -633,8 +645,7 @@ GenerateMembers(io::Printer* printer) const {
"}\n");
printer->Annotate("{", "}", descriptor_);
- if (descriptor_->is_packed() &&
- context_->HasGeneratedMethods(descriptor_->containing_type())) {
+ if (descriptor_->is_packed()) {
printer->Print(variables_,
"private int $name$MemoizedSerializedSize = -1;\n");
}
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 f9293171..d2ebc567 100644
--- a/src/google/protobuf/compiler/java/java_primitive_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_primitive_field_lite.cc
@@ -222,6 +222,7 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
@@ -230,6 +231,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_;\n"
"}\n");
@@ -266,6 +268,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
@@ -274,6 +277,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
@@ -488,6 +492,7 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
@@ -496,6 +501,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($boxed_type$) $oneof_name$_;\n"
@@ -528,6 +534,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
@@ -536,6 +543,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
@@ -645,6 +653,7 @@ GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.util.List<$boxed_type$>\n"
" ${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
@@ -652,12 +661,14 @@ GenerateMembers(io::Printer* printer) const {
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $repeated_get$(index);\n"
"}\n");
@@ -711,6 +722,7 @@ void RepeatedImmutablePrimitiveFieldLiteGenerator::
GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.util.List<$boxed_type$>\n"
" ${$get$capitalized_name$List$}$() {\n"
" return java.util.Collections.unmodifiableList(\n"
@@ -719,12 +731,14 @@ GenerateBuilderMembers(io::Printer* printer) const {
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return instance.get$capitalized_name$Count();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return instance.get$capitalized_name$(index);\n"
"}\n");
diff --git a/src/google/protobuf/compiler/java/java_shared_code_generator.cc b/src/google/protobuf/compiler/java/java_shared_code_generator.cc
index 9a42aba9..0cec20b9 100644
--- a/src/google/protobuf/compiler/java/java_shared_code_generator.cc
+++ b/src/google/protobuf/compiler/java/java_shared_code_generator.cc
@@ -33,16 +33,13 @@
#include <google/protobuf/compiler/java/java_shared_code_generator.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
#include <google/protobuf/compiler/code_generator.h>
+#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
-#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/strutil.h>
@@ -69,11 +66,11 @@ void SharedCodeGenerator::Generate(GeneratorContext* context,
string classname = name_resolver_->GetDescriptorClassName(file_);
string filename = package_dir + classname + ".java";
file_list->push_back(filename);
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
+ std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
&annotations);
- google::protobuf::scoped_ptr<io::Printer> printer(
+ std::unique_ptr<io::Printer> printer(
new io::Printer(output.get(), '$',
options_.annotate_code ? &annotation_collector : NULL));
string info_relative_path = classname + ".java.pb.meta";
@@ -108,7 +105,7 @@ void SharedCodeGenerator::Generate(GeneratorContext* context,
"}\n");
if (options_.annotate_code) {
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output(
+ std::unique_ptr<io::ZeroCopyOutputStream> info_output(
context->Open(info_full_path));
annotations.SerializeToZeroCopyStream(info_output.get());
annotation_file_list->push_back(info_full_path);
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 40502270..58a31f5d 100644
--- a/src/google/protobuf/compiler/java/java_shared_code_generator.h
+++ b/src/google/protobuf/compiler/java/java_shared_code_generator.h
@@ -36,9 +36,6 @@
#define GOOGLE_PROTOBUF_COMPILER_JAVA_SHARED_CODE_GENERATOR_H__
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
#include <vector>
@@ -77,7 +74,7 @@ class SharedCodeGenerator {
void GenerateDescriptors(io::Printer* printer);
private:
- google::protobuf::scoped_ptr<ClassNameResolver> name_resolver_;
+ std::unique_ptr<ClassNameResolver> name_resolver_;
const FileDescriptor* file_;
const Options options_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SharedCodeGenerator);
diff --git a/src/google/protobuf/compiler/java/java_string_field.cc b/src/google/protobuf/compiler/java/java_string_field.cc
index 2b6e9381..b08febc0 100644
--- a/src/google/protobuf/compiler/java/java_string_field.cc
+++ b/src/google/protobuf/compiler/java/java_string_field.cc
@@ -405,11 +405,15 @@ GenerateBuildingCode(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
printer->Print(variables_,
"if ($get_has_field_bit_from_local$) {\n"
+ " result.$name$_ = $name$_;\n"
" $set_has_field_bit_to_local$;\n"
+ "} else {\n"
+ " result.$name$_ = $default$;\n"
"}\n");
+ } else {
+ printer->Print(variables_,
+ "result.$name$_ = $name$_;\n");
}
- printer->Print(variables_,
- "result.$name$_ = $name$_;\n");
}
void ImmutableStringFieldGenerator::
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 adda307c..a238c67d 100644
--- a/src/google/protobuf/compiler/java/java_string_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_string_field_lite.cc
@@ -192,6 +192,7 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
@@ -200,12 +201,14 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" return $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public com.google.protobuf.ByteString\n"
" ${$get$capitalized_name$Bytes$}$() {\n"
" return com.google.protobuf.ByteString.copyFromUtf8($name$_);\n"
@@ -249,6 +252,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
@@ -257,6 +261,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
@@ -264,6 +269,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public com.google.protobuf.ByteString\n"
" ${$get$capitalized_name$Bytes$}$() {\n"
" return instance.get$capitalized_name$Bytes();\n"
@@ -419,6 +425,7 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
@@ -427,6 +434,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" java.lang.String ref $default_init$;\n"
" if ($has_oneof_case_message$) {\n"
@@ -438,6 +446,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public com.google.protobuf.ByteString\n"
" ${$get$capitalized_name$Bytes$}$() {\n"
" java.lang.String ref $default_init$;\n"
@@ -489,6 +498,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
@@ -497,6 +507,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
@@ -504,6 +515,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public com.google.protobuf.ByteString\n"
" ${$get$capitalized_name$Bytes$}$() {\n"
" return instance.get$capitalized_name$Bytes();\n"
@@ -641,6 +653,7 @@ GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.util.List<java.lang.String> "
"${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
@@ -648,12 +661,14 @@ GenerateMembers(io::Printer* printer) const {
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.lang.String "
"${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
@@ -661,6 +676,7 @@ GenerateMembers(io::Printer* printer) const {
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public com.google.protobuf.ByteString\n"
" ${$get$capitalized_name$Bytes$}$(int index) {\n"
" return com.google.protobuf.ByteString.copyFromUtf8(\n"
@@ -725,6 +741,7 @@ void RepeatedImmutableStringFieldLiteGenerator::
GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.util.List<java.lang.String>\n"
" ${$get$capitalized_name$List$}$() {\n"
" return java.util.Collections.unmodifiableList(\n"
@@ -733,12 +750,14 @@ GenerateBuilderMembers(io::Printer* printer) const {
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return instance.get$capitalized_name$Count();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.lang.String "
"${$get$capitalized_name$$}$(int index) {\n"
" return instance.get$capitalized_name$(index);\n"
@@ -746,6 +765,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public com.google.protobuf.ByteString\n"
" ${$get$capitalized_name$Bytes$}$(int index) {\n"
" return instance.get$capitalized_name$Bytes(index);\n"
diff --git a/src/google/protobuf/compiler/javanano/javanano_enum.cc b/src/google/protobuf/compiler/javanano/javanano_enum.cc
deleted file mode 100644
index c6e8dfe9..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_enum.cc
+++ /dev/null
@@ -1,143 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#include <map>
-#include <string>
-
-#include <google/protobuf/compiler/javanano/javanano_params.h>
-#include <google/protobuf/compiler/javanano/javanano_enum.h>
-#include <google/protobuf/compiler/javanano/javanano_helpers.h>
-#include <google/protobuf/io/printer.h>
-#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/stubs/strutil.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor, const Params& params)
- : params_(params), descriptor_(descriptor) {
- for (int i = 0; i < descriptor_->value_count(); i++) {
- const EnumValueDescriptor* value = descriptor_->value(i);
- const EnumValueDescriptor* canonical_value =
- descriptor_->FindValueByNumber(value->number());
-
- if (value == canonical_value) {
- canonical_values_.push_back(value);
- } else {
- Alias alias;
- alias.value = value;
- alias.canonical_value = canonical_value;
- aliases_.push_back(alias);
- }
- }
-}
-
-EnumGenerator::~EnumGenerator() {}
-
-void EnumGenerator::Generate(io::Printer* printer) {
- printer->Print(
- "\n"
- "// enum $classname$\n",
- "classname", descriptor_->name());
-
- const string classname = RenameJavaKeywords(descriptor_->name());
-
- // Start of container interface
- // If generating intdefs, we use the container interface as the intdef if
- // present. Otherwise, we just make an empty @interface parallel to the
- // constants.
- bool use_intdef = params_.generate_intdefs();
- bool use_shell_class = params_.java_enum_style();
- if (use_intdef) {
- // @IntDef annotation so tools can enforce correctness
- // Annotations will be discarded by the compiler
- printer->Print("@java.lang.annotation.Retention("
- "java.lang.annotation.RetentionPolicy.SOURCE)\n"
- "@android.support.annotation.IntDef({\n");
- printer->Indent();
- for (int i = 0; i < canonical_values_.size(); i++) {
- const string constant_name =
- RenameJavaKeywords(canonical_values_[i]->name());
- if (use_shell_class) {
- printer->Print("$classname$.$name$,\n",
- "classname", classname,
- "name", constant_name);
- } else {
- printer->Print("$name$,\n", "name", constant_name);
- }
- }
- printer->Outdent();
- printer->Print("})\n");
- }
- if (use_shell_class || use_intdef) {
- printer->Print(
- "public $at_for_intdef$interface $classname$ {\n",
- "classname", classname,
- "at_for_intdef", use_intdef ? "@" : "");
- if (use_shell_class) {
- printer->Indent();
- } else {
- printer->Print("}\n\n");
- }
- }
-
- // Canonical values
- for (int i = 0; i < canonical_values_.size(); i++) {
- printer->Print(
- "public static final int $name$ = $canonical_value$;\n",
- "name", RenameJavaKeywords(canonical_values_[i]->name()),
- "canonical_value", SimpleItoa(canonical_values_[i]->number()));
- }
-
- // Aliases
- for (int i = 0; i < aliases_.size(); i++) {
- printer->Print(
- "public static final int $name$ = $canonical_name$;\n",
- "name", RenameJavaKeywords(aliases_[i].value->name()),
- "canonical_name", RenameJavaKeywords(aliases_[i].canonical_value->name()));
- }
-
- // End of container interface
- if (use_shell_class) {
- printer->Outdent();
- printer->Print("}\n");
- }
-}
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-} // namespace google
diff --git a/src/google/protobuf/compiler/javanano/javanano_enum.h b/src/google/protobuf/compiler/javanano/javanano_enum.h
deleted file mode 100644
index 82e098fc..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_enum.h
+++ /dev/null
@@ -1,87 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_H__
-#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_H__
-
-#include <string>
-#include <vector>
-
-#include <google/protobuf/compiler/javanano/javanano_params.h>
-#include <google/protobuf/descriptor.h>
-
-namespace google {
-namespace protobuf {
- namespace io {
- class Printer; // printer.h
- }
-}
-
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-class EnumGenerator {
- public:
- explicit EnumGenerator(const EnumDescriptor* descriptor, const Params& params);
- ~EnumGenerator();
-
- void Generate(io::Printer* printer);
-
- private:
- const Params& params_;
- 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
- // given numeric value as "canonical" and the rest as aliases of that
- // canonical value.
- std::vector<const EnumValueDescriptor*> canonical_values_;
-
- struct Alias {
- const EnumValueDescriptor* value;
- const EnumValueDescriptor* canonical_value;
- };
- std::vector<Alias> aliases_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator);
-};
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-
-} // namespace google
-#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_H__
diff --git a/src/google/protobuf/compiler/javanano/javanano_enum_field.cc b/src/google/protobuf/compiler/javanano/javanano_enum_field.cc
deleted file mode 100644
index ea67a810..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_enum_field.cc
+++ /dev/null
@@ -1,544 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#include <map>
-#include <string>
-
-#include <google/protobuf/compiler/javanano/javanano_enum_field.h>
-#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/compiler/javanano/javanano_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 {
-namespace javanano {
-
-namespace {
-
-// TODO(kenton): Factor out a "SetCommonFieldVariables()" to get rid of
-// repeat code between this and the other field types.
-void SetEnumVariables(const Params& params,
- const FieldDescriptor* descriptor, std::map<string, string>* variables) {
- (*variables)["name"] =
- RenameJavaKeywords(UnderscoresToCamelCase(descriptor));
- (*variables)["capitalized_name"] =
- RenameJavaKeywords(UnderscoresToCapitalizedCamelCase(descriptor));
- (*variables)["number"] = SimpleItoa(descriptor->number());
- if (params.use_reference_types_for_primitives()
- && !params.reftypes_primitive_enums()
- && !descriptor->is_repeated()) {
- (*variables)["type"] = "java.lang.Integer";
- (*variables)["default"] = "null";
- } else {
- (*variables)["type"] = "int";
- (*variables)["default"] = DefaultValue(params, descriptor);
- }
- (*variables)["repeated_default"] =
- "com.google.protobuf.nano.WireFormatNano.EMPTY_INT_ARRAY";
- (*variables)["tag"] = SimpleItoa(internal::WireFormat::MakeTag(descriptor));
- (*variables)["tag_size"] = SimpleItoa(
- internal::WireFormat::TagSize(descriptor->number(), descriptor->type()));
- (*variables)["non_packed_tag"] = SimpleItoa(
- internal::WireFormatLite::MakeTag(descriptor->number(),
- internal::WireFormat::WireTypeForFieldType(descriptor->type())));
- (*variables)["message_name"] = descriptor->containing_type()->name();
- const EnumDescriptor* enum_type = descriptor->enum_type();
- (*variables)["message_type_intdef"] = "@"
- + ToJavaName(params, enum_type->name(), true,
- enum_type->containing_type(), enum_type->file());
-}
-
-void LoadEnumValues(const Params& params,
- const EnumDescriptor* enum_descriptor, std::vector<string>* canonical_values) {
- string enum_class_name = ClassName(params, enum_descriptor);
- for (int i = 0; i < enum_descriptor->value_count(); i++) {
- const EnumValueDescriptor* value = enum_descriptor->value(i);
- const EnumValueDescriptor* canonical_value =
- enum_descriptor->FindValueByNumber(value->number());
- if (value == canonical_value) {
- canonical_values->push_back(
- enum_class_name + "." + RenameJavaKeywords(value->name()));
- }
- }
-}
-
-void PrintCaseLabels(
- io::Printer* printer, const std::vector<string>& canonical_values) {
- for (int i = 0; i < canonical_values.size(); i++) {
- printer->Print(
- " case $value$:\n",
- "value", canonical_values[i]);
- }
-}
-
-} // namespace
-
-// ===================================================================
-
-EnumFieldGenerator::
-EnumFieldGenerator(const FieldDescriptor* descriptor, const Params& params)
- : FieldGenerator(params), descriptor_(descriptor) {
- SetEnumVariables(params, descriptor, &variables_);
- LoadEnumValues(params, descriptor->enum_type(), &canonical_values_);
-}
-
-EnumFieldGenerator::~EnumFieldGenerator() {}
-
-void EnumFieldGenerator::
-GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const {
- if (params_.generate_intdefs()) {
- printer->Print(variables_, "$message_type_intdef$\n");
- }
- printer->Print(variables_, "public $type$ $name$;\n");
-
- if (params_.generate_has()) {
- printer->Print(variables_,
- "public boolean has$capitalized_name$;\n");
- }
-}
-
-void EnumFieldGenerator::
-GenerateClearCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$name$ = $default$;\n");
-
- if (params_.generate_has()) {
- printer->Print(variables_,
- "has$capitalized_name$ = false;\n");
- }
-}
-
-void EnumFieldGenerator::
-GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "int value = input.readInt32();\n"
- "switch (value) {\n");
- PrintCaseLabels(printer, canonical_values_);
- printer->Print(variables_,
- " this.$name$ = value;\n");
- if (params_.generate_has()) {
- printer->Print(variables_,
- " has$capitalized_name$ = true;\n");
- }
- printer->Print(
- " break;\n"
- "}\n");
- // No default case: in case of invalid value from the wire, preserve old
- // field value. Also we are not storing the invalid value into the unknown
- // fields, because there is no way to get the value out.
-}
-
-void EnumFieldGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- if (descriptor_->is_required() && !params_.generate_has()) {
- // Always serialize a required field if we don't have the 'has' signal.
- printer->Print(variables_,
- "output.writeInt32($number$, this.$name$);\n");
- } else {
- if (params_.generate_has()) {
- printer->Print(variables_,
- "if (this.$name$ != $default$ || has$capitalized_name$) {\n");
- } else {
- printer->Print(variables_,
- "if (this.$name$ != $default$) {\n");
- }
- printer->Print(variables_,
- " output.writeInt32($number$, this.$name$);\n"
- "}\n");
- }
-}
-
-void EnumFieldGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- if (descriptor_->is_required() && !params_.generate_has()) {
- printer->Print(variables_,
- "size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
- " .computeInt32Size($number$, this.$name$);\n");
- } else {
- if (params_.generate_has()) {
- printer->Print(variables_,
- "if (this.$name$ != $default$ || has$capitalized_name$) {\n");
- } else {
- printer->Print(variables_,
- "if (this.$name$ != $default$) {\n");
- }
- printer->Print(variables_,
- " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
- " .computeInt32Size($number$, this.$name$);\n"
- "}\n");
- }
-}
-
-void EnumFieldGenerator::GenerateEqualsCode(io::Printer* printer) const {
- if (params_.use_reference_types_for_primitives()
- && !params_.reftypes_primitive_enums()) {
- printer->Print(variables_,
- "if (this.$name$ == null) {\n"
- " if (other.$name$ != null) {\n"
- " return false;\n"
- " }\n"
- "} else if (!this.$name$.equals(other.$name$)) {\n"
- " return false;"
- "}\n");
- } else {
- // We define equality as serialized form equality. If generate_has(),
- // then if the field value equals the default value in both messages,
- // but one's 'has' field is set and the other's is not, the serialized
- // forms are different and we should return false.
- printer->Print(variables_,
- "if (this.$name$ != other.$name$");
- if (params_.generate_has()) {
- printer->Print(variables_,
- "\n"
- " || (this.$name$ == $default$\n"
- " && this.has$capitalized_name$ != other.has$capitalized_name$)");
- }
- printer->Print(") {\n"
- " return false;\n"
- "}\n");
- }
-}
-
-void EnumFieldGenerator::GenerateHashCodeCode(io::Printer* printer) const {
- printer->Print(
- "result = 31 * result + ");
- if (params_.use_reference_types_for_primitives()
- && !params_.reftypes_primitive_enums()) {
- printer->Print(variables_,
- "(this.$name$ == null ? 0 : this.$name$)");
- } else {
- printer->Print(variables_,
- "this.$name$");
- }
- printer->Print(";\n");
-}
-
-// ===================================================================
-
-AccessorEnumFieldGenerator::
-AccessorEnumFieldGenerator(const FieldDescriptor* descriptor,
- const Params& params, int has_bit_index)
- : FieldGenerator(params), descriptor_(descriptor) {
- SetEnumVariables(params, descriptor, &variables_);
- LoadEnumValues(params, descriptor->enum_type(), &canonical_values_);
- SetBitOperationVariables("has", has_bit_index, &variables_);
-}
-
-AccessorEnumFieldGenerator::~AccessorEnumFieldGenerator() {}
-
-void AccessorEnumFieldGenerator::
-GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const {
- printer->Print(variables_, "private int $name$_;\n");
- if (params_.generate_intdefs()) {
- printer->Print(variables_, "$message_type_intdef$\n");
- }
- printer->Print(variables_,
- "public int get$capitalized_name$() {\n"
- " return $name$_;\n"
- "}\n"
- "public $message_name$ set$capitalized_name$(");
- if (params_.generate_intdefs()) {
- printer->Print(variables_,
- "\n"
- " $message_type_intdef$ ");
- }
- printer->Print(variables_,
- "int value) {\n"
- " $name$_ = value;\n"
- " $set_has$;\n"
- " return this;\n"
- "}\n"
- "public boolean has$capitalized_name$() {\n"
- " return $get_has$;\n"
- "}\n"
- "public $message_name$ clear$capitalized_name$() {\n"
- " $name$_ = $default$;\n"
- " $clear_has$;\n"
- " return this;\n"
- "}\n");
-}
-
-void AccessorEnumFieldGenerator::
-GenerateClearCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$name$_ = $default$;\n");
-}
-
-void AccessorEnumFieldGenerator::
-GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "int value = input.readInt32();\n"
- "switch (value) {\n");
- PrintCaseLabels(printer, canonical_values_);
- printer->Print(variables_,
- " $name$_ = value;\n"
- " $set_has$;\n"
- " break;\n"
- "}\n");
- // No default case: in case of invalid value from the wire, preserve old
- // field value. Also we are not storing the invalid value into the unknown
- // fields, because there is no way to get the value out.
-}
-
-void AccessorEnumFieldGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if ($get_has$) {\n"
- " output.writeInt32($number$, $name$_);\n"
- "}\n");
-}
-
-void AccessorEnumFieldGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if ($get_has$) {\n"
- " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
- " .computeInt32Size($number$, $name$_);\n"
- "}\n");
-}
-
-void AccessorEnumFieldGenerator::
-GenerateEqualsCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if ($different_has$\n"
- " || $name$_ != other.$name$_) {\n"
- " return false;\n"
- "}\n");
-}
-
-void AccessorEnumFieldGenerator::
-GenerateHashCodeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "result = 31 * result + $name$_;\n");
-}
-
-// ===================================================================
-
-RepeatedEnumFieldGenerator::
-RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor, const Params& params)
- : FieldGenerator(params), descriptor_(descriptor) {
- SetEnumVariables(params, descriptor, &variables_);
- LoadEnumValues(params, descriptor->enum_type(), &canonical_values_);
-}
-
-RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() {}
-
-void RepeatedEnumFieldGenerator::
-GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const {
- printer->Print(variables_,
- "public $type$[] $name$;\n");
-}
-
-void RepeatedEnumFieldGenerator::
-GenerateClearCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$name$ = $repeated_default$;\n");
-}
-
-void RepeatedEnumFieldGenerator::
-GenerateMergingCode(io::Printer* printer) const {
- // First, figure out the maximum length of the array, then parse,
- // and finally copy the valid values to the field.
- printer->Print(variables_,
- "int length = com.google.protobuf.nano.WireFormatNano\n"
- " .getRepeatedFieldArrayLength(input, $non_packed_tag$);\n"
- "int[] validValues = new int[length];\n"
- "int validCount = 0;\n"
- "for (int i = 0; i < length; i++) {\n"
- " if (i != 0) { // tag for first value already consumed.\n"
- " input.readTag();\n"
- " }\n"
- " int value = input.readInt32();\n"
- " switch (value) {\n");
- printer->Indent();
- PrintCaseLabels(printer, canonical_values_);
- printer->Outdent();
- printer->Print(variables_,
- " validValues[validCount++] = value;\n"
- " break;\n"
- " }\n"
- "}\n"
- "if (validCount != 0) {\n"
- " int i = this.$name$ == null ? 0 : this.$name$.length;\n"
- " if (i == 0 && validCount == validValues.length) {\n"
- " this.$name$ = validValues;\n"
- " } else {\n"
- " int[] newArray = new int[i + validCount];\n"
- " if (i != 0) {\n"
- " java.lang.System.arraycopy(this.$name$, 0, newArray, 0, i);\n"
- " }\n"
- " java.lang.System.arraycopy(validValues, 0, newArray, i, validCount);\n"
- " this.$name$ = newArray;\n"
- " }\n"
- "}\n");
-}
-
-void RepeatedEnumFieldGenerator::
-GenerateMergingCodeFromPacked(io::Printer* printer) const {
- printer->Print(variables_,
- "int bytes = input.readRawVarint32();\n"
- "int limit = input.pushLimit(bytes);\n"
- "// First pass to compute array length.\n"
- "int arrayLength = 0;\n"
- "int startPos = input.getPosition();\n"
- "while (input.getBytesUntilLimit() > 0) {\n"
- " switch (input.readInt32()) {\n");
- printer->Indent();
- PrintCaseLabels(printer, canonical_values_);
- printer->Outdent();
- printer->Print(variables_,
- " arrayLength++;\n"
- " break;\n"
- " }\n"
- "}\n"
- "if (arrayLength != 0) {\n"
- " input.rewindToPosition(startPos);\n"
- " int i = this.$name$ == null ? 0 : this.$name$.length;\n"
- " int[] newArray = new int[i + arrayLength];\n"
- " if (i != 0) {\n"
- " java.lang.System.arraycopy(this.$name$, 0, newArray, 0, i);\n"
- " }\n"
- " while (input.getBytesUntilLimit() > 0) {\n"
- " int value = input.readInt32();\n"
- " switch (value) {\n");
- printer->Indent();
- printer->Indent();
- PrintCaseLabels(printer, canonical_values_);
- printer->Outdent();
- printer->Outdent();
- printer->Print(variables_,
- " newArray[i++] = value;\n"
- " break;\n"
- " }\n"
- " }\n"
- " this.$name$ = newArray;\n"
- "}\n"
- "input.popLimit(limit);\n");
-}
-
-void RepeatedEnumFieldGenerator::
-GenerateRepeatedDataSizeCode(io::Printer* printer) const {
- // Creates a variable dataSize and puts the serialized size in there.
- printer->Print(variables_,
- "int dataSize = 0;\n"
- "for (int i = 0; i < this.$name$.length; i++) {\n"
- " int element = this.$name$[i];\n"
- " dataSize += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
- " .computeInt32SizeNoTag(element);\n"
- "}\n");
-}
-
-void RepeatedEnumFieldGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ != null && this.$name$.length > 0) {\n");
- printer->Indent();
-
- if (descriptor_->options().packed()) {
- GenerateRepeatedDataSizeCode(printer);
- printer->Print(variables_,
- "output.writeRawVarint32($tag$);\n"
- "output.writeRawVarint32(dataSize);\n"
- "for (int i = 0; i < this.$name$.length; i++) {\n"
- " output.writeRawVarint32(this.$name$[i]);\n"
- "}\n");
- } else {
- printer->Print(variables_,
- "for (int i = 0; i < this.$name$.length; i++) {\n"
- " output.writeInt32($number$, this.$name$[i]);\n"
- "}\n");
- }
-
- printer->Outdent();
- printer->Print(variables_,
- "}\n");
-}
-
-void RepeatedEnumFieldGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ != null && this.$name$.length > 0) {\n");
- printer->Indent();
-
- GenerateRepeatedDataSizeCode(printer);
-
- printer->Print(
- "size += dataSize;\n");
- if (descriptor_->options().packed()) {
- printer->Print(variables_,
- "size += $tag_size$;\n"
- "size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
- " .computeRawVarint32Size(dataSize);\n");
- } else {
- printer->Print(variables_,
- "size += $tag_size$ * this.$name$.length;\n");
- }
-
- printer->Outdent();
-
- printer->Print(
- "}\n");
-}
-
-void RepeatedEnumFieldGenerator::
-GenerateFixClonedCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ != null && this.$name$.length > 0) {\n"
- " cloned.$name$ = this.$name$.clone();\n"
- "}\n");
-}
-
-void RepeatedEnumFieldGenerator::
-GenerateEqualsCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (!com.google.protobuf.nano.InternalNano.equals(\n"
- " this.$name$, other.$name$)) {\n"
- " return false;\n"
- "}\n");
-}
-
-void RepeatedEnumFieldGenerator::
-GenerateHashCodeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "result = 31 * result\n"
- " + com.google.protobuf.nano.InternalNano.hashCode(this.$name$);\n");
-}
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-} // namespace google
diff --git a/src/google/protobuf/compiler/javanano/javanano_enum_field.h b/src/google/protobuf/compiler/javanano/javanano_enum_field.h
deleted file mode 100644
index 8cd0e248..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_enum_field.h
+++ /dev/null
@@ -1,126 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_FIELD_H__
-#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_FIELD_H__
-
-#include <map>
-#include <string>
-#include <vector>
-#include <google/protobuf/compiler/javanano/javanano_field.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-class EnumFieldGenerator : public FieldGenerator {
- public:
- explicit EnumFieldGenerator(
- const FieldDescriptor* descriptor, const Params& params);
- ~EnumFieldGenerator();
-
- // implements FieldGenerator ---------------------------------------
- void GenerateMembers(io::Printer* printer, bool lazy_init) const;
- void GenerateClearCode(io::Printer* printer) const;
- void GenerateMergingCode(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
- void GenerateEqualsCode(io::Printer* printer) const;
- void GenerateHashCodeCode(io::Printer* printer) const;
-
- private:
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
- std::vector<string> canonical_values_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator);
-};
-
-class AccessorEnumFieldGenerator : public FieldGenerator {
- public:
- explicit AccessorEnumFieldGenerator(const FieldDescriptor* descriptor,
- const Params& params, int has_bit_index);
- ~AccessorEnumFieldGenerator();
-
- // implements FieldGenerator ---------------------------------------
- void GenerateMembers(io::Printer* printer, bool lazy_init) const;
- void GenerateClearCode(io::Printer* printer) const;
- void GenerateMergingCode(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
- void GenerateEqualsCode(io::Printer* printer) const;
- void GenerateHashCodeCode(io::Printer* printer) const;
-
- private:
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
- std::vector<string> canonical_values_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(AccessorEnumFieldGenerator);
-};
-
-class RepeatedEnumFieldGenerator : public FieldGenerator {
- public:
- explicit RepeatedEnumFieldGenerator(
- const FieldDescriptor* descriptor, const Params& params);
- ~RepeatedEnumFieldGenerator();
-
- // implements FieldGenerator ---------------------------------------
- void GenerateMembers(io::Printer* printer, bool lazy_init) const;
- void GenerateClearCode(io::Printer* printer) const;
- void GenerateMergingCode(io::Printer* printer) const;
- void GenerateMergingCodeFromPacked(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
- void GenerateEqualsCode(io::Printer* printer) const;
- void GenerateHashCodeCode(io::Printer* printer) const;
- void GenerateFixClonedCode(io::Printer* printer) const;
-
- private:
- void GenerateRepeatedDataSizeCode(io::Printer* printer) const;
-
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
- std::vector<string> canonical_values_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator);
-};
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-
-} // namespace google
-#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_FIELD_H__
diff --git a/src/google/protobuf/compiler/javanano/javanano_extension.cc b/src/google/protobuf/compiler/javanano/javanano_extension.cc
deleted file mode 100644
index 4c61f915..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_extension.cc
+++ /dev/null
@@ -1,150 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: bduff@google.com (Brian Duff)
-
-#include <google/protobuf/compiler/javanano/javanano_extension.h>
-#include <google/protobuf/compiler/javanano/javanano_helpers.h>
-#include <google/protobuf/io/printer.h>
-#include <google/protobuf/stubs/strutil.h>
-#include <google/protobuf/wire_format.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-using internal::WireFormat;
-using internal::WireFormatLite;
-
-namespace {
-
-const char* GetTypeConstantName(const FieldDescriptor::Type type) {
- switch (type) {
- case FieldDescriptor::TYPE_INT32 : return "TYPE_INT32" ;
- case FieldDescriptor::TYPE_UINT32 : return "TYPE_UINT32" ;
- case FieldDescriptor::TYPE_SINT32 : return "TYPE_SINT32" ;
- case FieldDescriptor::TYPE_FIXED32 : return "TYPE_FIXED32" ;
- case FieldDescriptor::TYPE_SFIXED32: return "TYPE_SFIXED32";
- case FieldDescriptor::TYPE_INT64 : return "TYPE_INT64" ;
- case FieldDescriptor::TYPE_UINT64 : return "TYPE_UINT64" ;
- case FieldDescriptor::TYPE_SINT64 : return "TYPE_SINT64" ;
- case FieldDescriptor::TYPE_FIXED64 : return "TYPE_FIXED64" ;
- case FieldDescriptor::TYPE_SFIXED64: return "TYPE_SFIXED64";
- case FieldDescriptor::TYPE_FLOAT : return "TYPE_FLOAT" ;
- case FieldDescriptor::TYPE_DOUBLE : return "TYPE_DOUBLE" ;
- case FieldDescriptor::TYPE_BOOL : return "TYPE_BOOL" ;
- case FieldDescriptor::TYPE_STRING : return "TYPE_STRING" ;
- case FieldDescriptor::TYPE_BYTES : return "TYPE_BYTES" ;
- case FieldDescriptor::TYPE_ENUM : return "TYPE_ENUM" ;
- case FieldDescriptor::TYPE_GROUP : return "TYPE_GROUP" ;
- case FieldDescriptor::TYPE_MESSAGE : return "TYPE_MESSAGE" ;
-
- // No default because we want the compiler to complain if any new
- // types are added.
- }
-
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return NULL;
-}
-
-} // namespace
-
-void SetVariables(const FieldDescriptor* descriptor, const Params params,
- std::map<string, string>* variables) {
- (*variables)["extends"] = ClassName(params, descriptor->containing_type());
- (*variables)["name"] = RenameJavaKeywords(UnderscoresToCamelCase(descriptor));
- bool repeated = descriptor->is_repeated();
- (*variables)["repeated"] = repeated ? "Repeated" : "";
- (*variables)["type"] = GetTypeConstantName(descriptor->type());
- JavaType java_type = GetJavaType(descriptor->type());
- string tag = SimpleItoa(WireFormat::MakeTag(descriptor));
- if (java_type == JAVATYPE_MESSAGE) {
- (*variables)["ext_type"] = "MessageTyped";
- string message_type = ClassName(params, descriptor->message_type());
- if (repeated) {
- message_type += "[]";
- }
- (*variables)["class"] = message_type;
- // For message typed extensions, tags_params contains a single tag
- // for both singular and repeated cases.
- (*variables)["tag_params"] = tag;
- } else {
- (*variables)["ext_type"] = "PrimitiveTyped";
- if (!repeated) {
- (*variables)["class"] = BoxedPrimitiveTypeName(java_type);
- (*variables)["tag_params"] = tag;
- } else {
- (*variables)["class"] = PrimitiveTypeName(java_type) + "[]";
- if (!descriptor->is_packable()) {
- // Non-packable: nonPackedTag == tag, packedTag == 0
- (*variables)["tag_params"] = tag + ", " + tag + ", 0";
- } else if (descriptor->options().packed()) {
- // Packable and packed: tag == packedTag
- string non_packed_tag = SimpleItoa(WireFormatLite::MakeTag(
- descriptor->number(),
- WireFormat::WireTypeForFieldType(descriptor->type())));
- (*variables)["tag_params"] = tag + ", " + non_packed_tag + ", " + tag;
- } else {
- // Packable and not packed: tag == nonPackedTag
- string packed_tag = SimpleItoa(WireFormatLite::MakeTag(
- descriptor->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED));
- (*variables)["tag_params"] = tag + ", " + tag + ", " + packed_tag;
- }
- }
- }
-}
-
-ExtensionGenerator::
-ExtensionGenerator(const FieldDescriptor* descriptor, const Params& params)
- : params_(params), descriptor_(descriptor) {
- SetVariables(descriptor, params, &variables_);
-}
-
-ExtensionGenerator::~ExtensionGenerator() {}
-
-void ExtensionGenerator::Generate(io::Printer* printer) const {
- printer->Print("\n");
- PrintFieldComment(printer, descriptor_);
- printer->Print(variables_,
- "public static final com.google.protobuf.nano.Extension<\n"
- " $extends$,\n"
- " $class$> $name$ =\n"
- " com.google.protobuf.nano.Extension.create$repeated$$ext_type$(\n"
- " com.google.protobuf.nano.Extension.$type$,\n"
- " $class$.class,\n"
- " $tag_params$L);\n");
-}
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-} // namespace google
-
diff --git a/src/google/protobuf/compiler/javanano/javanano_field.cc b/src/google/protobuf/compiler/javanano/javanano_field.cc
deleted file mode 100644
index e31d1177..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_field.cc
+++ /dev/null
@@ -1,209 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#include <google/protobuf/compiler/javanano/javanano_field.h>
-#include <google/protobuf/compiler/javanano/javanano_helpers.h>
-#include <google/protobuf/compiler/javanano/javanano_primitive_field.h>
-#include <google/protobuf/compiler/javanano/javanano_enum_field.h>
-#include <google/protobuf/compiler/javanano/javanano_map_field.h>
-#include <google/protobuf/compiler/javanano/javanano_message_field.h>
-#include <google/protobuf/stubs/common.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-FieldGenerator::~FieldGenerator() {}
-
-bool FieldGenerator::SavedDefaultNeeded() const {
- // No saved default for this field by default.
- // Subclasses whose instances may need saved defaults will override this
- // and return the appropriate value.
- return false;
-}
-
-void FieldGenerator::GenerateInitSavedDefaultCode(io::Printer* printer) const {
- // No saved default for this field by default.
- // Subclasses whose instances may need saved defaults will override this
- // and generate the appropriate init code to the printer.
-}
-
-void FieldGenerator::GenerateMergingCodeFromPacked(io::Printer* printer) const {
- // Reaching here indicates a bug. Cases are:
- // - This FieldGenerator should support packing, but this method should be
- // overridden.
- // - This FieldGenerator doesn't support packing, and this method should
- // never have been called.
- GOOGLE_LOG(FATAL) << "GenerateParsingCodeFromPacked() "
- << "called on field generator that does not support packing.";
-}
-
-// =============================================
-
-FieldGeneratorMap::FieldGeneratorMap(
- const Descriptor* descriptor, const Params &params)
- : descriptor_(descriptor),
- field_generators_(
- new scoped_ptr<FieldGenerator>[descriptor->field_count()]) {
-
- int next_has_bit_index = 0;
- bool saved_defaults_needed = false;
- // Construct all the FieldGenerators.
- for (int i = 0; i < descriptor->field_count(); i++) {
- FieldGenerator* field_generator = MakeGenerator(
- descriptor->field(i), params, &next_has_bit_index);
- saved_defaults_needed = saved_defaults_needed
- || field_generator->SavedDefaultNeeded();
- field_generators_[i].reset(field_generator);
- }
- total_bits_ = next_has_bit_index;
- saved_defaults_needed_ = saved_defaults_needed;
-}
-
-FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field,
- const Params &params, int* next_has_bit_index) {
- JavaType java_type = GetJavaType(field);
- if (field->is_repeated()) {
- switch (java_type) {
- case JAVATYPE_MESSAGE:
- if (IsMapEntry(field->message_type())) {
- return new MapFieldGenerator(field, params);
- } else {
- return new RepeatedMessageFieldGenerator(field, params);
- }
- case JAVATYPE_ENUM:
- return new RepeatedEnumFieldGenerator(field, params);
- default:
- return new RepeatedPrimitiveFieldGenerator(field, params);
- }
- } else if (field->containing_oneof()) {
- switch (java_type) {
- case JAVATYPE_MESSAGE:
- return new MessageOneofFieldGenerator(field, params);
- case JAVATYPE_ENUM:
- default:
- return new PrimitiveOneofFieldGenerator(field, params);
- }
- } else if (params.optional_field_accessors() && field->is_optional()
- && java_type != JAVATYPE_MESSAGE) {
- // We need a has-bit for each primitive/enum field because their default
- // values could be same as explicitly set values. But we don't need it
- // for a message field because they have no defaults and Nano uses 'null'
- // for unset messages, which cannot be set explicitly.
- switch (java_type) {
- case JAVATYPE_ENUM:
- return new AccessorEnumFieldGenerator(
- field, params, (*next_has_bit_index)++);
- default:
- return new AccessorPrimitiveFieldGenerator(
- field, params, (*next_has_bit_index)++);
- }
- } else {
- switch (java_type) {
- case JAVATYPE_MESSAGE:
- return new MessageFieldGenerator(field, params);
- case JAVATYPE_ENUM:
- return new EnumFieldGenerator(field, params);
- default:
- return new PrimitiveFieldGenerator(field, params);
- }
- }
-}
-
-FieldGeneratorMap::~FieldGeneratorMap() {}
-
-const FieldGenerator& FieldGeneratorMap::get(
- const FieldDescriptor* field) const {
- GOOGLE_CHECK_EQ(field->containing_type(), descriptor_);
- return *field_generators_[field->index()];
-}
-
-void SetCommonOneofVariables(const FieldDescriptor* descriptor,
- std::map<string, string>* variables) {
- (*variables)["oneof_name"] =
- UnderscoresToCamelCase(descriptor->containing_oneof());
- (*variables)["oneof_capitalized_name"] =
- UnderscoresToCapitalizedCamelCase(descriptor->containing_oneof());
- (*variables)["oneof_index"] =
- SimpleItoa(descriptor->containing_oneof()->index());
- (*variables)["set_oneof_case"] =
- "this." + (*variables)["oneof_name"] +
- "Case_ = " + SimpleItoa(descriptor->number());
- (*variables)["clear_oneof_case"] =
- "this." + (*variables)["oneof_name"] + "Case_ = 0";
- (*variables)["has_oneof_case"] =
- "this." + (*variables)["oneof_name"] + "Case_ == " +
- SimpleItoa(descriptor->number());
-}
-
-void GenerateOneofFieldEquals(const FieldDescriptor* descriptor,
- const std::map<string, string>& variables,
- io::Printer* printer) {
- if (GetJavaType(descriptor) == JAVATYPE_BYTES) {
- printer->Print(variables,
- "if (this.has$capitalized_name$()) {\n"
- " if (!java.util.Arrays.equals((byte[]) this.$oneof_name$_,\n"
- " (byte[]) other.$oneof_name$_)) {\n"
- " return false;\n"
- " }\n"
- "}\n");
- } else {
- printer->Print(variables,
- "if (this.has$capitalized_name$()) {\n"
- " if (!this.$oneof_name$_.equals(other.$oneof_name$_)) {\n"
- " return false;\n"
- " }\n"
- "}\n");
- }
-}
-
-void GenerateOneofFieldHashCode(const FieldDescriptor* descriptor,
- const std::map<string, string>& variables,
- io::Printer* printer) {
- if (GetJavaType(descriptor) == JAVATYPE_BYTES) {
- printer->Print(variables,
- "result = 31 * result + ($has_oneof_case$\n"
- " ? java.util.Arrays.hashCode((byte[]) this.$oneof_name$_) : 0);\n");
- } else {
- printer->Print(variables,
- "result = 31 * result +\n"
- " ($has_oneof_case$ ? this.$oneof_name$_.hashCode() : 0);\n");
- }
-}
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-} // namespace google
diff --git a/src/google/protobuf/compiler/javanano/javanano_field.h b/src/google/protobuf/compiler/javanano/javanano_field.h
deleted file mode 100644
index 347c888c..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_field.h
+++ /dev/null
@@ -1,130 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_FIELD_H__
-#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_FIELD_H__
-
-#include <map>
-#include <string>
-#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/descriptor.h>
-#include <google/protobuf/compiler/javanano/javanano_params.h>
-
-namespace google {
-namespace protobuf {
- namespace io {
- class Printer; // printer.h
- }
-}
-
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-class FieldGenerator {
- public:
- FieldGenerator(const Params& params) : params_(params) {}
- virtual ~FieldGenerator();
-
- virtual bool SavedDefaultNeeded() const;
- virtual void GenerateInitSavedDefaultCode(io::Printer* printer) const;
-
- // Generates code for Java fields and methods supporting this field.
- // If this field needs a saved default (SavedDefaultNeeded() is true),
- // then @lazy_init controls how the static field for that default value
- // and its initialization code should be generated. If @lazy_init is
- // true, the static field is not declared final and the initialization
- // code is generated only when GenerateInitSavedDefaultCode is called;
- // otherwise, the static field is declared final and initialized inline.
- // GenerateInitSavedDefaultCode will not be called in the latter case.
- virtual void GenerateMembers(
- io::Printer* printer, bool lazy_init) const = 0;
-
- virtual void GenerateClearCode(io::Printer* printer) const = 0;
- virtual void GenerateMergingCode(io::Printer* printer) const = 0;
-
- // Generates code to merge from packed serialized form. The default
- // implementation will fail; subclasses which can handle packed serialized
- // forms will override this and print appropriate code to the printer.
- virtual void GenerateMergingCodeFromPacked(io::Printer* printer) const;
-
- virtual void GenerateSerializationCode(io::Printer* printer) const = 0;
- virtual void GenerateSerializedSizeCode(io::Printer* printer) const = 0;
- virtual void GenerateEqualsCode(io::Printer* printer) const = 0;
- virtual void GenerateHashCodeCode(io::Printer* printer) const = 0;
- virtual void GenerateFixClonedCode(io::Printer* printer) const {}
-
- protected:
- const Params& params_;
- private:
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator);
-};
-
-// Convenience class which constructs FieldGenerators for a Descriptor.
-class FieldGeneratorMap {
- public:
- explicit FieldGeneratorMap(const Descriptor* descriptor, const Params &params);
- ~FieldGeneratorMap();
-
- const FieldGenerator& get(const FieldDescriptor* field) const;
- int total_bits() const { return total_bits_; }
- bool saved_defaults_needed() const { return saved_defaults_needed_; }
-
- private:
- const Descriptor* descriptor_;
- scoped_array<scoped_ptr<FieldGenerator> > field_generators_;
- int total_bits_;
- bool saved_defaults_needed_;
-
- static FieldGenerator* MakeGenerator(const FieldDescriptor* field,
- const Params &params, int* next_has_bit_index);
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
-};
-
-void SetCommonOneofVariables(const FieldDescriptor* descriptor,
- std::map<string, string>* variables);
-void GenerateOneofFieldEquals(const FieldDescriptor* descriptor,
- const std::map<string, string>& variables,
- io::Printer* printer);
-void GenerateOneofFieldHashCode(const FieldDescriptor* descriptor,
- const std::map<string, string>& variables,
- io::Printer* printer);
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-
-} // namespace google
-#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_FIELD_H__
diff --git a/src/google/protobuf/compiler/javanano/javanano_file.cc b/src/google/protobuf/compiler/javanano/javanano_file.cc
deleted file mode 100644
index 7a661a42..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_file.cc
+++ /dev/null
@@ -1,263 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#include <iostream>
-
-#include <google/protobuf/compiler/javanano/javanano_file.h>
-#include <google/protobuf/compiler/javanano/javanano_enum.h>
-#include <google/protobuf/compiler/javanano/javanano_extension.h>
-#include <google/protobuf/compiler/javanano/javanano_helpers.h>
-#include <google/protobuf/compiler/javanano/javanano_message.h>
-#include <google/protobuf/compiler/code_generator.h>
-#include <google/protobuf/io/printer.h>
-#include <google/protobuf/io/zero_copy_stream.h>
-#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/stubs/strutil.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-namespace {
-
-// Recursively searches the given message to see if it contains any extensions.
-bool UsesExtensions(const Message& message) {
- const Reflection* reflection = message.GetReflection();
-
- // We conservatively assume that unknown fields are extensions.
- if (reflection->GetUnknownFields(message).field_count() > 0) return true;
-
- std::vector<const FieldDescriptor*> fields;
- reflection->ListFields(message, &fields);
-
- for (int i = 0; i < fields.size(); i++) {
- if (fields[i]->is_extension()) return true;
-
- if (fields[i]->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- if (fields[i]->is_repeated()) {
- int size = reflection->FieldSize(message, fields[i]);
- for (int j = 0; j < size; j++) {
- const Message& sub_message =
- reflection->GetRepeatedMessage(message, fields[i], j);
- if (UsesExtensions(sub_message)) return true;
- }
- } else {
- const Message& sub_message = reflection->GetMessage(message, fields[i]);
- if (UsesExtensions(sub_message)) return true;
- }
- }
- }
-
- return false;
-}
-
-} // namespace
-
-FileGenerator::FileGenerator(const FileDescriptor* file, const Params& params)
- : file_(file),
- params_(params),
- java_package_(FileJavaPackage(params, file)),
- classname_(FileClassName(params, file)) {}
-
-FileGenerator::~FileGenerator() {}
-
-bool FileGenerator::Validate(string* error) {
- // Check for extensions
- FileDescriptorProto file_proto;
- file_->CopyTo(&file_proto);
- if (UsesExtensions(file_proto) && !params_.store_unknown_fields()) {
- error->assign(file_->name());
- error->append(
- ": Java NANO_RUNTIME only supports extensions when the "
- "'store_unknown_fields' generator option is 'true'.");
- return false;
- }
-
- if (file_->service_count() != 0 && !params_.ignore_services()) {
- error->assign(file_->name());
- error->append(
- ": Java NANO_RUNTIME does not support services\"");
- return false;
- }
-
- if (!IsOuterClassNeeded(params_, file_)) {
- return true;
- }
-
- // Check whether legacy javanano generator would omit the outer class.
- if (!params_.has_java_outer_classname(file_->name())
- && file_->message_type_count() == 1
- && file_->enum_type_count() == 0 && file_->extension_count() == 0) {
- std::cout << "INFO: " << file_->name() << ":" << std::endl;
- std::cout << "Javanano generator has changed to align with java generator. "
- "An outer class will be created for this file and the single message "
- "in the file will become a nested class. Use java_multiple_files to "
- "skip generating the outer class, or set an explicit "
- "java_outer_classname to suppress this message." << std::endl;
- }
-
- // Check that no class name matches the file's class name. This is a common
- // problem that leads to Java compile errors that can be hard to understand.
- // It's especially bad when using the java_multiple_files, since we would
- // end up overwriting the outer class with one of the inner ones.
- bool found_conflict = false;
- for (int i = 0; !found_conflict && i < file_->message_type_count(); i++) {
- if (file_->message_type(i)->name() == classname_) {
- found_conflict = true;
- }
- }
- if (params_.java_enum_style()) {
- for (int i = 0; !found_conflict && i < file_->enum_type_count(); i++) {
- if (file_->enum_type(i)->name() == classname_) {
- found_conflict = true;
- }
- }
- }
- if (found_conflict) {
- error->assign(file_->name());
- error->append(
- ": Cannot generate Java output because the file's outer class name, \"");
- error->append(classname_);
- error->append(
- "\", matches the name of one of the types declared inside it. "
- "Please either rename the type or use the java_outer_classname "
- "option to specify a different outer class name for the .proto file.");
- return false;
- }
- return true;
-}
-
-void FileGenerator::Generate(io::Printer* printer) {
- // We don't import anything because we refer to all classes by their
- // fully-qualified names in the generated source.
- printer->Print(
- "// Generated by the protocol buffer compiler. DO NOT EDIT!\n");
- if (!java_package_.empty()) {
- printer->Print(
- "\n"
- "package $package$;\n",
- "package", java_package_);
- }
-
- // Note: constants (from enums, emitted in the loop below) may have the same names as constants
- // in the nested classes. This causes Java warnings, but is not fatal, so we suppress those
- // warnings here in the top-most class declaration.
- printer->Print(
- "\n"
- "@SuppressWarnings(\"hiding\")\n"
- "public interface $classname$ {\n",
- "classname", classname_);
- printer->Indent();
-
- // -----------------------------------------------------------------
-
- // Extensions.
- for (int i = 0; i < file_->extension_count(); i++) {
- ExtensionGenerator(file_->extension(i), params_).Generate(printer);
- }
-
- // Enums.
- for (int i = 0; i < file_->enum_type_count(); i++) {
- EnumGenerator(file_->enum_type(i), params_).Generate(printer);
- }
-
- // Messages.
- if (!params_.java_multiple_files(file_->name())) {
- for (int i = 0; i < file_->message_type_count(); i++) {
- MessageGenerator(file_->message_type(i), params_).Generate(printer);
- }
- }
-
- // Static variables.
- for (int i = 0; i < file_->message_type_count(); i++) {
- // TODO(kenton): Reuse MessageGenerator objects?
- MessageGenerator(file_->message_type(i), params_).GenerateStaticVariables(printer);
- }
-
- printer->Outdent();
- printer->Print(
- "}\n");
-}
-
-template<typename GeneratorClass, typename DescriptorClass>
-static void GenerateSibling(const string& package_dir,
- const string& java_package,
- const DescriptorClass* descriptor,
- GeneratorContext* output_directory,
- std::vector<string>* file_list,
- const Params& params) {
- string filename = package_dir + descriptor->name() + ".java";
- file_list->push_back(filename);
-
- scoped_ptr<io::ZeroCopyOutputStream> output(
- output_directory->Open(filename));
- io::Printer printer(output.get(), '$');
-
- printer.Print(
- "// Generated by the protocol buffer compiler. DO NOT EDIT!\n");
- if (!java_package.empty()) {
- printer.Print(
- "\n"
- "package $package$;\n",
- "package", java_package);
- }
-
- GeneratorClass(descriptor, params).Generate(&printer);
-}
-
-void FileGenerator::GenerateSiblings(const string& package_dir,
- GeneratorContext* output_directory,
- std::vector<string>* file_list) {
- if (params_.java_multiple_files(file_->name())) {
- for (int i = 0; i < file_->message_type_count(); i++) {
- GenerateSibling<MessageGenerator>(package_dir, java_package_,
- file_->message_type(i),
- output_directory, file_list, params_);
- }
-
- if (params_.java_enum_style()) {
- for (int i = 0; i < file_->enum_type_count(); i++) {
- GenerateSibling<EnumGenerator>(package_dir, java_package_,
- file_->enum_type(i),
- output_directory, file_list, params_);
- }
- }
- }
-}
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-} // namespace google
diff --git a/src/google/protobuf/compiler/javanano/javanano_file.h b/src/google/protobuf/compiler/javanano/javanano_file.h
deleted file mode 100644
index 4ad3868c..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_file.h
+++ /dev/null
@@ -1,94 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_FILE_H__
-#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_FILE_H__
-
-#include <string>
-#include <vector>
-#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/compiler/javanano/javanano_params.h>
-
-namespace google {
-namespace protobuf {
- class FileDescriptor; // descriptor.h
- namespace io {
- class Printer; // printer.h
- }
- namespace compiler {
- class GeneratorContext; // code_generator.h
- }
-}
-
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-class FileGenerator {
- public:
- explicit FileGenerator(const FileDescriptor* file, const Params& params);
- ~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);
-
- 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,
- GeneratorContext* output_directory,
- std::vector<string>* file_list);
-
- const string& java_package() { return java_package_; }
- const string& classname() { return classname_; }
-
- private:
- const FileDescriptor* file_;
- const Params& params_;
- string java_package_;
- string classname_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator);
-};
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-
-} // namespace google
-#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_FILE_H__
diff --git a/src/google/protobuf/compiler/javanano/javanano_generator.cc b/src/google/protobuf/compiler/javanano/javanano_generator.cc
deleted file mode 100644
index fd7151b1..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_generator.cc
+++ /dev/null
@@ -1,230 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#include <google/protobuf/compiler/javanano/javanano_params.h>
-#include <google/protobuf/compiler/javanano/javanano_generator.h>
-#include <google/protobuf/compiler/javanano/javanano_file.h>
-#include <google/protobuf/compiler/javanano/javanano_helpers.h>
-#include <google/protobuf/io/printer.h>
-#include <google/protobuf/io/zero_copy_stream.h>
-#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/stubs/strutil.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-namespace {
-
-string TrimString(const string& s) {
- string::size_type start = s.find_first_not_of(" \n\r\t");
- if (start == string::npos) {
- return "";
- }
- string::size_type end = s.find_last_not_of(" \n\r\t") + 1;
- return s.substr(start, end - start);
-}
-
-} // namespace
-
-void UpdateParamsRecursively(Params& params,
- const FileDescriptor* file) {
- // Add any parameters for this file
- if (file->options().has_java_outer_classname()) {
- params.set_java_outer_classname(
- file->name(), file->options().java_outer_classname());
- }
- if (file->options().has_java_package()) {
- string result = file->options().java_package();
- if (!result.empty()) {
- result += ".";
- }
- result += "nano";
- params.set_java_package(
- file->name(), result);
- }
- if (file->options().has_java_multiple_files()) {
- params.set_java_multiple_files(
- file->name(), file->options().java_multiple_files());
- }
-
- // Loop through all dependent files recursively
- // adding dep
- for (int i = 0; i < file->dependency_count(); i++) {
- UpdateParamsRecursively(params, file->dependency(i));
- }
-}
-
-JavaNanoGenerator::JavaNanoGenerator() {}
-JavaNanoGenerator::~JavaNanoGenerator() {}
-
-bool JavaNanoGenerator::Generate(const FileDescriptor* file,
- const string& parameter,
- GeneratorContext* output_directory,
- string* error) const {
- std::vector<std::pair<string, string> > options;
-
- ParseGeneratorParameter(parameter, &options);
-
- // -----------------------------------------------------------------
- // parse generator options
-
- // Name a file where we will write a list of generated file names, one
- // per line.
- string output_list_file;
- Params params(file->name());
-
- // Update per file params
- UpdateParamsRecursively(params, file);
-
- // Replace any existing options with ones from command line
- for (int i = 0; i < options.size(); i++) {
- string option_name = TrimString(options[i].first);
- string option_value = TrimString(options[i].second);
- if (option_name == "output_list_file") {
- output_list_file = option_value;
- } else if (option_name == "java_package") {
- std::vector<string> parts;
- SplitStringUsing(option_value, "|", &parts);
- if (parts.size() != 2) {
- *error = "Bad java_package, expecting filename|PackageName found '"
- + option_value + "'";
- return false;
- }
- params.set_java_package(parts[0], parts[1]);
- } else if (option_name == "java_outer_classname") {
- std::vector<string> parts;
- SplitStringUsing(option_value, "|", &parts);
- if (parts.size() != 2) {
- *error = "Bad java_outer_classname, "
- "expecting filename|ClassName found '"
- + option_value + "'";
- return false;
- }
- params.set_java_outer_classname(parts[0], parts[1]);
- } else if (option_name == "store_unknown_fields") {
- params.set_store_unknown_fields(option_value == "true");
- } else if (option_name == "java_multiple_files") {
- params.set_override_java_multiple_files(option_value == "true");
- } else if (option_name == "java_nano_generate_has") {
- params.set_generate_has(option_value == "true");
- } else if (option_name == "enum_style") {
- params.set_java_enum_style(option_value == "java");
- } else if (option_name == "optional_field_style") {
- params.set_optional_field_accessors(option_value == "accessors");
- params.set_use_reference_types_for_primitives(option_value == "reftypes"
- || option_value == "reftypes_compat_mode");
- params.set_reftypes_primitive_enums(
- option_value == "reftypes_compat_mode");
- if (option_value == "reftypes_compat_mode") {
- params.set_generate_clear(false);
- }
- } else if (option_name == "generate_equals") {
- params.set_generate_equals(option_value == "true");
- } else if (option_name == "ignore_services") {
- params.set_ignore_services(option_value == "true");
- } else if (option_name == "parcelable_messages") {
- params.set_parcelable_messages(option_value == "true");
- } else if (option_name == "generate_clone") {
- params.set_generate_clone(option_value == "true");
- } else if (option_name == "generate_intdefs") {
- params.set_generate_intdefs(option_value == "true");
- } else if (option_name == "generate_clear") {
- params.set_generate_clear(option_value == "true");
- } else {
- *error = "Ignore unknown javanano generator option: " + option_name;
- }
- }
-
- // Check illegal parameter combinations
- // Note: the enum-like optional_field_style generator param ensures
- // that we can never have illegal combinations of field styles
- // (e.g. reftypes and accessors can't be on at the same time).
- if (params.generate_has()
- && (params.optional_field_accessors()
- || params.use_reference_types_for_primitives())) {
- error->assign("java_nano_generate_has=true cannot be used in conjunction"
- " with optional_field_style=accessors or optional_field_style=reftypes");
- return false;
- }
-
- // -----------------------------------------------------------------
-
- FileGenerator file_generator(file, params);
- if (!file_generator.Validate(error)) {
- return false;
- }
-
- string package_dir =
- StringReplace(file_generator.java_package(), ".", "/", true);
- if (!package_dir.empty()) package_dir += "/";
-
- std::vector<string> all_files;
-
- if (IsOuterClassNeeded(params, file)) {
- string java_filename = package_dir;
- java_filename += file_generator.classname();
- java_filename += ".java";
- all_files.push_back(java_filename);
-
- // Generate main java file.
- scoped_ptr<io::ZeroCopyOutputStream> output(
- output_directory->Open(java_filename));
- io::Printer printer(output.get(), '$');
- file_generator.Generate(&printer);
- }
-
- // Generate sibling files.
- file_generator.GenerateSiblings(package_dir, output_directory, &all_files);
-
- // Generate output list if requested.
- if (!output_list_file.empty()) {
- // Generate output list. This is just a simple text file placed in a
- // deterministic location which lists the .java files being generated.
- scoped_ptr<io::ZeroCopyOutputStream> srclist_raw_output(
- output_directory->Open(output_list_file));
- io::Printer srclist_printer(srclist_raw_output.get(), '$');
- for (int i = 0; i < all_files.size(); i++) {
- srclist_printer.Print("$filename$\n", "filename", all_files[i]);
- }
- }
-
- return true;
-}
-
-} // namespace java
-} // namespace compiler
-} // namespace protobuf
-} // namespace google
diff --git a/src/google/protobuf/compiler/javanano/javanano_generator.h b/src/google/protobuf/compiler/javanano/javanano_generator.h
deleted file mode 100644
index 6f9f7f2a..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_generator.h
+++ /dev/null
@@ -1,72 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-//
-// Generates Java nano code for a given .proto file.
-
-#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_NANO_GENERATOR_H__
-#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_NANO_GENERATOR_H__
-
-#include <string>
-#include <google/protobuf/compiler/code_generator.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-// CodeGenerator implementation which generates Java nano code. If you create your
-// own protocol compiler binary and you want it to support Java output for the
-// nano runtime, you can do so by registering an instance of this CodeGenerator with
-// the CommandLineInterface in your main() function.
-class LIBPROTOC_EXPORT JavaNanoGenerator : public CodeGenerator {
- public:
- JavaNanoGenerator();
- ~JavaNanoGenerator();
-
- // implements CodeGenerator ----------------------------------------
- bool Generate(const FileDescriptor* file,
- const string& parameter,
- GeneratorContext* output_directory,
- string* error) const;
-
- private:
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(JavaNanoGenerator);
-};
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-
-} // namespace google
-#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_NANO_GENERATOR_H__
diff --git a/src/google/protobuf/compiler/javanano/javanano_helpers.cc b/src/google/protobuf/compiler/javanano/javanano_helpers.cc
deleted file mode 100644
index 1927ba12..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_helpers.cc
+++ /dev/null
@@ -1,591 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#include <limits>
-#include <vector>
-
-#include <google/protobuf/compiler/javanano/javanano_helpers.h>
-#include <google/protobuf/compiler/javanano/javanano_params.h>
-#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/stubs/hash.h>
-#include <google/protobuf/stubs/strutil.h>
-#include <google/protobuf/stubs/substitute.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-const char kThickSeparator[] =
- "// ===================================================================\n";
-const char kThinSeparator[] =
- "// -------------------------------------------------------------------\n";
-
-class RenameKeywords {
- private:
- hash_set<string> java_keywords_set_;
-
- public:
- RenameKeywords() {
- static const char* kJavaKeywordsList[] = {
- // Reserved Java Keywords
- "abstract", "assert", "boolean", "break", "byte", "case", "catch",
- "char", "class", "const", "continue", "default", "do", "double", "else",
- "enum", "extends", "final", "finally", "float", "for", "goto", "if",
- "implements", "import", "instanceof", "int", "interface", "long",
- "native", "new", "package", "private", "protected", "public", "return",
- "short", "static", "strictfp", "super", "switch", "synchronized",
- "this", "throw", "throws", "transient", "try", "void", "volatile", "while",
-
- // Reserved Keywords for Literals
- "false", "null", "true"
- };
-
- for (int i = 0; i < GOOGLE_ARRAYSIZE(kJavaKeywordsList); i++) {
- java_keywords_set_.insert(kJavaKeywordsList[i]);
- }
- }
-
- // Used to rename the a field name if it's a java keyword. Specifically
- // this is used to rename the ["name"] or ["capitalized_name"] field params.
- // (http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html)
- string RenameJavaKeywordsImpl(const string& input) {
- string result = input;
-
- if (java_keywords_set_.find(result) != java_keywords_set_.end()) {
- result += "_";
- }
-
- return result;
- }
-
-};
-
-static RenameKeywords sRenameKeywords;
-
-namespace {
-
-const char* kDefaultPackage = "";
-
-const string& FieldName(const FieldDescriptor* field) {
- // Groups are hacky: The name of the field is just the lower-cased name
- // of the group type. In Java, though, we would like to retain the original
- // capitalization of the type name.
- if (field->type() == FieldDescriptor::TYPE_GROUP) {
- return field->message_type()->name();
- } else {
- return field->name();
- }
-}
-
-string UnderscoresToCamelCaseImpl(const string& input, bool cap_next_letter) {
- string result;
- // Note: I distrust ctype.h due to locales.
- for (int i = 0; i < input.size(); i++) {
- if ('a' <= input[i] && input[i] <= 'z') {
- if (cap_next_letter) {
- result += input[i] + ('A' - 'a');
- } else {
- result += input[i];
- }
- cap_next_letter = false;
- } else if ('A' <= input[i] && input[i] <= 'Z') {
- if (i == 0 && !cap_next_letter) {
- // Force first letter to lower-case unless explicitly told to
- // capitalize it.
- result += input[i] + ('a' - 'A');
- } else {
- // Capital letters after the first are left as-is.
- result += input[i];
- }
- cap_next_letter = false;
- } else if ('0' <= input[i] && input[i] <= '9') {
- result += input[i];
- cap_next_letter = true;
- } else {
- cap_next_letter = true;
- }
- }
- return result;
-}
-
-} // namespace
-
-string UnderscoresToCamelCase(const FieldDescriptor* field) {
- return UnderscoresToCamelCaseImpl(FieldName(field), false);
-}
-
-string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field) {
- return UnderscoresToCamelCaseImpl(FieldName(field), true);
-}
-
-string UnderscoresToCamelCase(const MethodDescriptor* method) {
- return UnderscoresToCamelCaseImpl(method->name(), false);
-}
-
-string UnderscoresToCamelCase(const OneofDescriptor* oneof) {
- return UnderscoresToCamelCaseImpl(oneof->name(), false);
-}
-
-string UnderscoresToCapitalizedCamelCase(const OneofDescriptor* oneof) {
- return UnderscoresToCamelCaseImpl(oneof->name(), true);
-}
-
-string RenameJavaKeywords(const string& input) {
- return sRenameKeywords.RenameJavaKeywordsImpl(input);
-}
-
-string StripProto(const string& filename) {
- if (HasSuffixString(filename, ".protodevel")) {
- return StripSuffixString(filename, ".protodevel");
- } else {
- return StripSuffixString(filename, ".proto");
- }
-}
-
-string FileClassName(const Params& params, const FileDescriptor* file) {
- if (params.has_java_outer_classname(file->name())) {
- return params.java_outer_classname(file->name());
- } else {
- // Use the filename itself with underscores removed
- // and a CamelCase style name.
- string basename;
- string::size_type last_slash = file->name().find_last_of('/');
- if (last_slash == string::npos) {
- basename = file->name();
- } else {
- basename = file->name().substr(last_slash + 1);
- }
- return UnderscoresToCamelCaseImpl(StripProto(basename), true);
- }
-}
-
-string FileJavaPackage(const Params& params, const FileDescriptor* file) {
- if (params.has_java_package(file->name())) {
- return params.java_package(file->name());
- } else {
- string result = kDefaultPackage;
- if (!file->package().empty()) {
- if (!result.empty()) result += '.';
- result += file->package();
- }
-
- if (!result.empty()) {
- result += ".";
- }
- result += "nano";
-
- return result;
- }
-}
-
-bool IsOuterClassNeeded(const Params& params, const FileDescriptor* file) {
- // If java_multiple_files is false, the outer class is always needed.
- if (!params.java_multiple_files(file->name())) {
- return true;
- }
-
- // File-scope extensions need the outer class as the scope.
- if (file->extension_count() != 0) {
- return true;
- }
-
- // If container interfaces are not generated, file-scope enums need the
- // outer class as the scope.
- if (file->enum_type_count() != 0 && !params.java_enum_style()) {
- return true;
- }
-
- return false;
-}
-
-string ToJavaName(const Params& params, const string& name, bool is_class,
- const Descriptor* parent, const FileDescriptor* file) {
- string result;
- if (parent != NULL) {
- result.append(ClassName(params, parent));
- } else if (is_class && params.java_multiple_files(file->name())) {
- result.append(FileJavaPackage(params, file));
- } else {
- result.append(ClassName(params, file));
- }
- if (!result.empty()) result.append(1, '.');
- result.append(RenameJavaKeywords(name));
- return result;
-}
-
-string ClassName(const Params& params, const FileDescriptor* descriptor) {
- string result = FileJavaPackage(params, descriptor);
- if (!result.empty()) result += '.';
- result += FileClassName(params, descriptor);
- return result;
-}
-
-string ClassName(const Params& params, const EnumDescriptor* descriptor) {
- const Descriptor* parent = descriptor->containing_type();
- // When using Java enum style, an enum's class name contains the enum name.
- // Use the standard ToJavaName translation.
- if (params.java_enum_style()) {
- return ToJavaName(params, descriptor->name(), true, parent,
- descriptor->file());
- }
- // Otherwise the enum members are accessed from the enclosing class.
- if (parent != NULL) {
- return ClassName(params, parent);
- } else {
- return ClassName(params, descriptor->file());
- }
-}
-
-string FieldConstantName(const FieldDescriptor *field) {
- string name = field->name() + "_FIELD_NUMBER";
- UpperString(&name);
- return name;
-}
-
-string FieldDefaultConstantName(const FieldDescriptor *field) {
- return "_" + RenameJavaKeywords(UnderscoresToCamelCase(field)) + "Default";
-}
-
-void PrintFieldComment(io::Printer* printer, const FieldDescriptor* field) {
- // We don't want to print group bodies so we cut off after the first line
- // (the second line for extensions).
- string def = field->DebugString();
- string::size_type first_line_end = def.find_first_of('\n');
- printer->Print("// $def$\n",
- "def", def.substr(0, first_line_end));
- if (field->is_extension()) {
- string::size_type second_line_start = first_line_end + 1;
- string::size_type second_line_length =
- def.find('\n', second_line_start) - second_line_start;
- printer->Print("// $def$\n",
- "def", def.substr(second_line_start, second_line_length));
- }
-}
-
-JavaType GetJavaType(FieldDescriptor::Type field_type) {
- switch (field_type) {
- case FieldDescriptor::TYPE_INT32:
- case FieldDescriptor::TYPE_UINT32:
- case FieldDescriptor::TYPE_SINT32:
- case FieldDescriptor::TYPE_FIXED32:
- case FieldDescriptor::TYPE_SFIXED32:
- return JAVATYPE_INT;
-
- case FieldDescriptor::TYPE_INT64:
- case FieldDescriptor::TYPE_UINT64:
- case FieldDescriptor::TYPE_SINT64:
- case FieldDescriptor::TYPE_FIXED64:
- case FieldDescriptor::TYPE_SFIXED64:
- return JAVATYPE_LONG;
-
- case FieldDescriptor::TYPE_FLOAT:
- return JAVATYPE_FLOAT;
-
- case FieldDescriptor::TYPE_DOUBLE:
- return JAVATYPE_DOUBLE;
-
- case FieldDescriptor::TYPE_BOOL:
- return JAVATYPE_BOOLEAN;
-
- case FieldDescriptor::TYPE_STRING:
- return JAVATYPE_STRING;
-
- case FieldDescriptor::TYPE_BYTES:
- return JAVATYPE_BYTES;
-
- case FieldDescriptor::TYPE_ENUM:
- return JAVATYPE_ENUM;
-
- case FieldDescriptor::TYPE_GROUP:
- case FieldDescriptor::TYPE_MESSAGE:
- return JAVATYPE_MESSAGE;
-
- // No default because we want the compiler to complain if any new
- // types are added.
- }
-
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return JAVATYPE_INT;
-}
-
-string PrimitiveTypeName(JavaType type) {
- switch (type) {
- case JAVATYPE_INT : return "int";
- case JAVATYPE_LONG : return "long";
- case JAVATYPE_FLOAT : return "float";
- case JAVATYPE_DOUBLE : return "double";
- case JAVATYPE_BOOLEAN: return "boolean";
- case JAVATYPE_STRING : return "java.lang.String";
- case JAVATYPE_BYTES : return "byte[]";
- case JAVATYPE_ENUM : return "int";
- case JAVATYPE_MESSAGE: return "";
-
- // No default because we want the compiler to complain if any new
- // JavaTypes are added.
- }
-
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return "";
-}
-
-string BoxedPrimitiveTypeName(JavaType type) {
- switch (type) {
- case JAVATYPE_INT : return "java.lang.Integer";
- case JAVATYPE_LONG : return "java.lang.Long";
- case JAVATYPE_FLOAT : return "java.lang.Float";
- case JAVATYPE_DOUBLE : return "java.lang.Double";
- case JAVATYPE_BOOLEAN: return "java.lang.Boolean";
- case JAVATYPE_STRING : return "java.lang.String";
- case JAVATYPE_BYTES : return "byte[]";
- case JAVATYPE_ENUM : return "java.lang.Integer";
- case JAVATYPE_MESSAGE: return "";
-
- // No default because we want the compiler to complain if any new
- // JavaTypes are added.
- }
-
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return "";
-}
-
-string EmptyArrayName(const Params& params, const FieldDescriptor* field) {
- switch (GetJavaType(field)) {
- case JAVATYPE_INT : return "com.google.protobuf.nano.WireFormatNano.EMPTY_INT_ARRAY";
- case JAVATYPE_LONG : return "com.google.protobuf.nano.WireFormatNano.EMPTY_LONG_ARRAY";
- case JAVATYPE_FLOAT : return "com.google.protobuf.nano.WireFormatNano.EMPTY_FLOAT_ARRAY";
- case JAVATYPE_DOUBLE : return "com.google.protobuf.nano.WireFormatNano.EMPTY_DOUBLE_ARRAY";
- case JAVATYPE_BOOLEAN: return "com.google.protobuf.nano.WireFormatNano.EMPTY_BOOLEAN_ARRAY";
- case JAVATYPE_STRING : return "com.google.protobuf.nano.WireFormatNano.EMPTY_STRING_ARRAY";
- case JAVATYPE_BYTES : return "com.google.protobuf.nano.WireFormatNano.EMPTY_BYTES_ARRAY";
- case JAVATYPE_ENUM : return "com.google.protobuf.nano.WireFormatNano.EMPTY_INT_ARRAY";
- case JAVATYPE_MESSAGE: return ClassName(params, field->message_type()) + ".EMPTY_ARRAY";
-
- // No default because we want the compiler to complain if any new
- // JavaTypes are added.
- }
-
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return "";
-}
-
-string DefaultValue(const Params& params, const FieldDescriptor* field) {
- if (field->label() == FieldDescriptor::LABEL_REPEATED) {
- return EmptyArrayName(params, field);
- }
-
- if (params.use_reference_types_for_primitives()) {
- if (params.reftypes_primitive_enums()
- && field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
- return "Integer.MIN_VALUE";
- }
- return "null";
- }
-
- // Switch on cpp_type since we need to know which default_value_* method
- // of FieldDescriptor to call.
- switch (field->cpp_type()) {
- case FieldDescriptor::CPPTYPE_INT32:
- 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()));
- case FieldDescriptor::CPPTYPE_INT64:
- return SimpleItoa(field->default_value_int64()) + "L";
- case FieldDescriptor::CPPTYPE_UINT64:
- return SimpleItoa(static_cast<int64>(field->default_value_uint64())) +
- "L";
- case FieldDescriptor::CPPTYPE_DOUBLE: {
- double value = field->default_value_double();
- if (value == std::numeric_limits<double>::infinity()) {
- return "Double.POSITIVE_INFINITY";
- } else if (value == -std::numeric_limits<double>::infinity()) {
- return "Double.NEGATIVE_INFINITY";
- } else if (value != value) {
- return "Double.NaN";
- } else {
- return SimpleDtoa(value) + "D";
- }
- }
- case FieldDescriptor::CPPTYPE_FLOAT: {
- float value = field->default_value_float();
- if (value == std::numeric_limits<float>::infinity()) {
- return "Float.POSITIVE_INFINITY";
- } else if (value == -std::numeric_limits<float>::infinity()) {
- return "Float.NEGATIVE_INFINITY";
- } else if (value != value) {
- return "Float.NaN";
- } else {
- return SimpleFtoa(value) + "F";
- }
- }
- case FieldDescriptor::CPPTYPE_BOOL:
- return field->default_value_bool() ? "true" : "false";
- case FieldDescriptor::CPPTYPE_STRING:
- if (!field->default_value_string().empty()) {
- // Point it to the static final in the generated code.
- return FieldDefaultConstantName(field);
- } else {
- if (field->type() == FieldDescriptor::TYPE_BYTES) {
- return "com.google.protobuf.nano.WireFormatNano.EMPTY_BYTES";
- } else {
- return "\"\"";
- }
- }
-
- case FieldDescriptor::CPPTYPE_ENUM:
- return ClassName(params, field->enum_type()) + "." +
- RenameJavaKeywords(field->default_value_enum()->name());
-
- case FieldDescriptor::CPPTYPE_MESSAGE:
- return "null";
-
- // No default because we want the compiler to complain if any new
- // types are added.
- }
-
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return "";
-}
-
-
-static const char* kBitMasks[] = {
- "0x00000001",
- "0x00000002",
- "0x00000004",
- "0x00000008",
- "0x00000010",
- "0x00000020",
- "0x00000040",
- "0x00000080",
-
- "0x00000100",
- "0x00000200",
- "0x00000400",
- "0x00000800",
- "0x00001000",
- "0x00002000",
- "0x00004000",
- "0x00008000",
-
- "0x00010000",
- "0x00020000",
- "0x00040000",
- "0x00080000",
- "0x00100000",
- "0x00200000",
- "0x00400000",
- "0x00800000",
-
- "0x01000000",
- "0x02000000",
- "0x04000000",
- "0x08000000",
- "0x10000000",
- "0x20000000",
- "0x40000000",
- "0x80000000",
-};
-
-string GetBitFieldName(int index) {
- string var_name = "bitField";
- var_name += SimpleItoa(index);
- var_name += "_";
- return var_name;
-}
-
-string GetBitFieldNameForBit(int bit_index) {
- return GetBitFieldName(bit_index / 32);
-}
-
-string GenerateGetBit(int bit_index) {
- string var_name = GetBitFieldNameForBit(bit_index);
- int bit_in_var_index = bit_index % 32;
-
- string mask = kBitMasks[bit_in_var_index];
- string result = "((" + var_name + " & " + mask + ") != 0)";
- return result;
-}
-
-string GenerateSetBit(int bit_index) {
- string var_name = GetBitFieldNameForBit(bit_index);
- int bit_in_var_index = bit_index % 32;
-
- string mask = kBitMasks[bit_in_var_index];
- string result = var_name + " |= " + mask;
- return result;
-}
-
-string GenerateClearBit(int bit_index) {
- string var_name = GetBitFieldNameForBit(bit_index);
- int bit_in_var_index = bit_index % 32;
-
- string mask = kBitMasks[bit_in_var_index];
- string result = var_name + " = (" + var_name + " & ~" + mask + ")";
- return result;
-}
-
-string GenerateDifferentBit(int bit_index) {
- string var_name = GetBitFieldNameForBit(bit_index);
- int bit_in_var_index = bit_index % 32;
-
- string mask = kBitMasks[bit_in_var_index];
- string result = "((" + var_name + " & " + mask
- + ") != (other." + var_name + " & " + mask + "))";
- return result;
-}
-
-void SetBitOperationVariables(const string name,
- int bitIndex, std::map<string, string>* variables) {
- (*variables)["get_" + name] = GenerateGetBit(bitIndex);
- (*variables)["set_" + name] = GenerateSetBit(bitIndex);
- (*variables)["clear_" + name] = GenerateClearBit(bitIndex);
- (*variables)["different_" + name] = GenerateDifferentBit(bitIndex);
-}
-
-bool HasMapField(const Descriptor* descriptor) {
- for (int i = 0; i < descriptor->field_count(); ++i) {
- const FieldDescriptor* field = descriptor->field(i);
- if (field->type() == FieldDescriptor::TYPE_MESSAGE &&
- IsMapEntry(field->message_type())) {
- return true;
- }
- }
- return false;
-}
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-} // namespace google
diff --git a/src/google/protobuf/compiler/javanano/javanano_helpers.h b/src/google/protobuf/compiler/javanano/javanano_helpers.h
deleted file mode 100644
index 04b2d633..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_helpers.h
+++ /dev/null
@@ -1,199 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_HELPERS_H__
-#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_HELPERS_H__
-
-#include <string>
-#include <google/protobuf/compiler/javanano/javanano_params.h>
-#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/descriptor.h>
-#include <google/protobuf/io/printer.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-// Commonly-used separator comments. Thick is a line of '=', thin is a line
-// of '-'.
-extern const char kThickSeparator[];
-extern const char kThinSeparator[];
-
-// Converts the field's name to camel-case, e.g. "foo_bar_baz" becomes
-// "fooBarBaz" or "FooBarBaz", respectively.
-string UnderscoresToCamelCase(const FieldDescriptor* field);
-string UnderscoresToCamelCase(const OneofDescriptor* oneof);
-string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field);
-string UnderscoresToCapitalizedCamelCase(const OneofDescriptor* oneof);
-
-// Appends an "_" to the end of a field where the name is a reserved java
-// keyword. For example int32 public = 1 will generate int public_.
-string RenameJavaKeywords(const string& input);
-
-// 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);
-
-// Strips ".proto" or ".protodevel" from the end of a filename.
-string StripProto(const string& filename);
-
-// Gets the unqualified class name for the file. Each .proto file becomes a
-// single Java class, with all its contents nested in that class.
-string FileClassName(const Params& params, const FileDescriptor* file);
-
-// Returns the file's Java package name.
-string FileJavaPackage(const Params& params, const FileDescriptor* file);
-
-// Returns whether the Java outer class is needed, i.e. whether the option
-// java_multiple_files is false, or the proto file contains any file-scope
-// enums/extensions.
-bool IsOuterClassNeeded(const Params& params, const FileDescriptor* file);
-
-// Converts the given simple name of a proto entity to its fully-qualified name
-// in the Java namespace, given that it is in the given file enclosed in the
-// given parent message (or NULL for file-scope entities). Whether the file's
-// outer class name should be included in the return value depends on factors
-// inferrable from the given arguments, including is_class which indicates
-// whether the entity translates to a Java class.
-string ToJavaName(const Params& params, const string& name, bool is_class,
- const Descriptor* parent, const FileDescriptor* file);
-
-// These return the fully-qualified class name corresponding to the given
-// descriptor.
-inline string ClassName(const Params& params, const Descriptor* descriptor) {
- return ToJavaName(params, descriptor->name(), true,
- descriptor->containing_type(), descriptor->file());
-}
-string ClassName(const Params& params, const EnumDescriptor* descriptor);
-inline string ClassName(const Params& params,
- const ServiceDescriptor* descriptor) {
- return ToJavaName(params, descriptor->name(), true, NULL, descriptor->file());
-}
-inline string ExtensionIdentifierName(const Params& params,
- const FieldDescriptor* descriptor) {
- return ToJavaName(params, descriptor->name(), false,
- descriptor->extension_scope(), descriptor->file());
-}
-string ClassName(const Params& params, const FileDescriptor* descriptor);
-
-// Get the unqualified name that should be used for a field's field
-// number constant.
-string FieldConstantName(const FieldDescriptor *field);
-
-string FieldDefaultConstantName(const FieldDescriptor *field);
-
-// Print the field's proto-syntax definition as a comment.
-void PrintFieldComment(io::Printer* printer, const FieldDescriptor* field);
-
-enum JavaType {
- JAVATYPE_INT,
- JAVATYPE_LONG,
- JAVATYPE_FLOAT,
- JAVATYPE_DOUBLE,
- JAVATYPE_BOOLEAN,
- JAVATYPE_STRING,
- JAVATYPE_BYTES,
- JAVATYPE_ENUM,
- JAVATYPE_MESSAGE
-};
-
-JavaType GetJavaType(FieldDescriptor::Type field_type);
-
-inline JavaType GetJavaType(const FieldDescriptor* field) {
- return GetJavaType(field->type());
-}
-
-string PrimitiveTypeName(JavaType type);
-
-// Get the fully-qualified class name for a boxed primitive type, e.g.
-// "java.lang.Integer" for JAVATYPE_INT. Returns NULL for enum and message
-// types.
-string BoxedPrimitiveTypeName(JavaType type);
-
-string EmptyArrayName(const Params& params, const FieldDescriptor* field);
-
-string DefaultValue(const Params& params, const FieldDescriptor* field);
-
-
-// Methods for shared bitfields.
-
-// Gets the name of the shared bitfield for the given field index.
-string GetBitFieldName(int index);
-
-// Gets the name of the shared bitfield for the given bit index.
-// Effectively, GetBitFieldName(bit_index / 32)
-string GetBitFieldNameForBit(int bit_index);
-
-// Generates the java code for the expression that returns whether the bit at
-// the given bit index is set.
-// Example: "((bitField1_ & 0x04000000) != 0)"
-string GenerateGetBit(int bit_index);
-
-// Generates the java code for the expression that sets the bit at the given
-// bit index.
-// Example: "bitField1_ |= 0x04000000"
-string GenerateSetBit(int bit_index);
-
-// Generates the java code for the expression that clears the bit at the given
-// bit index.
-// Example: "bitField1_ = (bitField1_ & ~0x04000000)"
-string GenerateClearBit(int bit_index);
-
-// Generates the java code for the expression that returns whether the bit at
-// the given bit index contains different values in the current object and
-// another object accessible via the variable 'other'.
-// Example: "((bitField1_ & 0x04000000) != (other.bitField1_ & 0x04000000))"
-string GenerateDifferentBit(int bit_index);
-
-// Sets the 'get_*', 'set_*', 'clear_*' and 'different_*' variables, where * is
-// the given name of the bit, to the appropriate Java expressions for the given
-// bit index.
-void SetBitOperationVariables(const string name,
- int bitIndex, std::map<string, string>* variables);
-
-inline bool IsMapEntry(const Descriptor* descriptor) {
- // TODO(liujisi): Add an option to turn on maps for proto2 syntax as well.
- return descriptor->options().map_entry() &&
- descriptor->file()->syntax() == FileDescriptor::SYNTAX_PROTO3;
-}
-
-bool HasMapField(const Descriptor* descriptor);
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-
-} // namespace google
-#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_HELPERS_H__
diff --git a/src/google/protobuf/compiler/javanano/javanano_map_field.cc b/src/google/protobuf/compiler/javanano/javanano_map_field.cc
deleted file mode 100644
index a4ab8858..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_map_field.cc
+++ /dev/null
@@ -1,186 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-#include <google/protobuf/compiler/javanano/javanano_map_field.h>
-#include <google/protobuf/compiler/javanano/javanano_helpers.h>
-#include <google/protobuf/stubs/common.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 {
-namespace javanano {
-
-namespace {
-
-string TypeName(const Params& params, const FieldDescriptor* field,
- bool boxed) {
- JavaType java_type = GetJavaType(field);
- switch (java_type) {
- case JAVATYPE_MESSAGE:
- return ClassName(params, field->message_type());
- case JAVATYPE_INT:
- case JAVATYPE_LONG:
- case JAVATYPE_FLOAT:
- case JAVATYPE_DOUBLE:
- case JAVATYPE_BOOLEAN:
- case JAVATYPE_STRING:
- case JAVATYPE_BYTES:
- case JAVATYPE_ENUM:
- if (boxed) {
- return BoxedPrimitiveTypeName(java_type);
- } else {
- return PrimitiveTypeName(java_type);
- }
- // No default because we want the compiler to complain if any new JavaTypes
- // are added..
- }
-
- GOOGLE_LOG(FATAL) << "should not reach here.";
- return "";
-}
-
-const FieldDescriptor* KeyField(const FieldDescriptor* descriptor) {
- GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, descriptor->type());
- const Descriptor* message = descriptor->message_type();
- GOOGLE_CHECK(message->options().map_entry());
- return message->FindFieldByName("key");
-}
-
-const FieldDescriptor* ValueField(const FieldDescriptor* descriptor) {
- GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, descriptor->type());
- const Descriptor* message = descriptor->message_type();
- GOOGLE_CHECK(message->options().map_entry());
- return message->FindFieldByName("value");
-}
-
-void SetMapVariables(const Params& params,
- const FieldDescriptor* descriptor, std::map<string, string>* variables) {
- const FieldDescriptor* key = KeyField(descriptor);
- const FieldDescriptor* value = ValueField(descriptor);
- (*variables)["name"] =
- RenameJavaKeywords(UnderscoresToCamelCase(descriptor));
- (*variables)["number"] = SimpleItoa(descriptor->number());
- (*variables)["key_type"] = TypeName(params, key, false);
- (*variables)["boxed_key_type"] = TypeName(params,key, true);
- (*variables)["key_desc_type"] =
- "TYPE_" + ToUpper(FieldDescriptor::TypeName(key->type()));
- (*variables)["key_tag"] = SimpleItoa(internal::WireFormat::MakeTag(key));
- (*variables)["value_type"] = TypeName(params, value, false);
- (*variables)["boxed_value_type"] = TypeName(params, value, true);
- (*variables)["value_desc_type"] =
- "TYPE_" + ToUpper(FieldDescriptor::TypeName(value->type()));
- (*variables)["value_tag"] = SimpleItoa(internal::WireFormat::MakeTag(value));
- (*variables)["type_parameters"] =
- (*variables)["boxed_key_type"] + ", " + (*variables)["boxed_value_type"];
- (*variables)["value_default"] =
- value->type() == FieldDescriptor::TYPE_MESSAGE
- ? "new " + (*variables)["value_type"] + "()"
- : "null";
-}
-} // namespace
-
-// ===================================================================
-MapFieldGenerator::MapFieldGenerator(const FieldDescriptor* descriptor,
- const Params& params)
- : FieldGenerator(params), descriptor_(descriptor) {
- SetMapVariables(params, descriptor, &variables_);
-}
-
-MapFieldGenerator::~MapFieldGenerator() {}
-
-void MapFieldGenerator::
-GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const {
- printer->Print(variables_,
- "public java.util.Map<$type_parameters$> $name$;\n");
-}
-
-void MapFieldGenerator::
-GenerateClearCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$name$ = null;\n");
-}
-
-void MapFieldGenerator::
-GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "this.$name$ = com.google.protobuf.nano.InternalNano.mergeMapEntry(\n"
- " input, this.$name$, mapFactory,\n"
- " com.google.protobuf.nano.InternalNano.$key_desc_type$,\n"
- " com.google.protobuf.nano.InternalNano.$value_desc_type$,\n"
- " $value_default$,\n"
- " $key_tag$, $value_tag$);\n"
- "\n");
-}
-
-void MapFieldGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ != null) {\n"
- " com.google.protobuf.nano.InternalNano.serializeMapField(\n"
- " output, this.$name$, $number$,\n"
- " com.google.protobuf.nano.InternalNano.$key_desc_type$,\n"
- " com.google.protobuf.nano.InternalNano.$value_desc_type$);\n"
- "}\n");
-}
-
-void MapFieldGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ != null) {\n"
- " size += com.google.protobuf.nano.InternalNano.computeMapFieldSize(\n"
- " this.$name$, $number$,\n"
- " com.google.protobuf.nano.InternalNano.$key_desc_type$,\n"
- " com.google.protobuf.nano.InternalNano.$value_desc_type$);\n"
- "}\n");
-}
-
-void MapFieldGenerator::
-GenerateEqualsCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (!com.google.protobuf.nano.InternalNano.equals(\n"
- " this.$name$, other.$name$)) {\n"
- " return false;\n"
- "}\n");
-}
-
-void MapFieldGenerator::
-GenerateHashCodeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "result = 31 * result +\n"
- " com.google.protobuf.nano.InternalNano.hashCode(this.$name$);\n");
-}
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-} // namespace google
diff --git a/src/google/protobuf/compiler/javanano/javanano_map_field.h b/src/google/protobuf/compiler/javanano/javanano_map_field.h
deleted file mode 100644
index 81e5915d..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_map_field.h
+++ /dev/null
@@ -1,70 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_MAP_FIELD_H__
-#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_MAP_FIELD_H__
-
-#include <map>
-#include <string>
-#include <vector>
-#include <google/protobuf/compiler/javanano/javanano_field.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-class MapFieldGenerator : public FieldGenerator {
- public:
- explicit MapFieldGenerator(
- const FieldDescriptor* descriptor, const Params& params);
- ~MapFieldGenerator();
-
- // implements FieldGenerator ---------------------------------------
- void GenerateMembers(io::Printer* printer, bool lazy_init) const;
- void GenerateClearCode(io::Printer* printer) const;
- void GenerateMergingCode(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
- void GenerateEqualsCode(io::Printer* printer) const;
- void GenerateHashCodeCode(io::Printer* printer) const;
-
- private:
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator);
-};
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-} // namespace google
-#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_MAP_FIELD_H__
diff --git a/src/google/protobuf/compiler/javanano/javanano_message.cc b/src/google/protobuf/compiler/javanano/javanano_message.cc
deleted file mode 100644
index 78421887..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_message.cc
+++ /dev/null
@@ -1,676 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#include <algorithm>
-#include <google/protobuf/stubs/hash.h>
-#include <google/protobuf/compiler/javanano/javanano_message.h>
-#include <google/protobuf/compiler/javanano/javanano_enum.h>
-#include <google/protobuf/compiler/javanano/javanano_extension.h>
-#include <google/protobuf/compiler/javanano/javanano_helpers.h>
-#include <google/protobuf/stubs/strutil.h>
-#include <google/protobuf/io/printer.h>
-#include <google/protobuf/io/coded_stream.h>
-#include <google/protobuf/wire_format.h>
-#include <google/protobuf/descriptor.pb.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-using internal::WireFormat;
-using internal::WireFormatLite;
-
-namespace {
-
-struct FieldOrderingByNumber {
- inline bool operator()(const FieldDescriptor* a,
- const FieldDescriptor* b) const {
- return a->number() < b->number();
- }
-};
-
-// Sort the fields of the given Descriptor by number into a new[]'d array
-// and return it.
-const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) {
- const FieldDescriptor** fields =
- new const FieldDescriptor*[descriptor->field_count()];
- for (int i = 0; i < descriptor->field_count(); i++) {
- fields[i] = descriptor->field(i);
- }
- std::sort(fields, fields + descriptor->field_count(),
- FieldOrderingByNumber());
- return fields;
-}
-
-} // namespace
-
-// ===================================================================
-
-MessageGenerator::MessageGenerator(const Descriptor* descriptor, const Params& params)
- : params_(params),
- descriptor_(descriptor),
- field_generators_(descriptor, params) {
-}
-
-MessageGenerator::~MessageGenerator() {}
-
-void MessageGenerator::GenerateStaticVariables(io::Printer* printer) {
- // Generate static members for all nested types.
- for (int i = 0; i < descriptor_->nested_type_count(); i++) {
- // TODO(kenton): Reuse MessageGenerator objects?
- if (IsMapEntry(descriptor_->nested_type(i))) continue;
- MessageGenerator(descriptor_->nested_type(i), params_)
- .GenerateStaticVariables(printer);
- }
-}
-
-void MessageGenerator::GenerateStaticVariableInitializers(
- io::Printer* printer) {
- // Generate static member initializers for all nested types.
- for (int i = 0; i < descriptor_->nested_type_count(); i++) {
- // TODO(kenton): Reuse MessageGenerator objects?
- if (IsMapEntry(descriptor_->nested_type(i))) continue;
- MessageGenerator(descriptor_->nested_type(i), params_)
- .GenerateStaticVariableInitializers(printer);
- }
-}
-
-void MessageGenerator::Generate(io::Printer* printer) {
- if (!params_.store_unknown_fields() &&
- (descriptor_->extension_count() != 0 || descriptor_->extension_range_count() != 0)) {
- GOOGLE_LOG(FATAL) << "Extensions are only supported in NANO_RUNTIME if the "
- "'store_unknown_fields' generator option is 'true'\n";
- }
-
- const string& file_name = descriptor_->file()->name();
- bool is_own_file =
- params_.java_multiple_files(file_name)
- && descriptor_->containing_type() == NULL;
-
- if (is_own_file) {
- // Note: constants (from enums and fields requiring stored defaults, emitted in the loop below)
- // may have the same names as constants in the nested classes. This causes Java warnings, but
- // is not fatal, so we suppress those warnings here in the top-most class declaration.
- printer->Print(
- "\n"
- "@SuppressWarnings(\"hiding\")\n"
- "public final class $classname$ extends\n",
- "classname", descriptor_->name());
- } else {
- printer->Print(
- "\n"
- "public static final class $classname$ extends\n",
- "classname", descriptor_->name());
- }
- if (params_.store_unknown_fields() && params_.parcelable_messages()) {
- printer->Print(
- " com.google.protobuf.nano.android.ParcelableExtendableMessageNano<$classname$>",
- "classname", descriptor_->name());
- } else if (params_.store_unknown_fields()) {
- printer->Print(
- " com.google.protobuf.nano.ExtendableMessageNano<$classname$>",
- "classname", descriptor_->name());
- } else if (params_.parcelable_messages()) {
- printer->Print(
- " com.google.protobuf.nano.android.ParcelableMessageNano");
- } else {
- printer->Print(
- " com.google.protobuf.nano.MessageNano");
- }
- if (params_.generate_clone()) {
- printer->Print(" implements java.lang.Cloneable {\n");
- } else {
- printer->Print(" {\n");
- }
- printer->Indent();
-
- if (params_.parcelable_messages()) {
- printer->Print(
- "\n"
- "// Used by Parcelable\n"
- "@SuppressWarnings({\"unused\"})\n"
- "public static final android.os.Parcelable.Creator<$classname$> CREATOR =\n"
- " new com.google.protobuf.nano.android.ParcelableMessageNanoCreator<\n"
- " $classname$>($classname$.class);\n",
- "classname", descriptor_->name());
- }
-
- // Nested types and extensions
- for (int i = 0; i < descriptor_->extension_count(); i++) {
- ExtensionGenerator(descriptor_->extension(i), params_).Generate(printer);
- }
-
- for (int i = 0; i < descriptor_->enum_type_count(); i++) {
- EnumGenerator(descriptor_->enum_type(i), params_).Generate(printer);
- }
-
- for (int i = 0; i < descriptor_->nested_type_count(); i++) {
- if (IsMapEntry(descriptor_->nested_type(i))) continue;
- MessageGenerator(descriptor_->nested_type(i), params_).Generate(printer);
- }
-
- // oneof
- std::map<string, string> vars;
- vars["message_name"] = descriptor_->name();
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- const OneofDescriptor* oneof_desc = descriptor_->oneof_decl(i);
- vars["oneof_name"] = UnderscoresToCamelCase(oneof_desc);
- vars["oneof_capitalized_name"] =
- UnderscoresToCapitalizedCamelCase(oneof_desc);
- vars["oneof_index"] = SimpleItoa(oneof_desc->index());
- // Oneof Constants
- for (int j = 0; j < oneof_desc->field_count(); j++) {
- const FieldDescriptor* field = oneof_desc->field(j);
- vars["number"] = SimpleItoa(field->number());
- vars["cap_field_name"] = ToUpper(field->name());
- printer->Print(vars,
- "public static final int $cap_field_name$_FIELD_NUMBER = $number$;\n");
- }
- // oneofCase_ and oneof_
- printer->Print(vars,
- "private int $oneof_name$Case_ = 0;\n"
- "private java.lang.Object $oneof_name$_;\n");
- printer->Print(vars,
- "public int get$oneof_capitalized_name$Case() {\n"
- " return this.$oneof_name$Case_;\n"
- "}\n");
- // Oneof clear
- printer->Print(vars,
- "public $message_name$ clear$oneof_capitalized_name$() {\n"
- " this.$oneof_name$Case_ = 0;\n"
- " this.$oneof_name$_ = null;\n"
- " return this;\n"
- "}\n");
- }
-
- // Lazy initialization of otherwise static final fields can help prevent the
- // class initializer from being generated. We want to prevent it because it
- // stops ProGuard from inlining any methods in this class into call sites and
- // therefore reducing the method count. However, extensions are best kept as
- // public static final fields with initializers, so with their existence we
- // won't bother with lazy initialization.
- bool lazy_init = descriptor_->extension_count() == 0;
-
- // Empty array
- if (lazy_init) {
- printer->Print(
- "\n"
- "private static volatile $classname$[] _emptyArray;\n"
- "public static $classname$[] emptyArray() {\n"
- " // Lazily initializes the empty array\n"
- " if (_emptyArray == null) {\n"
- " synchronized (\n"
- " com.google.protobuf.nano.InternalNano.LAZY_INIT_LOCK) {\n"
- " if (_emptyArray == null) {\n"
- " _emptyArray = new $classname$[0];\n"
- " }\n"
- " }\n"
- " }\n"
- " return _emptyArray;\n"
- "}\n",
- "classname", descriptor_->name());
- } else {
- printer->Print(
- "\n"
- "private static final $classname$[] EMPTY_ARRAY = {};\n"
- "public static $classname$[] emptyArray() {\n"
- " return EMPTY_ARRAY;\n"
- "}\n",
- "classname", descriptor_->name());
- }
-
- // Integers for bit fields
- int totalInts = (field_generators_.total_bits() + 31) / 32;
- if (totalInts > 0) {
- printer->Print("\n");
- for (int i = 0; i < totalInts; i++) {
- printer->Print("private int $bit_field_name$;\n",
- "bit_field_name", GetBitFieldName(i));
- }
- }
-
- // Fields and maybe their default values
- for (int i = 0; i < descriptor_->field_count(); i++) {
- printer->Print("\n");
- PrintFieldComment(printer, descriptor_->field(i));
- field_generators_.get(descriptor_->field(i)).GenerateMembers(
- printer, lazy_init);
- }
-
- // Constructor, with lazy init code if needed
- if (lazy_init && field_generators_.saved_defaults_needed()) {
- printer->Print(
- "\n"
- "private static volatile boolean _classInitialized;\n"
- "\n"
- "public $classname$() {\n"
- " // Lazily initializes the field defaults\n"
- " if (!_classInitialized) {\n"
- " synchronized (\n"
- " com.google.protobuf.nano.InternalNano.LAZY_INIT_LOCK) {\n"
- " if (!_classInitialized) {\n",
- "classname", descriptor_->name());
- printer->Indent();
- printer->Indent();
- printer->Indent();
- printer->Indent();
- for (int i = 0; i < descriptor_->field_count(); i++) {
- field_generators_.get(descriptor_->field(i))
- .GenerateInitSavedDefaultCode(printer);
- }
- printer->Outdent();
- printer->Outdent();
- printer->Outdent();
- printer->Outdent();
- printer->Print(
- " _classInitialized = true;\n"
- " }\n"
- " }\n"
- " }\n");
- if (params_.generate_clear()) {
- printer->Print(" clear();\n");
- }
- printer->Print("}\n");
- } else {
- printer->Print(
- "\n"
- "public $classname$() {\n",
- "classname", descriptor_->name());
- if (params_.generate_clear()) {
- printer->Print(" clear();\n");
- } else {
- printer->Indent();
- GenerateFieldInitializers(printer);
- printer->Outdent();
- }
- printer->Print("}\n");
- }
-
- // Other methods in this class
-
- GenerateClear(printer);
-
- if (params_.generate_clone()) {
- GenerateClone(printer);
- }
-
- if (params_.generate_equals()) {
- GenerateEquals(printer);
- GenerateHashCode(printer);
- }
-
- GenerateMessageSerializationMethods(printer);
- GenerateMergeFromMethods(printer);
- GenerateParseFromMethods(printer);
-
- printer->Outdent();
- printer->Print("}\n");
-}
-
-// ===================================================================
-
-void MessageGenerator::
-GenerateMessageSerializationMethods(io::Printer* printer) {
- // Rely on the parent implementations of writeTo() and getSerializedSize()
- // if there are no fields to serialize in this message.
- if (descriptor_->field_count() == 0) {
- return;
- }
-
- scoped_array<const FieldDescriptor*> sorted_fields(
- SortFieldsByNumber(descriptor_));
-
- printer->Print(
- "\n"
- "@Override\n"
- "public void writeTo(com.google.protobuf.nano.CodedOutputByteBufferNano output)\n"
- " throws java.io.IOException {\n");
- printer->Indent();
-
- // Output the fields in sorted order
- for (int i = 0; i < descriptor_->field_count(); i++) {
- GenerateSerializeOneField(printer, sorted_fields[i]);
- }
-
- // The parent implementation will write any unknown fields if necessary.
- printer->Print(
- "super.writeTo(output);\n");
-
- printer->Outdent();
- printer->Print("}\n");
-
- // The parent implementation will get the serialized size for unknown
- // fields if necessary.
- printer->Print(
- "\n"
- "@Override\n"
- "protected int computeSerializedSize() {\n"
- " int size = super.computeSerializedSize();\n");
- printer->Indent();
-
- for (int i = 0; i < descriptor_->field_count(); i++) {
- field_generators_.get(sorted_fields[i]).GenerateSerializedSizeCode(printer);
- }
-
- printer->Outdent();
- printer->Print(
- " return size;\n"
- "}\n");
-}
-
-void MessageGenerator::GenerateMergeFromMethods(io::Printer* printer) {
- scoped_array<const FieldDescriptor*> sorted_fields(
- SortFieldsByNumber(descriptor_));
-
- printer->Print(
- "\n"
- "@Override\n"
- "public $classname$ mergeFrom(\n"
- " com.google.protobuf.nano.CodedInputByteBufferNano input)\n"
- " throws java.io.IOException {\n",
- "classname", descriptor_->name());
-
- printer->Indent();
- if (HasMapField(descriptor_)) {
- printer->Print(
- "com.google.protobuf.nano.MapFactories.MapFactory mapFactory =\n"
- " com.google.protobuf.nano.MapFactories.getMapFactory();\n");
- }
-
- printer->Print(
- "while (true) {\n");
- printer->Indent();
-
- printer->Print(
- "int tag = input.readTag();\n"
- "switch (tag) {\n");
- printer->Indent();
-
- printer->Print(
- "case 0:\n" // zero signals EOF / limit reached
- " return this;\n"
- "default: {\n");
-
- printer->Indent();
- if (params_.store_unknown_fields()) {
- printer->Print(
- "if (!storeUnknownField(input, tag)) {\n"
- " return this;\n"
- "}\n");
- } else {
- printer->Print(
- "if (!com.google.protobuf.nano.WireFormatNano.parseUnknownField(input, tag)) {\n"
- " return this;\n" // it's an endgroup tag
- "}\n");
- }
- printer->Print("break;\n");
- printer->Outdent();
- printer->Print("}\n");
-
- 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(tag));
- printer->Indent();
-
- field_generators_.get(field).GenerateMergingCode(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(packed_tag));
- printer->Indent();
-
- field_generators_.get(field).GenerateMergingCodeFromPacked(printer);
-
- printer->Outdent();
- printer->Print(
- " break;\n"
- "}\n");
- }
- }
-
- printer->Outdent();
- printer->Outdent();
- printer->Outdent();
- printer->Print(
- " }\n" // switch (tag)
- " }\n" // while (true)
- "}\n");
-}
-
-void MessageGenerator::
-GenerateParseFromMethods(io::Printer* printer) {
- // Note: These are separate from GenerateMessageSerializationMethods()
- // because they need to be generated even for messages that are optimized
- // for code size.
- printer->Print(
- "\n"
- "public static $classname$ parseFrom(byte[] data)\n"
- " throws com.google.protobuf.nano.InvalidProtocolBufferNanoException {\n"
- " return com.google.protobuf.nano.MessageNano.mergeFrom(new $classname$(), data);\n"
- "}\n"
- "\n"
- "public static $classname$ parseFrom(\n"
- " com.google.protobuf.nano.CodedInputByteBufferNano input)\n"
- " throws java.io.IOException {\n"
- " return new $classname$().mergeFrom(input);\n"
- "}\n",
- "classname", descriptor_->name());
-}
-
-void MessageGenerator::GenerateSerializeOneField(
- io::Printer* printer, const FieldDescriptor* field) {
- field_generators_.get(field).GenerateSerializationCode(printer);
-}
-
-void MessageGenerator::GenerateClear(io::Printer* printer) {
- if (!params_.generate_clear()) {
- return;
- }
- printer->Print(
- "\n"
- "public $classname$ clear() {\n",
- "classname", descriptor_->name());
- printer->Indent();
-
- GenerateFieldInitializers(printer);
-
- printer->Outdent();
- printer->Print(
- " return this;\n"
- "}\n");
-}
-
-void MessageGenerator::GenerateFieldInitializers(io::Printer* printer) {
- // Clear bit fields.
- int totalInts = (field_generators_.total_bits() + 31) / 32;
- for (int i = 0; i < totalInts; i++) {
- printer->Print("$bit_field_name$ = 0;\n",
- "bit_field_name", GetBitFieldName(i));
- }
-
- // Call clear for all of the fields.
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor* field = descriptor_->field(i);
- field_generators_.get(field).GenerateClearCode(printer);
- }
-
- // Clear oneofs.
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- printer->Print(
- "clear$oneof_capitalized_name$();\n",
- "oneof_capitalized_name", UnderscoresToCapitalizedCamelCase(
- descriptor_->oneof_decl(i)));
- }
-
- // Clear unknown fields.
- if (params_.store_unknown_fields()) {
- printer->Print("unknownFieldData = null;\n");
- }
- printer->Print("cachedSize = -1;\n");
-}
-
-void MessageGenerator::GenerateClone(io::Printer* printer) {
- printer->Print(
- "@Override\n"
- "public $classname$ clone() {\n",
- "classname", descriptor_->name());
- printer->Indent();
-
- printer->Print(
- "$classname$ cloned;\n"
- "try {\n"
- " cloned = ($classname$) super.clone();\n"
- "} catch (java.lang.CloneNotSupportedException e) {\n"
- " throw new java.lang.AssertionError(e);\n"
- "}\n",
- "classname", descriptor_->name());
-
- for (int i = 0; i < descriptor_->field_count(); i++) {
- field_generators_.get(descriptor_->field(i)).GenerateFixClonedCode(printer);
- }
-
- printer->Outdent();
- printer->Print(
- " return cloned;\n"
- "}\n"
- "\n");
-}
-
-void MessageGenerator::GenerateEquals(io::Printer* printer) {
- // Don't override if there are no fields. We could generate an
- // equals method that compares types, but often empty messages
- // are used as namespaces.
- if (descriptor_->field_count() == 0 && !params_.store_unknown_fields()) {
- return;
- }
-
- printer->Print(
- "\n"
- "@Override\n"
- "public boolean equals(Object o) {\n");
- printer->Indent();
- printer->Print(
- "if (o == this) {\n"
- " return true;\n"
- "}\n"
- "if (!(o instanceof $classname$)) {\n"
- " return false;\n"
- "}\n"
- "$classname$ other = ($classname$) o;\n",
- "classname", descriptor_->name());
-
- // Checking oneof case before checking each oneof field.
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- const OneofDescriptor* oneof_desc = descriptor_->oneof_decl(i);
- printer->Print(
- "if (this.$oneof_name$Case_ != other.$oneof_name$Case_) {\n"
- " return false;\n"
- "}\n",
- "oneof_name", UnderscoresToCamelCase(oneof_desc));
- }
-
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor* field = descriptor_->field(i);
- field_generators_.get(field).GenerateEqualsCode(printer);
- }
-
- if (params_.store_unknown_fields()) {
- printer->Print(
- "if (unknownFieldData == null || unknownFieldData.isEmpty()) {\n"
- " return other.unknownFieldData == null || other.unknownFieldData.isEmpty();\n"
- "} else {\n"
- " return unknownFieldData.equals(other.unknownFieldData);\n"
- "}");
- } else {
- printer->Print(
- "return true;\n");
- }
-
- printer->Outdent();
- printer->Print("}\n");
-}
-
-void MessageGenerator::GenerateHashCode(io::Printer* printer) {
- if (descriptor_->field_count() == 0 && !params_.store_unknown_fields()) {
- return;
- }
-
- printer->Print(
- "\n"
- "@Override\n"
- "public int hashCode() {\n");
- printer->Indent();
-
- printer->Print("int result = 17;\n");
- printer->Print("result = 31 * result + getClass().getName().hashCode();\n");
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor* field = descriptor_->field(i);
- field_generators_.get(field).GenerateHashCodeCode(printer);
- }
-
- if (params_.store_unknown_fields()) {
- printer->Print(
- "result = 31 * result + \n"
- " (unknownFieldData == null || unknownFieldData.isEmpty() ? 0 : \n"
- " unknownFieldData.hashCode());\n");
- }
-
- printer->Print("return result;\n");
-
- printer->Outdent();
- printer->Print("}\n");
-}
-
-// ===================================================================
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-} // namespace google
diff --git a/src/google/protobuf/compiler/javanano/javanano_message.h b/src/google/protobuf/compiler/javanano/javanano_message.h
deleted file mode 100644
index 281ec64f..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_message.h
+++ /dev/null
@@ -1,97 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_MESSAGE_H__
-#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_MESSAGE_H__
-
-#include <string>
-#include <google/protobuf/compiler/javanano/javanano_helpers.h>
-#include <google/protobuf/compiler/javanano/javanano_field.h>
-#include <google/protobuf/compiler/javanano/javanano_params.h>
-#include <google/protobuf/stubs/common.h>
-
-namespace google {
-namespace protobuf {
- namespace io {
- class Printer; // printer.h
- }
-}
-
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-class MessageGenerator {
- public:
- explicit MessageGenerator(const Descriptor* descriptor, const Params& params);
- ~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.
- void GenerateStaticVariables(io::Printer* printer);
-
- // Output code which initializes the static variables generated by
- // GenerateStaticVariables().
- void GenerateStaticVariableInitializers(io::Printer* printer);
-
- // Generate the class itself.
- void Generate(io::Printer* printer);
-
- private:
- void GenerateMessageSerializationMethods(io::Printer* printer);
- void GenerateMergeFromMethods(io::Printer* printer);
- void GenerateParseFromMethods(io::Printer* printer);
- void GenerateSerializeOneField(io::Printer* printer,
- const FieldDescriptor* field);
-
- void GenerateClear(io::Printer* printer);
- void GenerateFieldInitializers(io::Printer* printer);
- void GenerateEquals(io::Printer* printer);
- void GenerateHashCode(io::Printer* printer);
- void GenerateClone(io::Printer* printer);
-
- const Params& params_;
- const Descriptor* descriptor_;
- FieldGeneratorMap field_generators_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator);
-};
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-
-} // namespace google
-#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_MESSAGE_H__
diff --git a/src/google/protobuf/compiler/javanano/javanano_message_field.cc b/src/google/protobuf/compiler/javanano/javanano_message_field.cc
deleted file mode 100644
index 2ed8a3aa..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_message_field.cc
+++ /dev/null
@@ -1,363 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#include <map>
-#include <string>
-
-#include <google/protobuf/compiler/javanano/javanano_message_field.h>
-#include <google/protobuf/compiler/javanano/javanano_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 {
-namespace javanano {
-
-using internal::WireFormat;
-using internal::WireFormatLite;
-
-namespace {
-
-// TODO(kenton): Factor out a "SetCommonFieldVariables()" to get rid of
-// repeat code between this and the other field types.
-void SetMessageVariables(const Params& params,
- const FieldDescriptor* descriptor, std::map<string, string>* variables) {
- (*variables)["name"] =
- RenameJavaKeywords(UnderscoresToCamelCase(descriptor));
- (*variables)["capitalized_name"] =
- RenameJavaKeywords(UnderscoresToCapitalizedCamelCase(descriptor));
- (*variables)["number"] = SimpleItoa(descriptor->number());
- (*variables)["type"] = ClassName(params, descriptor->message_type());
- (*variables)["group_or_message"] =
- (descriptor->type() == FieldDescriptor::TYPE_GROUP) ?
- "Group" : "Message";
- (*variables)["message_name"] = descriptor->containing_type()->name();
- //(*variables)["message_type"] = descriptor->message_type()->name();
- (*variables)["tag"] = SimpleItoa(WireFormat::MakeTag(descriptor));
-}
-
-} // namespace
-
-// ===================================================================
-
-MessageFieldGenerator::
-MessageFieldGenerator(const FieldDescriptor* descriptor, const Params& params)
- : FieldGenerator(params), descriptor_(descriptor) {
- SetMessageVariables(params, descriptor, &variables_);
-}
-
-MessageFieldGenerator::~MessageFieldGenerator() {}
-
-void MessageFieldGenerator::
-GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const {
- printer->Print(variables_,
- "public $type$ $name$;\n");
-}
-
-void MessageFieldGenerator::
-GenerateClearCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$name$ = null;\n");
-}
-
-void MessageFieldGenerator::
-GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ == null) {\n"
- " this.$name$ = new $type$();\n"
- "}\n");
-
- if (descriptor_->type() == FieldDescriptor::TYPE_GROUP) {
- printer->Print(variables_,
- "input.readGroup(this.$name$, $number$);\n");
- } else {
- printer->Print(variables_,
- "input.readMessage(this.$name$);\n");
- }
-}
-
-void MessageFieldGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ != null) {\n"
- " output.write$group_or_message$($number$, this.$name$);\n"
- "}\n");
-}
-
-void MessageFieldGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ != null) {\n"
- " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
- " .compute$group_or_message$Size($number$, this.$name$);\n"
- "}\n");
-}
-
-void MessageFieldGenerator::
-GenerateFixClonedCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ != null) {\n"
- " cloned.$name$ = this.$name$.clone();\n"
- "}\n");
-}
-
-void MessageFieldGenerator::
-GenerateEqualsCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ == null) { \n"
- " if (other.$name$ != null) {\n"
- " return false;\n"
- " }\n"
- "} else {\n"
- " if (!this.$name$.equals(other.$name$)) {\n"
- " return false;\n"
- " }\n"
- "}\n");
-}
-
-void MessageFieldGenerator::
-GenerateHashCodeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "result = 31 * result +\n"
- " (this.$name$ == null ? 0 : this.$name$.hashCode());\n");
-}
-// ===================================================================
-
-MessageOneofFieldGenerator::MessageOneofFieldGenerator(
- const FieldDescriptor* descriptor, const Params& params)
- : FieldGenerator(params), descriptor_(descriptor) {
- SetMessageVariables(params, descriptor, &variables_);
- SetCommonOneofVariables(descriptor, &variables_);
-}
-
-MessageOneofFieldGenerator::~MessageOneofFieldGenerator() {}
-
-void MessageOneofFieldGenerator::
-GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const {
- printer->Print(variables_,
- "public boolean has$capitalized_name$() {\n"
- " return $has_oneof_case$;\n"
- "}\n"
- "public $type$ get$capitalized_name$() {\n"
- " if ($has_oneof_case$) {\n"
- " return ($type$) this.$oneof_name$_;\n"
- " }\n"
- " return null;\n"
- "}\n"
- "public $message_name$ set$capitalized_name$($type$ value) {\n"
- " if (value == null) { throw new java.lang.NullPointerException(); }\n"
- " $set_oneof_case$;\n"
- " this.$oneof_name$_ = value;\n"
- " return this;\n"
- "}\n");
-}
-
-void MessageOneofFieldGenerator::
-GenerateClearCode(io::Printer* printer) const {
- // No clear method for oneof fields.
-}
-
-void MessageOneofFieldGenerator::
-GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (!($has_oneof_case$)) {\n"
- " this.$oneof_name$_ = new $type$();\n"
- "}\n"
- "input.readMessage(\n"
- " (com.google.protobuf.nano.MessageNano) this.$oneof_name$_);\n"
- "$set_oneof_case$;\n");
-}
-
-void MessageOneofFieldGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if ($has_oneof_case$) {\n"
- " output.writeMessage($number$,\n"
- " (com.google.protobuf.nano.MessageNano) this.$oneof_name$_);\n"
- "}\n");
-}
-
-void MessageOneofFieldGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if ($has_oneof_case$) {\n"
- " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
- " .computeMessageSize($number$,\n"
- " (com.google.protobuf.nano.MessageNano) this.$oneof_name$_);\n"
- "}\n");
-}
-
-void MessageOneofFieldGenerator::
-GenerateFixClonedCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$oneof_name$ != null) {\n"
- " cloned.$oneof_name$ = this.$oneof_name$.clone();\n"
- "}\n");
-}
-
-void MessageOneofFieldGenerator::
-GenerateEqualsCode(io::Printer* printer) const {
- GenerateOneofFieldEquals(descriptor_, variables_, printer);
-}
-
-void MessageOneofFieldGenerator::
-GenerateHashCodeCode(io::Printer* printer) const {
- GenerateOneofFieldHashCode(descriptor_, variables_, printer);
-}
-
-// ===================================================================
-
-RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator(
- const FieldDescriptor* descriptor, const Params& params)
- : FieldGenerator(params), descriptor_(descriptor) {
- SetMessageVariables(params, descriptor, &variables_);
-}
-
-RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() {}
-
-void RepeatedMessageFieldGenerator::
-GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const {
- printer->Print(variables_,
- "public $type$[] $name$;\n");
-}
-
-void RepeatedMessageFieldGenerator::
-GenerateClearCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$name$ = $type$.emptyArray();\n");
-}
-
-void RepeatedMessageFieldGenerator::
-GenerateMergingCode(io::Printer* printer) const {
- // First, figure out the length of the array, then parse.
- printer->Print(variables_,
- "int arrayLength = com.google.protobuf.nano.WireFormatNano\n"
- " .getRepeatedFieldArrayLength(input, $tag$);\n"
- "int i = this.$name$ == null ? 0 : this.$name$.length;\n"
- "$type$[] newArray =\n"
- " new $type$[i + arrayLength];\n"
- "if (i != 0) {\n"
- " java.lang.System.arraycopy(this.$name$, 0, newArray, 0, i);\n"
- "}\n"
- "for (; i < newArray.length - 1; i++) {\n"
- " newArray[i] = new $type$();\n");
-
- if (descriptor_->type() == FieldDescriptor::TYPE_GROUP) {
- printer->Print(variables_,
- " input.readGroup(newArray[i], $number$);\n");
- } else {
- printer->Print(variables_,
- " input.readMessage(newArray[i]);\n");
- }
-
- printer->Print(variables_,
- " input.readTag();\n"
- "}\n"
- "// Last one without readTag.\n"
- "newArray[i] = new $type$();\n");
-
- if (descriptor_->type() == FieldDescriptor::TYPE_GROUP) {
- printer->Print(variables_,
- "input.readGroup(newArray[i], $number$);\n");
- } else {
- printer->Print(variables_,
- "input.readMessage(newArray[i]);\n");
- }
-
- printer->Print(variables_,
- "this.$name$ = newArray;\n");
-}
-
-void RepeatedMessageFieldGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ != null && this.$name$.length > 0) {\n"
- " for (int i = 0; i < this.$name$.length; i++) {\n"
- " $type$ element = this.$name$[i];\n"
- " if (element != null) {\n"
- " output.write$group_or_message$($number$, element);\n"
- " }\n"
- " }\n"
- "}\n");
-}
-
-void RepeatedMessageFieldGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ != null && this.$name$.length > 0) {\n"
- " for (int i = 0; i < this.$name$.length; i++) {\n"
- " $type$ element = this.$name$[i];\n"
- " if (element != null) {\n"
- " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
- " .compute$group_or_message$Size($number$, element);\n"
- " }\n"
- " }\n"
- "}\n");
-}
-
-void RepeatedMessageFieldGenerator::
-GenerateFixClonedCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ != null && this.$name$.length > 0) {\n"
- " cloned.$name$ = new $type$[this.$name$.length];\n"
- " for (int i = 0; i < this.$name$.length; i++) {\n"
- " if (this.$name$[i] != null) {\n"
- " cloned.$name$[i] = this.$name$[i].clone();\n"
- " }\n"
- " }\n"
- "}\n");
-}
-
-void RepeatedMessageFieldGenerator::
-GenerateEqualsCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (!com.google.protobuf.nano.InternalNano.equals(\n"
- " this.$name$, other.$name$)) {\n"
- " return false;\n"
- "}\n");
-}
-
-void RepeatedMessageFieldGenerator::
-GenerateHashCodeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "result = 31 * result\n"
- " + com.google.protobuf.nano.InternalNano.hashCode(this.$name$);\n");
-}
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-} // namespace google
diff --git a/src/google/protobuf/compiler/javanano/javanano_message_field.h b/src/google/protobuf/compiler/javanano/javanano_message_field.h
deleted file mode 100644
index 0ae8879b..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_message_field.h
+++ /dev/null
@@ -1,121 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_MESSAGE_FIELD_H__
-#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_MESSAGE_FIELD_H__
-
-#include <map>
-#include <string>
-#include <google/protobuf/compiler/javanano/javanano_field.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-class MessageFieldGenerator : public FieldGenerator {
- public:
- explicit MessageFieldGenerator(
- const FieldDescriptor* descriptor, const Params& params);
- ~MessageFieldGenerator();
-
- // implements FieldGenerator ---------------------------------------
- void GenerateMembers(io::Printer* printer, bool lazy_init) const;
- void GenerateClearCode(io::Printer* printer) const;
- void GenerateMergingCode(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
- void GenerateEqualsCode(io::Printer* printer) const;
- void GenerateHashCodeCode(io::Printer* printer) const;
- void GenerateFixClonedCode(io::Printer* printer) const;
-
- private:
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator);
-};
-
-class MessageOneofFieldGenerator : public FieldGenerator {
- public:
- explicit MessageOneofFieldGenerator(const FieldDescriptor* descriptor,
- const Params& params);
- ~MessageOneofFieldGenerator();
-
- // implements FieldGenerator ---------------------------------------
- void GenerateMembers(io::Printer* printer, bool lazy_init) const;
- void GenerateClearCode(io::Printer* printer) const;
- void GenerateMergingCode(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
- void GenerateEqualsCode(io::Printer* printer) const;
- void GenerateHashCodeCode(io::Printer* printer) const;
- void GenerateFixClonedCode(io::Printer* printer) const;
-
- private:
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageOneofFieldGenerator);
-};
-
-class RepeatedMessageFieldGenerator : public FieldGenerator {
- public:
- explicit RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor,
- const Params& params);
- ~RepeatedMessageFieldGenerator();
-
- // implements FieldGenerator ---------------------------------------
- void GenerateMembers(io::Printer* printer, bool lazy_init) const;
- void GenerateClearCode(io::Printer* printer) const;
- void GenerateMergingCode(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
- void GenerateEqualsCode(io::Printer* printer) const;
- void GenerateHashCodeCode(io::Printer* printer) const;
- void GenerateFixClonedCode(io::Printer* printer) const;
-
- private:
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator);
-};
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-
-} // namespace google
-#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_MESSAGE_FIELD_H__
diff --git a/src/google/protobuf/compiler/javanano/javanano_params.h b/src/google/protobuf/compiler/javanano/javanano_params.h
deleted file mode 100644
index 3594767d..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_params.h
+++ /dev/null
@@ -1,258 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2010 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: wink@google.com (Wink Saville)
-
-#ifndef PROTOBUF_COMPILER_JAVANANO_JAVANANO_PARAMS_H_
-#define PROTOBUF_COMPILER_JAVANANO_JAVANANO_PARAMS_H_
-
-#include <map>
-#include <set>
-#include <google/protobuf/stubs/strutil.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-enum eMultipleFiles { JAVANANO_MUL_UNSET, JAVANANO_MUL_FALSE, JAVANANO_MUL_TRUE };
-
-// Parameters for used by the generators
-class Params {
- public:
- typedef std::map<string, string> NameMap;
- typedef std::set<string> NameSet;
- private:
- string empty_;
- string base_name_;
- eMultipleFiles override_java_multiple_files_;
- bool store_unknown_fields_;
- NameMap java_packages_;
- NameMap java_outer_classnames_;
- NameSet java_multiple_files_;
- bool generate_has_;
- bool java_enum_style_;
- bool optional_field_accessors_;
- bool use_reference_types_for_primitives_;
- bool generate_equals_;
- bool ignore_services_;
- bool parcelable_messages_;
- bool reftypes_primitive_enums_;
- bool generate_clear_;
- bool generate_clone_;
- bool generate_intdefs_;
-
- public:
- Params(const string & base_name) :
- empty_(""),
- base_name_(base_name),
- override_java_multiple_files_(JAVANANO_MUL_UNSET),
- store_unknown_fields_(false),
- generate_has_(false),
- java_enum_style_(false),
- optional_field_accessors_(false),
- use_reference_types_for_primitives_(false),
- generate_equals_(false),
- ignore_services_(false),
- parcelable_messages_(false),
- reftypes_primitive_enums_(false),
- generate_clear_(true),
- generate_clone_(false),
- generate_intdefs_(false) {
- }
-
- const string& base_name() const {
- return base_name_;
- }
-
- bool has_java_package(const string& file_name) const {
- return java_packages_.find(file_name)
- != java_packages_.end();
- }
- void set_java_package(const string& file_name,
- const string& java_package) {
- java_packages_[file_name] = java_package;
- }
- const string& java_package(const string& file_name) const {
- NameMap::const_iterator itr;
-
- itr = java_packages_.find(file_name);
- if (itr == java_packages_.end()) {
- return empty_;
- } else {
- return itr->second;
- }
- }
- const NameMap& java_packages() {
- return java_packages_;
- }
-
- bool has_java_outer_classname(const string& file_name) const {
- return java_outer_classnames_.find(file_name)
- != java_outer_classnames_.end();
- }
- void set_java_outer_classname(const string& file_name,
- const string& java_outer_classname) {
- java_outer_classnames_[file_name] = java_outer_classname;
- }
- const string& java_outer_classname(const string& file_name) const {
- NameMap::const_iterator itr;
-
- itr = java_outer_classnames_.find(file_name);
- if (itr == java_outer_classnames_.end()) {
- return empty_;
- } else {
- return itr->second;
- }
- }
- const NameMap& java_outer_classnames() {
- return java_outer_classnames_;
- }
-
- void set_override_java_multiple_files(bool java_multiple_files) {
- if (java_multiple_files) {
- override_java_multiple_files_ = JAVANANO_MUL_TRUE;
- } else {
- override_java_multiple_files_ = JAVANANO_MUL_FALSE;
- }
- }
- void clear_override_java_multiple_files() {
- override_java_multiple_files_ = JAVANANO_MUL_UNSET;
- }
-
- void set_java_multiple_files(const string& file_name, bool value) {
- if (value) {
- java_multiple_files_.insert(file_name);
- } else {
- java_multiple_files_.erase(file_name);
- }
- }
- bool java_multiple_files(const string& file_name) const {
- switch (override_java_multiple_files_) {
- case JAVANANO_MUL_FALSE:
- return false;
- case JAVANANO_MUL_TRUE:
- return true;
- default:
- return java_multiple_files_.find(file_name)
- != java_multiple_files_.end();
- }
- }
-
- void set_store_unknown_fields(bool value) {
- store_unknown_fields_ = value;
- }
- bool store_unknown_fields() const {
- return store_unknown_fields_;
- }
-
- void set_generate_has(bool value) {
- generate_has_ = value;
- }
- bool generate_has() const {
- return generate_has_;
- }
-
- void set_java_enum_style(bool value) {
- java_enum_style_ = value;
- }
- bool java_enum_style() const {
- return java_enum_style_;
- }
-
- void set_optional_field_accessors(bool value) {
- optional_field_accessors_ = value;
- }
- bool optional_field_accessors() const {
- return optional_field_accessors_;
- }
-
- void set_use_reference_types_for_primitives(bool value) {
- use_reference_types_for_primitives_ = value;
- }
- bool use_reference_types_for_primitives() const {
- return use_reference_types_for_primitives_;
- }
-
- void set_generate_equals(bool value) {
- generate_equals_ = value;
- }
- bool generate_equals() const {
- return generate_equals_;
- }
-
- void set_ignore_services(bool value) {
- ignore_services_ = value;
- }
- bool ignore_services() const {
- return ignore_services_;
- }
-
- void set_parcelable_messages(bool value) {
- parcelable_messages_ = value;
- }
- bool parcelable_messages() const {
- return parcelable_messages_;
- }
-
- void set_reftypes_primitive_enums(bool value) {
- reftypes_primitive_enums_ = value;
- }
- bool reftypes_primitive_enums() const {
- return reftypes_primitive_enums_;
- }
-
- void set_generate_clear(bool value) {
- generate_clear_ = value;
- }
- bool generate_clear() const {
- return generate_clear_;
- }
-
- void set_generate_clone(bool value) {
- generate_clone_ = value;
- }
- bool generate_clone() const {
- return generate_clone_;
- }
-
- void set_generate_intdefs(bool value) {
- generate_intdefs_ = value;
- }
- bool generate_intdefs() const {
- return generate_intdefs_;
- }
-};
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-} // namespace google
-#endif // PROTOBUF_COMPILER_JAVANANO_JAVANANO_PARAMS_H_
diff --git a/src/google/protobuf/compiler/javanano/javanano_primitive_field.cc b/src/google/protobuf/compiler/javanano/javanano_primitive_field.cc
deleted file mode 100644
index 66a0ff05..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_primitive_field.cc
+++ /dev/null
@@ -1,968 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#include <map>
-#include <math.h>
-#include <string>
-
-#include <google/protobuf/compiler/javanano/javanano_primitive_field.h>
-#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/compiler/javanano/javanano_helpers.h>
-#include <google/protobuf/io/printer.h>
-#include <google/protobuf/wire_format.h>
-#include <google/protobuf/stubs/strutil.h>
-#include <google/protobuf/stubs/substitute.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-using internal::WireFormat;
-using internal::WireFormatLite;
-
-namespace {
-
-bool IsReferenceType(JavaType type) {
- switch (type) {
- case JAVATYPE_INT : return false;
- case JAVATYPE_LONG : return false;
- case JAVATYPE_FLOAT : return false;
- case JAVATYPE_DOUBLE : return false;
- case JAVATYPE_BOOLEAN: return false;
- case JAVATYPE_STRING : return true;
- case JAVATYPE_BYTES : return true;
- case JAVATYPE_ENUM : return false;
- case JAVATYPE_MESSAGE: return true;
-
- // No default because we want the compiler to complain if any new
- // JavaTypes are added.
- }
-
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return false;
-}
-
-bool IsArrayType(JavaType type) {
- switch (type) {
- case JAVATYPE_INT : return false;
- case JAVATYPE_LONG : return false;
- case JAVATYPE_FLOAT : return false;
- case JAVATYPE_DOUBLE : return false;
- case JAVATYPE_BOOLEAN: return false;
- case JAVATYPE_STRING : return false;
- case JAVATYPE_BYTES : return true;
- case JAVATYPE_ENUM : return false;
- case JAVATYPE_MESSAGE: return false;
-
- // No default because we want the compiler to complain if any new
- // JavaTypes are added.
- }
-
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return false;
-}
-
-const char* GetCapitalizedType(const FieldDescriptor* field) {
- switch (field->type()) {
- case FieldDescriptor::TYPE_INT32 : return "Int32" ;
- case FieldDescriptor::TYPE_UINT32 : return "UInt32" ;
- case FieldDescriptor::TYPE_SINT32 : return "SInt32" ;
- case FieldDescriptor::TYPE_FIXED32 : return "Fixed32" ;
- case FieldDescriptor::TYPE_SFIXED32: return "SFixed32";
- case FieldDescriptor::TYPE_INT64 : return "Int64" ;
- case FieldDescriptor::TYPE_UINT64 : return "UInt64" ;
- case FieldDescriptor::TYPE_SINT64 : return "SInt64" ;
- case FieldDescriptor::TYPE_FIXED64 : return "Fixed64" ;
- case FieldDescriptor::TYPE_SFIXED64: return "SFixed64";
- case FieldDescriptor::TYPE_FLOAT : return "Float" ;
- case FieldDescriptor::TYPE_DOUBLE : return "Double" ;
- case FieldDescriptor::TYPE_BOOL : return "Bool" ;
- case FieldDescriptor::TYPE_STRING : return "String" ;
- case FieldDescriptor::TYPE_BYTES : return "Bytes" ;
- case FieldDescriptor::TYPE_ENUM : return "Enum" ;
- case FieldDescriptor::TYPE_GROUP : return "Group" ;
- case FieldDescriptor::TYPE_MESSAGE : return "Message" ;
-
- // No default because we want the compiler to complain if any new
- // types are added.
- }
-
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return NULL;
-}
-
-// For encodings with fixed sizes, returns that size in bytes. Otherwise
-// returns -1.
-int FixedSize(FieldDescriptor::Type type) {
- switch (type) {
- case FieldDescriptor::TYPE_INT32 : return -1;
- case FieldDescriptor::TYPE_INT64 : return -1;
- case FieldDescriptor::TYPE_UINT32 : return -1;
- case FieldDescriptor::TYPE_UINT64 : return -1;
- case FieldDescriptor::TYPE_SINT32 : return -1;
- case FieldDescriptor::TYPE_SINT64 : return -1;
- case FieldDescriptor::TYPE_FIXED32 : return WireFormatLite::kFixed32Size;
- case FieldDescriptor::TYPE_FIXED64 : return WireFormatLite::kFixed64Size;
- case FieldDescriptor::TYPE_SFIXED32: return WireFormatLite::kSFixed32Size;
- case FieldDescriptor::TYPE_SFIXED64: return WireFormatLite::kSFixed64Size;
- case FieldDescriptor::TYPE_FLOAT : return WireFormatLite::kFloatSize;
- case FieldDescriptor::TYPE_DOUBLE : return WireFormatLite::kDoubleSize;
-
- case FieldDescriptor::TYPE_BOOL : return WireFormatLite::kBoolSize;
- case FieldDescriptor::TYPE_ENUM : return -1;
-
- case FieldDescriptor::TYPE_STRING : return -1;
- case FieldDescriptor::TYPE_BYTES : return -1;
- case FieldDescriptor::TYPE_GROUP : return -1;
- case FieldDescriptor::TYPE_MESSAGE : return -1;
-
- // No default because we want the compiler to complain if any new
- // types are added.
- }
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return -1;
-}
-
-bool AllAscii(const string& text) {
- for (int i = 0; i < text.size(); i++) {
- if ((text[i] & 0x80) != 0) {
- return false;
- }
- }
- return true;
-}
-
-
-void SetPrimitiveVariables(const FieldDescriptor* descriptor, const Params params,
- std::map<string, string>* variables) {
- (*variables)["name"] =
- RenameJavaKeywords(UnderscoresToCamelCase(descriptor));
- (*variables)["capitalized_name"] =
- RenameJavaKeywords(UnderscoresToCapitalizedCamelCase(descriptor));
- (*variables)["number"] = SimpleItoa(descriptor->number());
- if (params.use_reference_types_for_primitives()
- && !descriptor->is_repeated()) {
- (*variables)["type"] = BoxedPrimitiveTypeName(GetJavaType(descriptor));
- } else {
- (*variables)["type"] = PrimitiveTypeName(GetJavaType(descriptor));
- }
- // Deals with defaults. For C++-string types (string and bytes),
- // we might need to have the generated code do the unicode decoding
- // (see comments in InternalNano.java for gory details.). We would
- // like to do this once into a static field and re-use that from
- // then on.
- if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_STRING &&
- !descriptor->default_value_string().empty() &&
- !params.use_reference_types_for_primitives()) {
- if (descriptor->type() == FieldDescriptor::TYPE_BYTES) {
- (*variables)["default"] = DefaultValue(params, descriptor);
- (*variables)["default_constant"] = FieldDefaultConstantName(descriptor);
- (*variables)["default_constant_value"] = strings::Substitute(
- "com.google.protobuf.nano.InternalNano.bytesDefaultValue(\"$0\")",
- CEscape(descriptor->default_value_string()));
- (*variables)["default_copy_if_needed"] =
- (*variables)["default"] + ".clone()";
- } else if (AllAscii(descriptor->default_value_string())) {
- // All chars are ASCII. In this case directly referencing a
- // CEscape()'d string literal works fine.
- (*variables)["default"] =
- "\"" + CEscape(descriptor->default_value_string()) + "\"";
- (*variables)["default_copy_if_needed"] = (*variables)["default"];
- } else {
- // Strings where some chars are non-ASCII. We need to save the
- // default value.
- (*variables)["default"] = DefaultValue(params, descriptor);
- (*variables)["default_constant"] = FieldDefaultConstantName(descriptor);
- (*variables)["default_constant_value"] = strings::Substitute(
- "com.google.protobuf.nano.InternalNano.stringDefaultValue(\"$0\")",
- CEscape(descriptor->default_value_string()));
- (*variables)["default_copy_if_needed"] = (*variables)["default"];
- }
- } else {
- // Non-string, non-bytes field. Defaults are literals.
- (*variables)["default"] = DefaultValue(params, descriptor);
- (*variables)["default_copy_if_needed"] = (*variables)["default"];
- }
- (*variables)["boxed_type"] = BoxedPrimitiveTypeName(GetJavaType(descriptor));
- (*variables)["capitalized_type"] = GetCapitalizedType(descriptor);
- (*variables)["tag"] = SimpleItoa(WireFormat::MakeTag(descriptor));
- (*variables)["tag_size"] = SimpleItoa(
- WireFormat::TagSize(descriptor->number(), descriptor->type()));
- (*variables)["non_packed_tag"] = SimpleItoa(
- internal::WireFormatLite::MakeTag(descriptor->number(),
- internal::WireFormat::WireTypeForFieldType(descriptor->type())));
- int fixed_size = FixedSize(descriptor->type());
- if (fixed_size != -1) {
- (*variables)["fixed_size"] = SimpleItoa(fixed_size);
- }
- (*variables)["message_name"] = descriptor->containing_type()->name();
- (*variables)["empty_array_name"] = EmptyArrayName(params, descriptor);
-}
-} // namespace
-
-// ===================================================================
-
-PrimitiveFieldGenerator::
-PrimitiveFieldGenerator(const FieldDescriptor* descriptor, const Params& params)
- : FieldGenerator(params), descriptor_(descriptor) {
- SetPrimitiveVariables(descriptor, params, &variables_);
-}
-
-PrimitiveFieldGenerator::~PrimitiveFieldGenerator() {}
-
-bool PrimitiveFieldGenerator::SavedDefaultNeeded() const {
- return variables_.find("default_constant") != variables_.end();
-}
-
-void PrimitiveFieldGenerator::GenerateInitSavedDefaultCode(io::Printer* printer) const {
- if (variables_.find("default_constant") != variables_.end()) {
- printer->Print(variables_,
- "$default_constant$ = $default_constant_value$;\n");
- }
-}
-
-void PrimitiveFieldGenerator::
-GenerateMembers(io::Printer* printer, bool lazy_init) const {
- if (variables_.find("default_constant") != variables_.end()) {
- // Those primitive types that need a saved default.
- if (lazy_init) {
- printer->Print(variables_,
- "private static $type$ $default_constant$;\n");
- } else {
- printer->Print(variables_,
- "private static final $type$ $default_constant$ =\n"
- " $default_constant_value$;\n");
- }
- }
-
- printer->Print(variables_,
- "public $type$ $name$;\n");
-
- if (params_.generate_has()) {
- printer->Print(variables_,
- "public boolean has$capitalized_name$;\n");
- }
-}
-
-void PrimitiveFieldGenerator::
-GenerateClearCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$name$ = $default_copy_if_needed$;\n");
-
- if (params_.generate_has()) {
- printer->Print(variables_,
- "has$capitalized_name$ = false;\n");
- }
-}
-
-void PrimitiveFieldGenerator::
-GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "this.$name$ = input.read$capitalized_type$();\n");
-
- if (params_.generate_has()) {
- printer->Print(variables_,
- "has$capitalized_name$ = true;\n");
- }
-}
-
-void PrimitiveFieldGenerator::
-GenerateSerializationConditional(io::Printer* printer) const {
- if (params_.use_reference_types_for_primitives()) {
- // For reference type mode, serialize based on equality
- // to null.
- printer->Print(variables_,
- "if (this.$name$ != null) {\n");
- return;
- }
- if (params_.generate_has()) {
- printer->Print(variables_,
- "if (has$capitalized_name$ || ");
- } else {
- printer->Print(variables_,
- "if (");
- }
- JavaType java_type = GetJavaType(descriptor_);
- if (IsArrayType(java_type)) {
- printer->Print(variables_,
- "!java.util.Arrays.equals(this.$name$, $default$)) {\n");
- } else if (IsReferenceType(java_type)) {
- printer->Print(variables_,
- "!this.$name$.equals($default$)) {\n");
- } else if (java_type == JAVATYPE_FLOAT) {
- printer->Print(variables_,
- "java.lang.Float.floatToIntBits(this.$name$)\n"
- " != java.lang.Float.floatToIntBits($default$)) {\n");
- } else if (java_type == JAVATYPE_DOUBLE) {
- printer->Print(variables_,
- "java.lang.Double.doubleToLongBits(this.$name$)\n"
- " != java.lang.Double.doubleToLongBits($default$)) {\n");
- } else {
- printer->Print(variables_,
- "this.$name$ != $default$) {\n");
- }
-}
-
-void PrimitiveFieldGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- if (descriptor_->is_required() && !params_.generate_has()) {
- // Always serialize a required field if we don't have the 'has' signal.
- printer->Print(variables_,
- "output.write$capitalized_type$($number$, this.$name$);\n");
- } else {
- GenerateSerializationConditional(printer);
- printer->Print(variables_,
- " output.write$capitalized_type$($number$, this.$name$);\n"
- "}\n");
- }
-}
-
-void PrimitiveFieldGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- if (descriptor_->is_required() && !params_.generate_has()) {
- printer->Print(variables_,
- "size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
- " .compute$capitalized_type$Size($number$, this.$name$);\n");
- } else {
- GenerateSerializationConditional(printer);
- printer->Print(variables_,
- " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
- " .compute$capitalized_type$Size($number$, this.$name$);\n"
- "}\n");
- }
-}
-
-void RepeatedPrimitiveFieldGenerator::
-GenerateFixClonedCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ != null && this.$name$.length > 0) {\n"
- " cloned.$name$ = this.$name$.clone();\n"
- "}\n");
-}
-
-void PrimitiveFieldGenerator::
-GenerateEqualsCode(io::Printer* printer) const {
- // We define equality as serialized form equality. If generate_has(),
- // then if the field value equals the default value in both messages,
- // but one's 'has' field is set and the other's is not, the serialized
- // forms are different and we should return false.
- JavaType java_type = GetJavaType(descriptor_);
- if (java_type == JAVATYPE_BYTES) {
- printer->Print(variables_,
- "if (!java.util.Arrays.equals(this.$name$, other.$name$)");
- if (params_.generate_has()) {
- printer->Print(variables_,
- "\n"
- " || (java.util.Arrays.equals(this.$name$, $default$)\n"
- " && this.has$capitalized_name$ != other.has$capitalized_name$)");
- }
- printer->Print(") {\n"
- " return false;\n"
- "}\n");
- } else if (java_type == JAVATYPE_STRING
- || params_.use_reference_types_for_primitives()) {
- printer->Print(variables_,
- "if (this.$name$ == null) {\n"
- " if (other.$name$ != null) {\n"
- " return false;\n"
- " }\n"
- "} else if (!this.$name$.equals(other.$name$)");
- if (params_.generate_has()) {
- printer->Print(variables_,
- "\n"
- " || (this.$name$.equals($default$)\n"
- " && this.has$capitalized_name$ != other.has$capitalized_name$)");
- }
- printer->Print(") {\n"
- " return false;\n"
- "}\n");
- } else if (java_type == JAVATYPE_FLOAT) {
- printer->Print(variables_,
- "{\n"
- " int bits = java.lang.Float.floatToIntBits(this.$name$);\n"
- " if (bits != java.lang.Float.floatToIntBits(other.$name$)");
- if (params_.generate_has()) {
- printer->Print(variables_,
- "\n"
- " || (bits == java.lang.Float.floatToIntBits($default$)\n"
- " && this.has$capitalized_name$ != other.has$capitalized_name$)");
- }
- printer->Print(") {\n"
- " return false;\n"
- " }\n"
- "}\n");
- } else if (java_type == JAVATYPE_DOUBLE) {
- printer->Print(variables_,
- "{\n"
- " long bits = java.lang.Double.doubleToLongBits(this.$name$);\n"
- " if (bits != java.lang.Double.doubleToLongBits(other.$name$)");
- if (params_.generate_has()) {
- printer->Print(variables_,
- "\n"
- " || (bits == java.lang.Double.doubleToLongBits($default$)\n"
- " && this.has$capitalized_name$ != other.has$capitalized_name$)");
- }
- printer->Print(") {\n"
- " return false;\n"
- " }\n"
- "}\n");
- } else {
- printer->Print(variables_,
- "if (this.$name$ != other.$name$");
- if (params_.generate_has()) {
- printer->Print(variables_,
- "\n"
- " || (this.$name$ == $default$\n"
- " && this.has$capitalized_name$ != other.has$capitalized_name$)");
- }
- printer->Print(") {\n"
- " return false;\n"
- "}\n");
- }
-}
-
-void PrimitiveFieldGenerator::
-GenerateHashCodeCode(io::Printer* printer) const {
- JavaType java_type = GetJavaType(descriptor_);
- if (java_type == JAVATYPE_BYTES) {
- printer->Print(variables_,
- "result = 31 * result + java.util.Arrays.hashCode(this.$name$);\n");
- } else if (java_type == JAVATYPE_STRING
- || params_.use_reference_types_for_primitives()) {
- printer->Print(variables_,
- "result = 31 * result\n"
- " + (this.$name$ == null ? 0 : this.$name$.hashCode());\n");
- } else {
- switch (java_type) {
- // For all Java primitive types below, the hash codes match the
- // results of BoxedType.valueOf(primitiveValue).hashCode().
- case JAVATYPE_INT:
- printer->Print(variables_,
- "result = 31 * result + this.$name$;\n");
- break;
- case JAVATYPE_LONG:
- printer->Print(variables_,
- "result = 31 * result\n"
- " + (int) (this.$name$ ^ (this.$name$ >>> 32));\n");
- break;
- case JAVATYPE_FLOAT:
- printer->Print(variables_,
- "result = 31 * result\n"
- " + java.lang.Float.floatToIntBits(this.$name$);\n");
- break;
- case JAVATYPE_DOUBLE:
- printer->Print(variables_,
- "{\n"
- " long v = java.lang.Double.doubleToLongBits(this.$name$);\n"
- " result = 31 * result + (int) (v ^ (v >>> 32));\n"
- "}\n");
- break;
- case JAVATYPE_BOOLEAN:
- printer->Print(variables_,
- "result = 31 * result + (this.$name$ ? 1231 : 1237);\n");
- break;
- default:
- GOOGLE_LOG(ERROR) << "unknown java type for primitive field";
- break;
- }
- }
-}
-
-// ===================================================================
-
-AccessorPrimitiveFieldGenerator::
-AccessorPrimitiveFieldGenerator(const FieldDescriptor* descriptor,
- const Params& params, int has_bit_index)
- : FieldGenerator(params), descriptor_(descriptor) {
- SetPrimitiveVariables(descriptor, params, &variables_);
- SetBitOperationVariables("has", has_bit_index, &variables_);
-}
-
-AccessorPrimitiveFieldGenerator::~AccessorPrimitiveFieldGenerator() {}
-
-bool AccessorPrimitiveFieldGenerator::SavedDefaultNeeded() const {
- return variables_.find("default_constant") != variables_.end();
-}
-
-void AccessorPrimitiveFieldGenerator::
-GenerateInitSavedDefaultCode(io::Printer* printer) const {
- if (variables_.find("default_constant") != variables_.end()) {
- printer->Print(variables_,
- "$default_constant$ = $default_constant_value$;\n");
- }
-}
-
-void AccessorPrimitiveFieldGenerator::
-GenerateMembers(io::Printer* printer, bool lazy_init) const {
- if (variables_.find("default_constant") != variables_.end()) {
- // Those primitive types that need a saved default.
- if (lazy_init) {
- printer->Print(variables_,
- "private static $type$ $default_constant$;\n");
- } else {
- printer->Print(variables_,
- "private static final $type$ $default_constant$ =\n"
- " $default_constant_value$;\n");
- }
- }
- printer->Print(variables_,
- "private $type$ $name$_;\n"
- "public $type$ get$capitalized_name$() {\n"
- " return $name$_;\n"
- "}\n"
- "public $message_name$ set$capitalized_name$($type$ value) {\n");
- if (IsReferenceType(GetJavaType(descriptor_))) {
- printer->Print(variables_,
- " if (value == null) {\n"
- " throw new java.lang.NullPointerException();\n"
- " }\n");
- }
- printer->Print(variables_,
- " $name$_ = value;\n"
- " $set_has$;\n"
- " return this;\n"
- "}\n"
- "public boolean has$capitalized_name$() {\n"
- " return $get_has$;\n"
- "}\n"
- "public $message_name$ clear$capitalized_name$() {\n"
- " $name$_ = $default_copy_if_needed$;\n"
- " $clear_has$;\n"
- " return this;\n"
- "}\n");
-}
-
-void AccessorPrimitiveFieldGenerator::
-GenerateClearCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$name$_ = $default_copy_if_needed$;\n");
-}
-
-void AccessorPrimitiveFieldGenerator::
-GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$name$_ = input.read$capitalized_type$();\n"
- "$set_has$;\n");
-}
-
-void AccessorPrimitiveFieldGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if ($get_has$) {\n"
- " output.write$capitalized_type$($number$, $name$_);\n"
- "}\n");
-}
-
-void AccessorPrimitiveFieldGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if ($get_has$) {\n"
- " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
- " .compute$capitalized_type$Size($number$, $name$_);\n"
- "}\n");
-}
-
-void AccessorPrimitiveFieldGenerator::
-GenerateEqualsCode(io::Printer* printer) const {
- switch (GetJavaType(descriptor_)) {
- // For all Java primitive types below, the equality checks match the
- // results of BoxedType.valueOf(primitiveValue).equals(otherValue).
- case JAVATYPE_FLOAT:
- printer->Print(variables_,
- "if ($different_has$\n"
- " || java.lang.Float.floatToIntBits($name$_)\n"
- " != java.lang.Float.floatToIntBits(other.$name$_)) {\n"
- " return false;\n"
- "}\n");
- break;
- case JAVATYPE_DOUBLE:
- printer->Print(variables_,
- "if ($different_has$\n"
- " || java.lang.Double.doubleToLongBits($name$_)\n"
- " != java.lang.Double.doubleToLongBits(other.$name$_)) {\n"
- " return false;\n"
- "}\n");
- break;
- case JAVATYPE_INT:
- case JAVATYPE_LONG:
- case JAVATYPE_BOOLEAN:
- printer->Print(variables_,
- "if ($different_has$\n"
- " || $name$_ != other.$name$_) {\n"
- " return false;\n"
- "}\n");
- break;
- case JAVATYPE_STRING:
- // Accessor style would guarantee $name$_ non-null
- printer->Print(variables_,
- "if ($different_has$\n"
- " || !$name$_.equals(other.$name$_)) {\n"
- " return false;\n"
- "}\n");
- break;
- case JAVATYPE_BYTES:
- // Accessor style would guarantee $name$_ non-null
- printer->Print(variables_,
- "if ($different_has$\n"
- " || !java.util.Arrays.equals($name$_, other.$name$_)) {\n"
- " return false;\n"
- "}\n");
- break;
- default:
- GOOGLE_LOG(ERROR) << "unknown java type for primitive field";
- break;
- }
-}
-
-void AccessorPrimitiveFieldGenerator::
-GenerateHashCodeCode(io::Printer* printer) const {
- switch (GetJavaType(descriptor_)) {
- // For all Java primitive types below, the hash codes match the
- // results of BoxedType.valueOf(primitiveValue).hashCode().
- case JAVATYPE_INT:
- printer->Print(variables_,
- "result = 31 * result + $name$_;\n");
- break;
- case JAVATYPE_LONG:
- printer->Print(variables_,
- "result = 31 * result + (int) ($name$_ ^ ($name$_ >>> 32));\n");
- break;
- case JAVATYPE_FLOAT:
- printer->Print(variables_,
- "result = 31 * result +\n"
- " java.lang.Float.floatToIntBits($name$_);\n");
- break;
- case JAVATYPE_DOUBLE:
- printer->Print(variables_,
- "{\n"
- " long v = java.lang.Double.doubleToLongBits($name$_);\n"
- " result = 31 * result + (int) (v ^ (v >>> 32));\n"
- "}\n");
- break;
- case JAVATYPE_BOOLEAN:
- printer->Print(variables_,
- "result = 31 * result + ($name$_ ? 1231 : 1237);\n");
- break;
- case JAVATYPE_STRING:
- // Accessor style would guarantee $name$_ non-null
- printer->Print(variables_,
- "result = 31 * result + $name$_.hashCode();\n");
- break;
- case JAVATYPE_BYTES:
- // Accessor style would guarantee $name$_ non-null
- printer->Print(variables_,
- "result = 31 * result + java.util.Arrays.hashCode($name$_);\n");
- break;
- default:
- GOOGLE_LOG(ERROR) << "unknown java type for primitive field";
- break;
- }
-}
-
-// ===================================================================
-
-PrimitiveOneofFieldGenerator::PrimitiveOneofFieldGenerator(
- const FieldDescriptor* descriptor, const Params& params)
- : FieldGenerator(params), descriptor_(descriptor) {
- SetPrimitiveVariables(descriptor, params, &variables_);
- SetCommonOneofVariables(descriptor, &variables_);
-}
-
-PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() {}
-
-void PrimitiveOneofFieldGenerator::GenerateMembers(
- io::Printer* printer, bool /*unused lazy_init*/) const {
- printer->Print(variables_,
- "public boolean has$capitalized_name$() {\n"
- " return $has_oneof_case$;\n"
- "}\n"
- "public $type$ get$capitalized_name$() {\n"
- " if ($has_oneof_case$) {\n"
- " return ($type$) ($boxed_type$) this.$oneof_name$_;\n"
- " }\n"
- " return $default$;\n"
- "}\n"
- "public $message_name$ set$capitalized_name$($type$ value) {\n"
- " $set_oneof_case$;\n"
- " this.$oneof_name$_ = value;\n"
- " return this;\n"
- "}\n");
-}
-
-void PrimitiveOneofFieldGenerator::GenerateClearCode(
- io::Printer* printer) const {
- // No clear method for oneof fields.
-}
-
-void PrimitiveOneofFieldGenerator::GenerateMergingCode(
- io::Printer* printer) const {
- printer->Print(variables_,
- "this.$oneof_name$_ = input.read$capitalized_type$();\n"
- "$set_oneof_case$;\n");
-}
-
-void PrimitiveOneofFieldGenerator::GenerateSerializationCode(
- io::Printer* printer) const {
- printer->Print(variables_,
- "if ($has_oneof_case$) {\n"
- " output.write$capitalized_type$(\n"
- " $number$, ($boxed_type$) this.$oneof_name$_);\n"
- "}\n");
-}
-
-void PrimitiveOneofFieldGenerator::GenerateSerializedSizeCode(
- io::Printer* printer) const {
- printer->Print(variables_,
- "if ($has_oneof_case$) {\n"
- " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
- " .compute$capitalized_type$Size(\n"
- " $number$, ($boxed_type$) this.$oneof_name$_);\n"
- "}\n");
-}
-
-void PrimitiveOneofFieldGenerator::GenerateEqualsCode(
- io::Printer* printer) const {
- GenerateOneofFieldEquals(descriptor_, variables_, printer);
-}
-
-void PrimitiveOneofFieldGenerator::GenerateHashCodeCode(
- io::Printer* printer) const {
- GenerateOneofFieldHashCode(descriptor_, variables_, printer);
-}
-
-// ===================================================================
-
-RepeatedPrimitiveFieldGenerator::RepeatedPrimitiveFieldGenerator(
- const FieldDescriptor* descriptor, const Params& params)
- : FieldGenerator(params), descriptor_(descriptor) {
- SetPrimitiveVariables(descriptor, params, &variables_);
-}
-
-RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() {}
-
-void RepeatedPrimitiveFieldGenerator::
-GenerateMembers(io::Printer* printer, bool /*unused init_defaults*/) const {
- printer->Print(variables_,
- "public $type$[] $name$;\n");
-}
-
-void RepeatedPrimitiveFieldGenerator::
-GenerateClearCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$name$ = $default$;\n");
-}
-
-void RepeatedPrimitiveFieldGenerator::
-GenerateMergingCode(io::Printer* printer) const {
- // First, figure out the length of the array, then parse.
- printer->Print(variables_,
- "int arrayLength = com.google.protobuf.nano.WireFormatNano\n"
- " .getRepeatedFieldArrayLength(input, $non_packed_tag$);\n"
- "int i = this.$name$ == null ? 0 : this.$name$.length;\n");
-
- if (GetJavaType(descriptor_) == JAVATYPE_BYTES) {
- printer->Print(variables_,
- "byte[][] newArray = new byte[i + arrayLength][];\n");
- } else {
- printer->Print(variables_,
- "$type$[] newArray = new $type$[i + arrayLength];\n");
- }
- printer->Print(variables_,
- "if (i != 0) {\n"
- " java.lang.System.arraycopy(this.$name$, 0, newArray, 0, i);\n"
- "}\n"
- "for (; i < newArray.length - 1; i++) {\n"
- " newArray[i] = input.read$capitalized_type$();\n"
- " input.readTag();\n"
- "}\n"
- "// Last one without readTag.\n"
- "newArray[i] = input.read$capitalized_type$();\n"
- "this.$name$ = newArray;\n");
-}
-
-void RepeatedPrimitiveFieldGenerator::
-GenerateMergingCodeFromPacked(io::Printer* printer) const {
- printer->Print(
- "int length = input.readRawVarint32();\n"
- "int limit = input.pushLimit(length);\n");
-
- // If we know the elements will all be of the same size, the arrayLength
- // can be calculated much more easily. However, FixedSize() returns 1 for
- // repeated bool fields, which are guaranteed to have the fixed size of
- // 1 byte per value only if we control the output. On the wire they can
- // legally appear as variable-size integers, so we need to use the slow
- // way for repeated bool fields.
- if (descriptor_->type() == FieldDescriptor::TYPE_BOOL
- || FixedSize(descriptor_->type()) == -1) {
- printer->Print(variables_,
- "// First pass to compute array length.\n"
- "int arrayLength = 0;\n"
- "int startPos = input.getPosition();\n"
- "while (input.getBytesUntilLimit() > 0) {\n"
- " input.read$capitalized_type$();\n"
- " arrayLength++;\n"
- "}\n"
- "input.rewindToPosition(startPos);\n");
- } else {
- printer->Print(variables_,
- "int arrayLength = length / $fixed_size$;\n");
- }
-
- printer->Print(variables_,
- "int i = this.$name$ == null ? 0 : this.$name$.length;\n"
- "$type$[] newArray = new $type$[i + arrayLength];\n"
- "if (i != 0) {\n"
- " java.lang.System.arraycopy(this.$name$, 0, newArray, 0, i);\n"
- "}\n"
- "for (; i < newArray.length; i++) {\n"
- " newArray[i] = input.read$capitalized_type$();\n"
- "}\n"
- "this.$name$ = newArray;\n"
- "input.popLimit(limit);\n");
-}
-
-void RepeatedPrimitiveFieldGenerator::
-GenerateRepeatedDataSizeCode(io::Printer* printer) const {
- // Creates a variable dataSize and puts the serialized size in there.
- // If the element type is a Java reference type, also generates
- // dataCount which stores the number of non-null elements in the field.
- if (IsReferenceType(GetJavaType(descriptor_))) {
- printer->Print(variables_,
- "int dataCount = 0;\n"
- "int dataSize = 0;\n"
- "for (int i = 0; i < this.$name$.length; i++) {\n"
- " $type$ element = this.$name$[i];\n"
- " if (element != null) {\n"
- " dataCount++;\n"
- " dataSize += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
- " .compute$capitalized_type$SizeNoTag(element);\n"
- " }\n"
- "}\n");
- } else if (FixedSize(descriptor_->type()) == -1) {
- printer->Print(variables_,
- "int dataSize = 0;\n"
- "for (int i = 0; i < this.$name$.length; i++) {\n"
- " $type$ element = this.$name$[i];\n"
- " dataSize += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
- " .compute$capitalized_type$SizeNoTag(element);\n"
- "}\n");
- } else {
- printer->Print(variables_,
- "int dataSize = $fixed_size$ * this.$name$.length;\n");
- }
-}
-
-void RepeatedPrimitiveFieldGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ != null && this.$name$.length > 0) {\n");
- printer->Indent();
-
- if (descriptor_->is_packable() && descriptor_->options().packed()) {
- GenerateRepeatedDataSizeCode(printer);
- printer->Print(variables_,
- "output.writeRawVarint32($tag$);\n"
- "output.writeRawVarint32(dataSize);\n"
- "for (int i = 0; i < this.$name$.length; i++) {\n"
- " output.write$capitalized_type$NoTag(this.$name$[i]);\n"
- "}\n");
- } else if (IsReferenceType(GetJavaType(descriptor_))) {
- printer->Print(variables_,
- "for (int i = 0; i < this.$name$.length; i++) {\n"
- " $type$ element = this.$name$[i];\n"
- " if (element != null) {\n"
- " output.write$capitalized_type$($number$, element);\n"
- " }\n"
- "}\n");
- } else {
- printer->Print(variables_,
- "for (int i = 0; i < this.$name$.length; i++) {\n"
- " output.write$capitalized_type$($number$, this.$name$[i]);\n"
- "}\n");
- }
-
- printer->Outdent();
- printer->Print("}\n");
-}
-
-void RepeatedPrimitiveFieldGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (this.$name$ != null && this.$name$.length > 0) {\n");
- printer->Indent();
-
- GenerateRepeatedDataSizeCode(printer);
-
- printer->Print(
- "size += dataSize;\n");
- if (descriptor_->is_packable() && descriptor_->options().packed()) {
- printer->Print(variables_,
- "size += $tag_size$;\n"
- "size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
- " .computeRawVarint32Size(dataSize);\n");
- } else if (IsReferenceType(GetJavaType(descriptor_))) {
- printer->Print(variables_,
- "size += $tag_size$ * dataCount;\n");
- } else {
- printer->Print(variables_,
- "size += $tag_size$ * this.$name$.length;\n");
- }
-
- printer->Outdent();
-
- printer->Print(
- "}\n");
-}
-
-void RepeatedPrimitiveFieldGenerator::
-GenerateEqualsCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (!com.google.protobuf.nano.InternalNano.equals(\n"
- " this.$name$, other.$name$)) {\n"
- " return false;\n"
- "}\n");
-}
-
-void RepeatedPrimitiveFieldGenerator::
-GenerateHashCodeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "result = 31 * result\n"
- " + com.google.protobuf.nano.InternalNano.hashCode(this.$name$);\n");
-}
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-} // namespace google
diff --git a/src/google/protobuf/compiler/javanano/javanano_primitive_field.h b/src/google/protobuf/compiler/javanano/javanano_primitive_field.h
deleted file mode 100644
index d7d72d57..00000000
--- a/src/google/protobuf/compiler/javanano/javanano_primitive_field.h
+++ /dev/null
@@ -1,150 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// http://code.google.com/p/protobuf/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_PRIMITIVE_FIELD_H__
-#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_PRIMITIVE_FIELD_H__
-
-#include <map>
-#include <string>
-#include <google/protobuf/compiler/javanano/javanano_field.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace javanano {
-
-class PrimitiveFieldGenerator : public FieldGenerator {
- public:
- explicit PrimitiveFieldGenerator(
- const FieldDescriptor* descriptor, const Params& params);
- ~PrimitiveFieldGenerator();
-
- // implements FieldGenerator ---------------------------------------
- bool SavedDefaultNeeded() const;
- void GenerateInitSavedDefaultCode(io::Printer* printer) const;
- void GenerateMembers(io::Printer* printer, bool lazy_init) const;
- void GenerateClearCode(io::Printer* printer) const;
- void GenerateMergingCode(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
- void GenerateEqualsCode(io::Printer* printer) const;
- void GenerateHashCodeCode(io::Printer* printer) const;
-
- private:
- void GenerateSerializationConditional(io::Printer* printer) const;
-
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator);
-};
-
-class AccessorPrimitiveFieldGenerator : public FieldGenerator {
- public:
- explicit AccessorPrimitiveFieldGenerator(const FieldDescriptor* descriptor,
- const Params &params, int has_bit_index);
- ~AccessorPrimitiveFieldGenerator();
-
- // implements FieldGenerator ---------------------------------------
- bool SavedDefaultNeeded() const;
- void GenerateInitSavedDefaultCode(io::Printer* printer) const;
- void GenerateMembers(io::Printer* printer, bool lazy_init) const;
- void GenerateClearCode(io::Printer* printer) const;
- void GenerateMergingCode(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
- void GenerateEqualsCode(io::Printer* printer) const;
- void GenerateHashCodeCode(io::Printer* printer) const;
-
- private:
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(AccessorPrimitiveFieldGenerator);
-};
-
-class PrimitiveOneofFieldGenerator : public FieldGenerator {
- public:
- explicit PrimitiveOneofFieldGenerator(
- const FieldDescriptor* descriptor, const Params& params);
- ~PrimitiveOneofFieldGenerator();
-
- // implements FieldGenerator ---------------------------------------
- void GenerateMembers(io::Printer* printer, bool lazy_init) const;
- void GenerateClearCode(io::Printer* printer) const;
- void GenerateMergingCode(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
- void GenerateEqualsCode(io::Printer* printer) const;
- void GenerateHashCodeCode(io::Printer* printer) const;
-
- private:
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveOneofFieldGenerator);
-};
-
-class RepeatedPrimitiveFieldGenerator : public FieldGenerator {
- public:
- explicit RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor,
- const Params& params);
- ~RepeatedPrimitiveFieldGenerator();
-
- // implements FieldGenerator ---------------------------------------
- void GenerateMembers(io::Printer* printer, bool lazy_init) const;
- void GenerateClearCode(io::Printer* printer) const;
- void GenerateMergingCode(io::Printer* printer) const;
- void GenerateMergingCodeFromPacked(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
- void GenerateEqualsCode(io::Printer* printer) const;
- void GenerateHashCodeCode(io::Printer* printer) const;
- void GenerateFixClonedCode(io::Printer* printer) const;
-
- private:
- void GenerateRepeatedDataSizeCode(io::Printer* printer) const;
-
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator);
-};
-
-} // namespace javanano
-} // namespace compiler
-} // namespace protobuf
-
-} // namespace google
-#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_PRIMITIVE_FIELD_H__
diff --git a/src/google/protobuf/compiler/js/embed.cc b/src/google/protobuf/compiler/js/embed.cc
deleted file mode 100644
index a725b62e..00000000
--- a/src/google/protobuf/compiler/js/embed.cc
+++ /dev/null
@@ -1,112 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-#include <cassert>
-#include <cstdlib>
-#include <fstream>
-#include <iostream>
-#include <string>
-
-const char output_file[] = "well_known_types_embed.cc";
-
-static bool AsciiIsPrint(unsigned char c) {
- return c >= 32 && c < 127;
-}
-
-static char ToDecimalDigit(int num) {
- assert(num < 10);
- return '0' + num;
-}
-
-static std::string CEscape(const std::string& str) {
- std::string dest;
-
- for (size_t i = 0; i < str.size(); ++i) {
- unsigned char ch = str[i];
- switch (ch) {
- case '\n': dest += "\\n"; break;
- case '\r': dest += "\\r"; break;
- case '\t': dest += "\\t"; break;
- case '\"': dest += "\\\""; break;
- case '\\': dest += "\\\\"; break;
- default:
- if (AsciiIsPrint(ch)) {
- dest += ch;
- } else {
- dest += "\\";
- dest += ToDecimalDigit(ch / 64);
- dest += ToDecimalDigit((ch % 64) / 8);
- dest += ToDecimalDigit(ch % 8);
- }
- break;
- }
- }
-
- return dest;
-}
-
-static void AddFile(const char* name, std::basic_ostream<char>* out) {
- std::ifstream in(name);
-
- if (!in.is_open()) {
- std::cerr << "Couldn't open input file: " << name << "\n";
- std::exit(EXIT_FAILURE);
- }
-
- // Make canonical name only include the final element.
- for (const char *p = name; *p; p++) {
- if (*p == '/') {
- name = p + 1;
- }
- }
-
- *out << "{\"" << CEscape(name) << "\",\n";
-
- for (std::string line; std::getline(in, line); ) {
- *out << " \"" << CEscape(line) << "\\n\"\n";
- }
-
- *out << "},\n";
-}
-
-int main(int argc, char *argv[]) {
- std::cout << "#include "
- "\"google/protobuf/compiler/js/well_known_types_embed.h\"\n";
- std::cout << "struct FileToc well_known_types_js[] = {\n";
-
- for (int i = 1; i < argc; i++) {
- AddFile(argv[i], &std::cout);
- }
-
- std::cout << " {NULL, NULL} // Terminate the list.\n";
- std::cout << "};\n";
-
- return EXIT_SUCCESS;
-}
diff --git a/src/google/protobuf/compiler/js/js_generator.cc b/src/google/protobuf/compiler/js/js_generator.cc
index fd2d3dfd..d25a3668 100755..100644
--- a/src/google/protobuf/compiler/js/js_generator.cc
+++ b/src/google/protobuf/compiler/js/js_generator.cc
@@ -35,9 +35,6 @@
#include <limits>
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
#include <utility>
#include <vector>
@@ -52,6 +49,7 @@
#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/strutil.h>
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -278,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.
@@ -1677,8 +1676,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(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);
+ }
}
}
}
@@ -2062,6 +2072,7 @@ void Generator::GenerateOneofCaseDefinition(
" $upcase$: $number$",
"upcase", ToEnumCase(oneof->field(i)->name()),
"number", JSFieldIndex(oneof->field(i)));
+ printer->Annotate("upcase", oneof->field(i));
}
printer->Print(
@@ -2768,28 +2779,33 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
void Generator::GenerateRepeatedPrimitiveHelperMethods(
const GeneratorOptions& options, io::Printer* printer,
const FieldDescriptor* field, bool untyped) const {
+ // clang-format off
printer->Print(
"/**\n"
" * @param {!$optionaltype$} value\n"
- " * @param {number=} opt_index\n"
+ " * @param {number=} opt_index$returndoc$\n"
" */\n"
"$class$.prototype.$addername$ = function(value, opt_index) {\n"
" jspb.Message.addToRepeatedField(this, $index$",
"class", GetMessagePath(options, field->containing_type()), "addername",
"add" + JSGetterName(options, field, BYTES_DEFAULT,
/* drop_list = */ true),
- "optionaltype", JSTypeName(options, field, BYTES_DEFAULT), "index",
- JSFieldIndex(field));
+ "optionaltype", JSTypeName(options, field, BYTES_DEFAULT),
+ "index", JSFieldIndex(field),
+ "returndoc", JSReturnDoc(options, field));
printer->Annotate("addername", field);
printer->Print(
- "$oneofgroup$, $type$value$rptvalueinit$$typeclose$, opt_index);\n"
+ "$oneofgroup$, $type$value$rptvalueinit$$typeclose$, "
+ "opt_index);$returnvalue$\n"
"};\n"
"\n"
"\n",
"type", untyped ? "/** @type{string|number|boolean|!Uint8Array} */(" : "",
"typeclose", untyped ? ")" : "", "oneofgroup",
(field->containing_oneof() ? (", " + JSOneofArray(options, field)) : ""),
- "rptvalueinit", "");
+ "rptvalueinit", "",
+ "returnvalue", JSReturnClause(field));
+ // clang-format on
}
void Generator::GenerateRepeatedMessageHelperMethods(
@@ -2958,8 +2974,12 @@ void Generator::GenerateClassDeserializeBinaryField(
if (value_field->type() == FieldDescriptor::TYPE_MESSAGE) {
printer->Print(", $messageType$.deserializeBinaryFromReader",
"messageType", GetMessagePath(options, value_field->message_type()));
+ } else {
+ printer->Print(", null");
}
-
+ printer->Print(", $defaultKey$",
+ "defaultKey", JSFieldDefault(key_field)
+ );
printer->Print(");\n");
printer->Print(" });\n");
} else {
@@ -3206,21 +3226,24 @@ void Generator::GenerateExtension(const GeneratorOptions& options,
? GetMessagePath(options, field->extension_scope())
: GetFilePath(options, field->file()));
+ const string extension_object_name = JSObjectFieldName(options, field);
printer->Print(
"\n"
"/**\n"
" * A tuple of {field number, class constructor} for the extension\n"
- " * field named `$name$`.\n"
+ " * field named `$nameInComment$`.\n"
" * @type {!jspb.ExtensionFieldInfo<$extensionType$>}\n"
" */\n"
"$class$.$name$ = new jspb.ExtensionFieldInfo(\n",
- "name", JSObjectFieldName(options, field),
+ "nameInComment", extension_object_name,
+ "name", extension_object_name,
"class", extension_scope,
"extensionType", JSFieldTypeAnnotation(
options, field,
/* is_setter_argument = */ false,
/* force_present = */ true,
/* singular_if_not_packed = */ false));
+ printer->Annotate("name", field);
printer->Print(
" $index$,\n"
" {$name$: 0},\n"
@@ -3230,7 +3253,7 @@ void Generator::GenerateExtension(const GeneratorOptions& options,
" $toObject$),\n"
" $repeated$);\n",
"index", SimpleItoa(field->number()),
- "name", JSObjectFieldName(options, field),
+ "name", extension_object_name,
"ctor", (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ?
SubmessageTypeRef(options, field) : string("null")),
"toObject", (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ?
@@ -3249,7 +3272,7 @@ void Generator::GenerateExtension(const GeneratorOptions& options,
"extendName",
JSExtensionsObjectName(options, field->file(), field->containing_type()),
"index", SimpleItoa(field->number()), "class", extension_scope, "name",
- JSObjectFieldName(options, field), "binaryReaderFn",
+ extension_object_name, "binaryReaderFn",
JSBinaryReaderMethodName(options, field), "binaryWriterFn",
JSBinaryWriterMethodName(options, field), "binaryMessageSerializeFn",
(field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE)
@@ -3272,7 +3295,7 @@ void Generator::GenerateExtension(const GeneratorOptions& options,
field->containing_type()),
"index", SimpleItoa(field->number()),
"class", extension_scope,
- "name", JSObjectFieldName(options, field));
+ "name", extension_object_name);
}
bool GeneratorOptions::ParseFromOptions(
@@ -3314,6 +3337,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") {
@@ -3423,15 +3448,23 @@ 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",
+ "var $alias$ = require('$file$');\n"
+ "goog.object.extend(proto, $alias$);\n",
"alias", ModuleAlias(name),
"file",
GetRootPath(file->name(), name) + GetJSFilename(options, name));
@@ -3470,9 +3503,13 @@ 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.
@@ -3500,7 +3537,7 @@ bool Generator::GenerateAll(const std::vector<const FileDescriptor*>& files,
// All output should go in a single file.
string filename = options.output_dir + "/" + options.library +
options.GetFileNameExtension();
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
+ std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
GOOGLE_CHECK(output.get());
io::Printer printer(output.get(), '$');
@@ -3549,7 +3586,7 @@ bool Generator::GenerateAll(const std::vector<const FileDescriptor*>& files,
}
string filename = GetMessageFileName(options, desc);
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
context->Open(filename));
GOOGLE_CHECK(output.get());
io::Printer printer(output.get(), '$');
@@ -3575,7 +3612,7 @@ bool Generator::GenerateAll(const std::vector<const FileDescriptor*>& files,
}
string filename = GetEnumFileName(options, enumdesc);
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
context->Open(filename));
GOOGLE_CHECK(output.get());
io::Printer printer(output.get(), '$');
@@ -3598,7 +3635,7 @@ bool Generator::GenerateAll(const std::vector<const FileDescriptor*>& files,
if (allowed_set.count(file) == 1) {
string filename = GetExtensionFileName(options, file);
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
context->Open(filename));
GOOGLE_CHECK(output.get());
io::Printer printer(output.get(), '$');
@@ -3634,7 +3671,7 @@ bool Generator::GenerateAll(const std::vector<const FileDescriptor*>& files,
string filename =
options.output_dir + "/" + GetJSFilename(options, file->name());
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
+ std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
GOOGLE_CHECK(output.get());
GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
diff --git a/src/google/protobuf/compiler/js/js_generator.h b/src/google/protobuf/compiler/js/js_generator.h
index 3cc60e22..b50ef7fd 100755..100644
--- a/src/google/protobuf/compiler/js/js_generator.h
+++ b/src/google/protobuf/compiler/js/js_generator.h
@@ -63,10 +63,11 @@ struct GeneratorOptions {
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()
diff --git a/src/google/protobuf/compiler/js/well_known_types_embed.cc b/src/google/protobuf/compiler/js/well_known_types_embed.cc
new file mode 100644
index 00000000..e5ee5510
--- /dev/null
+++ b/src/google/protobuf/compiler/js/well_known_types_embed.cc
@@ -0,0 +1,225 @@
+#include <google/protobuf/compiler/js/well_known_types_embed.h>
+
+struct FileToc well_known_types_js[] = {
+ {"any.js",
+ "/* This code will be inserted into generated code for\n"
+ " * google/protobuf/any.proto. */\n"
+ "\n"
+ "/**\n"
+ " * Returns the type name contained in this instance, if any.\n"
+ " * @return {string|undefined}\n"
+ " */\n"
+ "proto.google.protobuf.Any.prototype.getTypeName = function() {\n"
+ " return this.getTypeUrl().split('/').pop();\n"
+ "};\n"
+ "\n"
+ "\n"
+ "/**\n"
+ " * Packs the given message instance into this Any.\n"
+ " * @param {!Uint8Array} serialized The serialized data to pack.\n"
+ " * @param {string} name The type name of this message object.\n"
+ " * @param {string=} opt_typeUrlPrefix the type URL prefix.\n"
+ " */\n"
+ "proto.google.protobuf.Any.prototype.pack = function(serialized, name,\n"
+ " opt_typeUrlPrefix) "
+ "{\n"
+ " if (!opt_typeUrlPrefix) {\n"
+ " opt_typeUrlPrefix = 'type.googleapis.com/';\n"
+ " }\n"
+ "\n"
+ " if (opt_typeUrlPrefix.substr(-1) != '/') {\n"
+ " this.setTypeUrl(opt_typeUrlPrefix + '/' + name);\n"
+ " } else {\n"
+ " this.setTypeUrl(opt_typeUrlPrefix + name);\n"
+ " }\n"
+ "\n"
+ " this.setValue(serialized);\n"
+ "};\n"
+ "\n"
+ "\n"
+ "/**\n"
+ " * @template T\n"
+ " * Unpacks this Any into the given message object.\n"
+ " * @param {function(Uint8Array):T} deserialize Function that will "
+ "deserialize\n"
+ " * the binary data properly.\n"
+ " * @param {string} name The expected type name of this message object.\n"
+ " * @return {?T} If the name matched the expected name, returns the "
+ "deserialized\n"
+ " * object, otherwise returns null.\n"
+ " */\n"
+ "proto.google.protobuf.Any.prototype.unpack = function(deserialize, name) "
+ "{\n"
+ " if (this.getTypeName() == name) {\n"
+ " return deserialize(this.getValue_asU8());\n"
+ " } else {\n"
+ " return null;\n"
+ " }\n"
+ "};\n"},
+ {"timestamp.js",
+ "/* This code will be inserted into generated code for\n"
+ " * google/protobuf/timestamp.proto. */\n"
+ "\n"
+ "/**\n"
+ " * Returns a JavaScript 'Date' object corresponding to this Timestamp.\n"
+ " * @return {!Date}\n"
+ " */\n"
+ "proto.google.protobuf.Timestamp.prototype.toDate = function() {\n"
+ " var seconds = this.getSeconds();\n"
+ " var nanos = this.getNanos();\n"
+ "\n"
+ " return new Date((seconds * 1000) + (nanos / 1000000));\n"
+ "};\n"
+ "\n"
+ "\n"
+ "/**\n"
+ " * Sets the value of this Timestamp object to be the given Date.\n"
+ " * @param {!Date} value The value to set.\n"
+ " */\n"
+ "proto.google.protobuf.Timestamp.prototype.fromDate = function(value) {\n"
+ " this.setSeconds(Math.floor(value.getTime() / 1000));\n"
+ " this.setNanos(value.getMilliseconds() * 1000000);\n"
+ "};\n"},
+ {"struct.js",
+ "/* This code will be inserted into generated code for\n"
+ " * google/protobuf/struct.proto. */\n"
+ "\n"
+ "/**\n"
+ " * Typedef representing plain JavaScript values that can go into a\n"
+ " * Struct.\n"
+ " * @typedef {null|number|string|boolean|Array|Object}\n"
+ " */\n"
+ "proto.google.protobuf.JavaScriptValue;\n"
+ "\n"
+ "\n"
+ "/**\n"
+ " * Converts this Value object to a plain JavaScript value.\n"
+ " * @return {?proto.google.protobuf.JavaScriptValue} a plain JavaScript\n"
+ " * value representing this Struct.\n"
+ " */\n"
+ "proto.google.protobuf.Value.prototype.toJavaScript = function() {\n"
+ " var kindCase = proto.google.protobuf.Value.KindCase;\n"
+ " switch (this.getKindCase()) {\n"
+ " case kindCase.NULL_VALUE:\n"
+ " return null;\n"
+ " case kindCase.NUMBER_VALUE:\n"
+ " return this.getNumberValue();\n"
+ " case kindCase.STRING_VALUE:\n"
+ " return this.getStringValue();\n"
+ " case kindCase.BOOL_VALUE:\n"
+ " return this.getBoolValue();\n"
+ " case kindCase.STRUCT_VALUE:\n"
+ " return this.getStructValue().toJavaScript();\n"
+ " case kindCase.LIST_VALUE:\n"
+ " return this.getListValue().toJavaScript();\n"
+ " default:\n"
+ " throw new Error('Unexpected struct type');\n"
+ " }\n"
+ "};\n"
+ "\n"
+ "\n"
+ "/**\n"
+ " * Converts this JavaScript value to a new Value proto.\n"
+ " * @param {!proto.google.protobuf.JavaScriptValue} value The value to\n"
+ " * convert.\n"
+ " * @return {!proto.google.protobuf.Value} The newly constructed value.\n"
+ " */\n"
+ "proto.google.protobuf.Value.fromJavaScript = function(value) {\n"
+ " var ret = new proto.google.protobuf.Value();\n"
+ " switch (goog.typeOf(value)) {\n"
+ " case 'string':\n"
+ " ret.setStringValue(/** @type {string} */ (value));\n"
+ " break;\n"
+ " case 'number':\n"
+ " ret.setNumberValue(/** @type {number} */ (value));\n"
+ " break;\n"
+ " case 'boolean':\n"
+ " ret.setBoolValue(/** @type {boolean} */ (value));\n"
+ " break;\n"
+ " case 'null':\n"
+ " ret.setNullValue(proto.google.protobuf.NullValue.NULL_VALUE);\n"
+ " break;\n"
+ " case 'array':\n"
+ " ret.setListValue(proto.google.protobuf.ListValue.fromJavaScript(\n"
+ " /** @type{!Array} */ (value)));\n"
+ " break;\n"
+ " case 'object':\n"
+ " ret.setStructValue(proto.google.protobuf.Struct.fromJavaScript(\n"
+ " /** @type{!Object} */ (value)));\n"
+ " break;\n"
+ " default:\n"
+ " throw new Error('Unexpected struct type.');\n"
+ " }\n"
+ "\n"
+ " return ret;\n"
+ "};\n"
+ "\n"
+ "\n"
+ "/**\n"
+ " * Converts this ListValue object to a plain JavaScript array.\n"
+ " * @return {!Array} a plain JavaScript array representing this List.\n"
+ " */\n"
+ "proto.google.protobuf.ListValue.prototype.toJavaScript = function() {\n"
+ " var ret = [];\n"
+ " var values = this.getValuesList();\n"
+ "\n"
+ " for (var i = 0; i < values.length; i++) {\n"
+ " ret[i] = values[i].toJavaScript();\n"
+ " }\n"
+ "\n"
+ " return ret;\n"
+ "};\n"
+ "\n"
+ "\n"
+ "/**\n"
+ " * Constructs a ListValue protobuf from this plain JavaScript array.\n"
+ " * @param {!Array} array a plain JavaScript array\n"
+ " * @return {proto.google.protobuf.ListValue} a new ListValue object\n"
+ " */\n"
+ "proto.google.protobuf.ListValue.fromJavaScript = function(array) {\n"
+ " var ret = new proto.google.protobuf.ListValue();\n"
+ "\n"
+ " for (var i = 0; i < array.length; i++) {\n"
+ " "
+ "ret.addValues(proto.google.protobuf.Value.fromJavaScript(array[i]));\n"
+ " }\n"
+ "\n"
+ " return ret;\n"
+ "};\n"
+ "\n"
+ "\n"
+ "/**\n"
+ " * Converts this Struct object to a plain JavaScript object.\n"
+ " * @return {!Object<string, !proto.google.protobuf.JavaScriptValue>} a "
+ "plain\n"
+ " * JavaScript object representing this Struct.\n"
+ " */\n"
+ "proto.google.protobuf.Struct.prototype.toJavaScript = function() {\n"
+ " var ret = {};\n"
+ "\n"
+ " this.getFieldsMap().forEach(function(value, key) {\n"
+ " ret[key] = value.toJavaScript();\n"
+ " });\n"
+ "\n"
+ " return ret;\n"
+ "};\n"
+ "\n"
+ "\n"
+ "/**\n"
+ " * Constructs a Struct protobuf from this plain JavaScript object.\n"
+ " * @param {!Object} obj a plain JavaScript object\n"
+ " * @return {proto.google.protobuf.Struct} a new Struct object\n"
+ " */\n"
+ "proto.google.protobuf.Struct.fromJavaScript = function(obj) {\n"
+ " var ret = new proto.google.protobuf.Struct();\n"
+ " var map = ret.getFieldsMap();\n"
+ "\n"
+ " for (var property in obj) {\n"
+ " var val = obj[property];\n"
+ " map.set(property, proto.google.protobuf.Value.fromJavaScript(val));\n"
+ " }\n"
+ "\n"
+ " return ret;\n"
+ "};\n"},
+ {NULL, NULL} // Terminate the list.
+};
diff --git a/src/google/protobuf/compiler/main.cc b/src/google/protobuf/compiler/main.cc
index 680d6428..1db35441 100644
--- a/src/google/protobuf/compiler/main.cc
+++ b/src/google/protobuf/compiler/main.cc
@@ -40,7 +40,6 @@
#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
#include <google/protobuf/compiler/csharp/csharp_generator.h>
-#include <google/protobuf/compiler/javanano/javanano_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>
@@ -71,11 +70,6 @@ int main(int argc, char* argv[]) {
cli.RegisterGenerator("--python_out", &py_generator,
"Generate Python source file.");
- // Java Nano
- google::protobuf::compiler::javanano::JavaNanoGenerator javanano_generator;
- cli.RegisterGenerator("--javanano_out", &javanano_generator,
- "Generate Java Nano source file.");
-
// PHP
google::protobuf::compiler::php::Generator php_generator;
cli.RegisterGenerator("--php_out", &php_generator,
diff --git a/src/google/protobuf/compiler/mock_code_generator.cc b/src/google/protobuf/compiler/mock_code_generator.cc
index 7719ec3d..e150f97d 100644
--- a/src/google/protobuf/compiler/mock_code_generator.cc
+++ b/src/google/protobuf/compiler/mock_code_generator.cc
@@ -35,9 +35,6 @@
#include <stdlib.h>
#include <iostream>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
@@ -103,8 +100,7 @@ void MockCodeGenerator::ExpectGenerated(
File::GetContents(output_directory + "/" + GetOutputFileName(name, file),
&content, true));
- std::vector<string> lines =
- Split(content, "\n", true);
+ std::vector<string> lines = Split(content, "\n", true);
while (!lines.empty() && lines.back().empty()) {
lines.pop_back();
@@ -232,7 +228,7 @@ bool MockCodeGenerator::Generate(
for (size_t i = 0; i < insert_into.size(); i++) {
{
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->OpenForInsert(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(context->OpenForInsert(
GetOutputFileName(insert_into[i], file), kFirstInsertionPointName));
io::Printer printer(output.get(), '$');
printer.PrintRaw(GetOutputFileContent(name_, "first_insert",
@@ -244,7 +240,7 @@ bool MockCodeGenerator::Generate(
}
{
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
context->OpenForInsert(GetOutputFileName(insert_into[i], file),
kSecondInsertionPointName));
io::Printer printer(output.get(), '$');
@@ -257,7 +253,7 @@ bool MockCodeGenerator::Generate(
}
}
} else {
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
context->Open(GetOutputFileName(name_, file)));
GeneratedCodeInfo annotations;
@@ -287,7 +283,7 @@ bool MockCodeGenerator::Generate(
return false;
}
if (annotate) {
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> meta_output(
+ std::unique_ptr<io::ZeroCopyOutputStream> meta_output(
context->Open(GetOutputFileName(name_, file) + ".meta"));
if (!TextFormat::Print(annotations, meta_output.get())) {
*error = "MockCodeGenerator couldn't write .meta";
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_field.cc
index b6123fad..f74599ba 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_field.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_field.cc
@@ -410,10 +410,8 @@ bool RepeatedFieldGenerator::RuntimeUsesHasBit(void) const {
FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor,
const Options& options)
: descriptor_(descriptor),
- field_generators_(
- new scoped_ptr<FieldGenerator>[descriptor->field_count()]),
- extension_generators_(
- new scoped_ptr<FieldGenerator>[descriptor->extension_count()]) {
+ field_generators_(descriptor->field_count()),
+ extension_generators_(descriptor->extension_count()) {
// Construct all the FieldGenerators.
for (int i = 0; i < descriptor->field_count(); i++) {
field_generators_[i].reset(
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_field.h b/src/google/protobuf/compiler/objectivec/objectivec_field.h
index 6bd5db2e..216034d0 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_field.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_field.h
@@ -182,8 +182,8 @@ class FieldGeneratorMap {
private:
const Descriptor* descriptor_;
- scoped_array<scoped_ptr<FieldGenerator> > field_generators_;
- scoped_array<scoped_ptr<FieldGenerator> > extension_generators_;
+ std::vector<std::unique_ptr<FieldGenerator>> field_generators_;
+ std::vector<std::unique_ptr<FieldGenerator>> extension_generators_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
};
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_file.cc b/src/google/protobuf/compiler/objectivec/objectivec_file.cc
index 6f80a0de..f0d9b4d5 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_file.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_file.cc
@@ -188,6 +188,7 @@ bool IsDirectDependency(const FileDescriptor* dep, const FileDescriptor* file) {
FileGenerator::FileGenerator(const FileDescriptor *file, const Options& options)
: file_(file),
root_class_name_(FileClassName(file)),
+ is_bundled_proto_(IsProtobufLibraryBundledProtoFile(file)),
options_(options) {
for (int i = 0; i < file_->enum_type_count(); i++) {
EnumGenerator *generator = new EnumGenerator(file_->enum_type(i));
@@ -214,7 +215,17 @@ FileGenerator::~FileGenerator() {
}
void FileGenerator::GenerateHeader(io::Printer *printer) {
- PrintFileRuntimePreamble(printer, "GPBProtocolBuffers.h");
+ std::set<string> headers;
+ // Generated files bundled with the library get minimal imports, everything
+ // else gets the wrapper so everything is usable.
+ if (is_bundled_proto_) {
+ headers.insert("GPBRootObject.h");
+ headers.insert("GPBMessage.h");
+ headers.insert("GPBDescriptor.h");
+ } else {
+ headers.insert("GPBProtocolBuffers.h");
+ }
+ PrintFileRuntimePreamble(printer, headers);
// Add some verification that the generated code matches the source the
// code is being compiled with.
@@ -236,7 +247,8 @@ void FileGenerator::GenerateHeader(io::Printer *printer) {
{
ImportWriter import_writer(
options_.generate_for_named_framework,
- options_.named_framework_to_proto_path_mappings_path);
+ options_.named_framework_to_proto_path_mappings_path,
+ is_bundled_proto_);
const string header_extension(kHeaderExtension);
for (int i = 0; i < file_->public_dependency_count(); i++) {
import_writer.AddFile(file_->public_dependency(i), header_extension);
@@ -337,7 +349,9 @@ void FileGenerator::GenerateHeader(io::Printer *printer) {
void FileGenerator::GenerateSource(io::Printer *printer) {
// #import the runtime support.
- PrintFileRuntimePreamble(printer, "GPBProtocolBuffers_RuntimeSupport.h");
+ std::set<string> headers;
+ headers.insert("GPBProtocolBuffers_RuntimeSupport.h");
+ PrintFileRuntimePreamble(printer, headers);
// Enums use atomic in the generated code, so add the system import as needed.
if (FileContainsEnums(file_)) {
@@ -352,7 +366,8 @@ void FileGenerator::GenerateSource(io::Printer *printer) {
{
ImportWriter import_writer(
options_.generate_for_named_framework,
- options_.named_framework_to_proto_path_mappings_path);
+ options_.named_framework_to_proto_path_mappings_path,
+ is_bundled_proto_);
const string header_extension(kHeaderExtension);
// #import the header for this proto file.
@@ -566,7 +581,7 @@ void FileGenerator::GenerateSource(io::Printer *printer) {
// files. This currently only supports the runtime coming from a framework
// as defined by the official CocoaPod.
void FileGenerator::PrintFileRuntimePreamble(
- io::Printer* printer, const string& header_to_import) const {
+ io::Printer* printer, const std::set<string>& headers_to_import) const {
printer->Print(
"// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
"// source: $filename$\n"
@@ -575,6 +590,7 @@ void FileGenerator::PrintFileRuntimePreamble(
const string framework_name(ProtobufLibraryFrameworkName);
const string cpp_symbol(ProtobufFrameworkImportSymbol(framework_name));
+
printer->Print(
"// This CPP symbol can be defined to use imports that match up to the framework\n"
"// imports needed when using CocoaPods.\n"
@@ -582,15 +598,31 @@ void FileGenerator::PrintFileRuntimePreamble(
" #define $cpp_symbol$ 0\n"
"#endif\n"
"\n"
- "#if $cpp_symbol$\n"
- " #import <$framework_name$/$header$>\n"
- "#else\n"
- " #import \"$header$\"\n"
+ "#if $cpp_symbol$\n",
+ "cpp_symbol", cpp_symbol);
+
+
+ for (std::set<string>::const_iterator iter = headers_to_import.begin();
+ iter != headers_to_import.end(); ++iter) {
+ printer->Print(
+ " #import <$framework_name$/$header$>\n",
+ "header", *iter,
+ "framework_name", framework_name);
+ }
+
+ printer->Print(
+ "#else\n");
+
+ for (std::set<string>::const_iterator iter = headers_to_import.begin();
+ iter != headers_to_import.end(); ++iter) {
+ printer->Print(
+ " #import \"$header$\"\n",
+ "header", *iter);
+ }
+
+ printer->Print(
"#endif\n"
- "\n",
- "cpp_symbol", cpp_symbol,
- "header", header_to_import,
- "framework_name", framework_name);
+ "\n");
}
} // namespace objectivec
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_file.h b/src/google/protobuf/compiler/objectivec/objectivec_file.h
index 9c3f0071..1754fc0a 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_file.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_file.h
@@ -66,6 +66,7 @@ class FileGenerator {
private:
const FileDescriptor* file_;
string root_class_name_;
+ bool is_bundled_proto_;
std::vector<EnumGenerator*> enum_generators_;
std::vector<MessageGenerator*> message_generators_;
@@ -74,7 +75,7 @@ class FileGenerator {
const Options options_;
void PrintFileRuntimePreamble(
- io::Printer* printer, const string& header_to_import) const;
+ io::Printer* printer, const std::set<string>& headers_to_import) const;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator);
};
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_generator.cc b/src/google/protobuf/compiler/objectivec/objectivec_generator.cc
index 760ff481..e0597cc7 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_generator.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_generator.cc
@@ -142,7 +142,7 @@ bool ObjectiveCGenerator::GenerateAll(const std::vector<const FileDescriptor*>&
// Generate header.
{
- scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
context->Open(filepath + ".pbobjc.h"));
io::Printer printer(output.get(), '$');
file_generator.GenerateHeader(&printer);
@@ -150,7 +150,7 @@ bool ObjectiveCGenerator::GenerateAll(const std::vector<const FileDescriptor*>&
// Generate m file.
{
- scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
context->Open(filepath + ".pbobjc.m"));
io::Printer printer(output.get(), '$');
file_generator.GenerateSource(&printer);
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
index 5727dd56..df71c8bb 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
@@ -1504,10 +1504,12 @@ bool ParseSimpleFile(
ImportWriter::ImportWriter(
const string& generate_for_named_framework,
- const string& named_framework_to_proto_path_mappings_path)
+ const string& named_framework_to_proto_path_mappings_path,
+ bool include_wkt_imports)
: generate_for_named_framework_(generate_for_named_framework),
named_framework_to_proto_path_mappings_path_(
named_framework_to_proto_path_mappings_path),
+ include_wkt_imports_(include_wkt_imports),
need_to_parse_mapping_file_(true) {
}
@@ -1518,9 +1520,14 @@ void ImportWriter::AddFile(const FileDescriptor* file,
const string file_path(FilePath(file));
if (IsProtobufLibraryBundledProtoFile(file)) {
- protobuf_framework_imports_.push_back(
- FilePathBasename(file) + header_extension);
- protobuf_non_framework_imports_.push_back(file_path + header_extension);
+ // The imports of the WKTs are only needed within the library itself,
+ // in other cases, they get skipped because the generated code already
+ // import GPBProtocolBuffers.h and hence proves them.
+ if (include_wkt_imports_) {
+ protobuf_framework_imports_.push_back(
+ FilePathBasename(file) + header_extension);
+ protobuf_non_framework_imports_.push_back(file_path + header_extension);
+ }
return;
}
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
index f74607c8..8999aa59 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
@@ -253,7 +253,8 @@ bool LIBPROTOC_EXPORT ParseSimpleFile(
class LIBPROTOC_EXPORT ImportWriter {
public:
ImportWriter(const string& generate_for_named_framework,
- const string& named_framework_to_proto_path_mappings_path);
+ const string& named_framework_to_proto_path_mappings_path,
+ bool include_wkt_imports);
~ImportWriter();
void AddFile(const FileDescriptor* file, const string& header_extension);
@@ -275,6 +276,7 @@ class LIBPROTOC_EXPORT ImportWriter {
const string generate_for_named_framework_;
const string named_framework_to_proto_path_mappings_path_;
+ const bool include_wkt_imports_;
std::map<string, string> proto_file_to_framework_name_;
bool need_to_parse_mapping_file_;
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_map_field.h b/src/google/protobuf/compiler/objectivec/objectivec_map_field.h
index 6664d849..dc7beacf 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_map_field.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_map_field.h
@@ -54,7 +54,7 @@ class MapFieldGenerator : public RepeatedFieldGenerator {
virtual void DetermineForwardDeclarations(std::set<string>* fwd_decls) const;
private:
- scoped_ptr<FieldGenerator> value_field_generator_;
+ std::unique_ptr<FieldGenerator> value_field_generator_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator);
};
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_message.cc b/src/google/protobuf/compiler/objectivec/objectivec_message.cc
index f1465c3e..83888854 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_message.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_message.cc
@@ -310,7 +310,7 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) {
"classname", class_name_);
if (descriptor_->field_count()) {
- scoped_array<const FieldDescriptor*> sorted_fields(
+ std::unique_ptr<const FieldDescriptor*[]> sorted_fields(
SortFieldsByNumber(descriptor_));
printer->Print("typedef GPB_ENUM($classname$_FieldNumber) {\n",
@@ -420,9 +420,9 @@ void MessageGenerator::GenerateSource(io::Printer* printer) {
.GeneratePropertyImplementation(printer);
}
- scoped_array<const FieldDescriptor*> sorted_fields(
+ std::unique_ptr<const FieldDescriptor*[]> sorted_fields(
SortFieldsByNumber(descriptor_));
- scoped_array<const FieldDescriptor*> size_order_fields(
+ std::unique_ptr<const FieldDescriptor*[]> size_order_fields(
SortFieldsByStorageSize(descriptor_));
std::vector<const Descriptor::ExtensionRange*> sorted_extensions;
diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc
index 03d05ad4..5c7047a6 100644
--- a/src/google/protobuf/compiler/parser.cc
+++ b/src/google/protobuf/compiler/parser.cc
@@ -39,13 +39,14 @@
#include <limits>
+#include <google/protobuf/stubs/casts.h>
+#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/parser.h>
-#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/wire_format.h>
#include <google/protobuf/io/tokenizer.h>
-#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/map_util.h>
@@ -336,31 +337,42 @@ 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()) {
location_->add_span(parser_->input_->current().line);
location_->add_span(parser_->input_->current().column);
}
Parser::LocationRecorder::LocationRecorder(const LocationRecorder& parent) {
- Init(parent);
+ Init(parent, parent.source_code_info_);
+}
+
+Parser::LocationRecorder::LocationRecorder(const LocationRecorder& parent,
+ int path1,
+ SourceCodeInfo* source_code_info) {
+ Init(parent, source_code_info);
+ AddPath(path1);
}
Parser::LocationRecorder::LocationRecorder(const LocationRecorder& parent,
int path1) {
- Init(parent);
+ Init(parent, parent.source_code_info_);
AddPath(path1);
}
Parser::LocationRecorder::LocationRecorder(const LocationRecorder& parent,
int path1, int path2) {
- Init(parent);
+ Init(parent, parent.source_code_info_);
AddPath(path1);
AddPath(path2);
}
-void Parser::LocationRecorder::Init(const LocationRecorder& parent) {
+void Parser::LocationRecorder::Init(const LocationRecorder& parent,
+ SourceCodeInfo* source_code_info) {
parser_ = parent.parser_;
- location_ = parser_->source_code_info_->add_location();
+ source_code_info_ = source_code_info;
+
+ location_ = source_code_info_->add_location();
location_->mutable_path()->CopyFrom(parent.location_->path());
location_->add_span(parser_->input_->current().line);
@@ -402,6 +414,10 @@ void Parser::LocationRecorder::RecordLegacyLocation(const Message* descriptor,
}
}
+int Parser::LocationRecorder::CurrentPathSize() const {
+ return location_->path_size();
+}
+
void Parser::LocationRecorder::AttachComments(
string* leading, string* trailing,
std::vector<string>* detached_comments) const {
@@ -1495,21 +1511,30 @@ bool Parser::ParseExtensions(DescriptorProto* message,
range->set_end(end);
} while (TryConsume(","));
- if (LookingAt("[")) {
- LocationRecorder location(
- extensions_location,
- DescriptorProto::ExtensionRange::kOptionsFieldNumber);
- DO(Consume("["));
+ if (LookingAt("[")) {
+ int range_number_index = extensions_location.CurrentPathSize();
+ SourceCodeInfo info;
// Parse extension range options in the first range.
ExtensionRangeOptions* options =
message->mutable_extension_range(old_range_size)->mutable_options();
- do {
- DO(ParseOption(options, location, containing_file, OPTION_ASSIGNMENT));
- } while (TryConsume(","));
- DO(Consume("]"));
+ {
+ LocationRecorder index_location(
+ extensions_location, 0 /* we fill this in w/ actual index below */,
+ &info);
+ LocationRecorder location(
+ index_location,
+ DescriptorProto::ExtensionRange::kOptionsFieldNumber);
+ DO(Consume("["));
+
+ do {
+ DO(ParseOption(options, location, containing_file, OPTION_ASSIGNMENT));
+ } while (TryConsume(","));
+
+ DO(Consume("]"));
+ }
// Then copy the extension range options to all of the other ranges we've
// parsed.
@@ -1517,6 +1542,19 @@ bool Parser::ParseExtensions(DescriptorProto* message,
message->mutable_extension_range(i)->mutable_options()
->CopyFrom(*options);
}
+ // and copy source locations to the other ranges, too
+ 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
+ continue;
+ }
+ SourceCodeInfo_Location* dest = source_code_info_->add_location();
+ dest->CopyFrom(info.location(j));
+ dest->set_path(range_number_index, i);
+ }
+ }
}
DO(ConsumeEndOfDeclaration(";", &extensions_location));
@@ -1650,10 +1688,6 @@ bool Parser::ParseReservedNumbers(EnumDescriptorProto* message,
if (TryConsume("max")) {
// This is in the enum descriptor path, which doesn't have the message
// set duality to fix up, so it doesn't integrate with the sentinel.
-
- // Evaluate 'max' to INT_MAX - 1 so that incrementing to create the
- // exclusive range end doesn't cause an overflow.
- // Note, this prevents reserving the actual INT_MAX enum value.
end = INT_MAX;
} else {
DO(ConsumeSignedInteger(&end, "Expected integer."));
diff --git a/src/google/protobuf/compiler/parser.h b/src/google/protobuf/compiler/parser.h
index 33b4c700..5d98e5e1 100644
--- a/src/google/protobuf/compiler/parser.h
+++ b/src/google/protobuf/compiler/parser.h
@@ -40,10 +40,10 @@
#include <map>
#include <string>
#include <utility>
-#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/repeated_field.h>
#include <google/protobuf/io/tokenizer.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/repeated_field.h>
namespace google {
namespace protobuf { class Message; }
@@ -224,6 +224,10 @@ class LIBPROTOBUF_EXPORT Parser {
LocationRecorder(const LocationRecorder& parent, int path1);
LocationRecorder(const LocationRecorder& parent, int path1, int path2);
+ // Creates a recorder that generates locations into given source code info.
+ LocationRecorder(const LocationRecorder& parent, int path1,
+ SourceCodeInfo* source_code_info);
+
~LocationRecorder();
// Add a path component. See SourceCodeInfo.Location.path in
@@ -250,6 +254,9 @@ class LIBPROTOBUF_EXPORT Parser {
void RecordLegacyLocation(const Message* descriptor,
DescriptorPool::ErrorCollector::ErrorLocation location);
+ // Returns the number of path components in the recorder's current location.
+ int CurrentPathSize() const;
+
// Attaches leading and trailing comments to the location. The two strings
// will be swapped into place, so after this is called *leading and
// *trailing will be empty.
@@ -264,9 +271,10 @@ class LIBPROTOBUF_EXPORT Parser {
// SourceCodeInfo.location repeated field. For top-level elements,
// parent_index_ is -1.
Parser* parser_;
+ SourceCodeInfo* source_code_info_;
SourceCodeInfo::Location* location_;
- void Init(const LocationRecorder& parent);
+ void Init(const LocationRecorder& parent, SourceCodeInfo* source_code_info);
};
// =================================================================
diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc
index 9b59842e..0725a682 100644
--- a/src/google/protobuf/compiler/parser_unittest.cc
+++ b/src/google/protobuf/compiler/parser_unittest.cc
@@ -33,9 +33,6 @@
// Sanjay Ghemawat, Jeff Dean, and others.
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
#include <algorithm>
#include <map>
@@ -50,6 +47,7 @@
#include <google/protobuf/text_format.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/substitute.h>
+
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/testing/googletest.h>
@@ -177,9 +175,9 @@ class ParserTest : public testing::Test {
MockErrorCollector error_collector_;
DescriptorPool pool_;
- google::protobuf::scoped_ptr<io::ZeroCopyInputStream> raw_input_;
- google::protobuf::scoped_ptr<io::Tokenizer> input_;
- google::protobuf::scoped_ptr<Parser> parser_;
+ std::unique_ptr<io::ZeroCopyInputStream> raw_input_;
+ std::unique_ptr<io::Tokenizer> input_;
+ std::unique_ptr<Parser> parser_;
bool require_syntax_identifier_;
};
diff --git a/src/google/protobuf/compiler/php/php_generator.cc b/src/google/protobuf/compiler/php/php_generator.cc
index eefdb196..a58e1754 100644
--- a/src/google/protobuf/compiler/php/php_generator.cc
+++ b/src/google/protobuf/compiler/php/php_generator.cc
@@ -40,8 +40,6 @@
#include <sstream>
-using google::protobuf::internal::scoped_ptr;
-
const std::string kDescriptorFile = "google/protobuf/descriptor.proto";
const std::string kEmptyFile = "google/protobuf/empty.proto";
const std::string kEmptyMetadataFile = "GPBMetadata/Google/Protobuf/GPBEmpty.php";
@@ -85,7 +83,7 @@ std::string PhpName(const std::string& full_name, bool is_descriptor);
std::string DefaultForField(FieldDescriptor* field);
std::string IntToString(int32 value);
std::string FilenameToClassname(const string& filename);
-std::string GeneratedMetadataFileName(const std::string& proto_file,
+std::string GeneratedMetadataFileName(const FileDescriptor* file,
bool is_descriptor);
std::string LabelForField(FieldDescriptor* field);
std::string TypeName(FieldDescriptor* field);
@@ -96,6 +94,9 @@ void Indent(io::Printer* printer);
void Outdent(io::Printer* printer);
void GenerateMessageDocComment(io::Printer* printer, const Descriptor* message,
int is_descriptor);
+void GenerateMessageConstructorDocComment(io::Printer* printer,
+ const Descriptor* message,
+ int is_descriptor);
void GenerateFieldDocComment(io::Printer* printer, const FieldDescriptor* field,
int is_descriptor, int function_type);
void GenerateEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_,
@@ -107,31 +108,40 @@ void GenerateServiceDocComment(io::Printer* printer,
void GenerateServiceMethodDocComment(io::Printer* printer,
const MethodDescriptor* method);
-std::string RenameEmpty(const std::string& name) {
- if (name == "Empty") {
- return "GPBEmpty";
- } else {
- return name;
+
+std::string ReservedNamePrefix(const string& classname,
+ const FileDescriptor* file) {
+ bool is_reserved = false;
+
+ string lower = classname;
+ transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
+
+ for (int i = 0; i < kReservedNamesSize; i++) {
+ if (lower == kReservedNames[i]) {
+ is_reserved = true;
+ break;
+ }
}
-}
-std::string MessageFullName(const Descriptor* message, bool is_descriptor) {
- if (is_descriptor) {
- return StringReplace(message->full_name(),
- "google.protobuf",
- "google.protobuf.internal", false);
- } else {
- return message->full_name();
+ if (is_reserved) {
+ if (file->package() == "google.protobuf") {
+ return "GPB";
+ } else {
+ return "PB";
+ }
}
+
+ return "";
}
-std::string EnumFullName(const EnumDescriptor* envm, bool is_descriptor) {
+template <typename DescriptorType>
+std::string DescriptorFullName(const DescriptorType* desc, bool is_descriptor) {
if (is_descriptor) {
- return StringReplace(envm->full_name(),
+ return StringReplace(desc->full_name(),
"google.protobuf",
"google.protobuf.internal", false);
} else {
- return envm->full_name();
+ return desc->full_name();
}
}
@@ -143,22 +153,55 @@ std::string ClassNamePrefix(const string& classname,
return prefix;
}
- bool is_reserved = false;
+ return ReservedNamePrefix(classname, desc->file());
+}
+
+template <typename DescriptorType>
+std::string GeneratedClassNameImpl(const DescriptorType* desc) {
+ std::string classname = ClassNamePrefix(desc->name(), desc) + desc->name();
+ const Descriptor* containing = desc->containing_type();
+ while (containing != NULL) {
+ classname = ClassNamePrefix(containing->name(), desc) + containing->name()
+ + '\\' + classname;
+ containing = containing->containing_type();
+ }
+ return classname;
+}
+
+std::string GeneratedClassNameImpl(const ServiceDescriptor* desc) {
+ std::string classname = desc->name();
+ return ClassNamePrefix(classname, desc) + classname;
+}
+
+std::string GeneratedClassName(const Descriptor* desc) {
+ return GeneratedClassNameImpl(desc);
+}
+
+std::string GeneratedClassName(const EnumDescriptor* desc) {
+ return GeneratedClassNameImpl(desc);
+}
+
+std::string GeneratedClassName(const ServiceDescriptor* desc) {
+ return GeneratedClassNameImpl(desc);
+}
+template <typename DescriptorType>
+std::string LegacyGeneratedClassName(const DescriptorType* desc) {
+ std::string classname = desc->name();
+ const Descriptor* containing = desc->containing_type();
+ while (containing != NULL) {
+ classname = containing->name() + '_' + classname;
+ containing = containing->containing_type();
+ }
+ return ClassNamePrefix(classname, desc) + classname;
+}
+
+std::string ClassNamePrefix(const string& classname) {
string lower = classname;
transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
for (int i = 0; i < kReservedNamesSize; i++) {
if (lower == kReservedNames[i]) {
- is_reserved = true;
- break;
- }
- }
-
- if (is_reserved) {
- if (desc->file()->package() == "google.protobuf") {
- return "GPB";
- } else {
return "PB";
}
}
@@ -194,34 +237,39 @@ std::string ConstantNamePrefix(const string& classname) {
}
template <typename DescriptorType>
-std::string NamespacedName(const string& classname,
- const DescriptorType* desc, bool is_descriptor) {
+std::string RootPhpNamespace(const DescriptorType* desc, bool is_descriptor) {
if (desc->file()->options().has_php_namespace()) {
const string& php_namespace = desc->file()->options().php_namespace();
if (php_namespace != "") {
- return php_namespace + '\\' + classname;
- } else {
- return classname;
+ return php_namespace;
}
+ return "";
}
- if (desc->file()->package() == "") {
- return classname;
- } else {
- return PhpName(desc->file()->package(), is_descriptor) + '\\' +
- classname;
+ if (desc->file()->package() != "") {
+ return PhpName(desc->file()->package(), is_descriptor);
}
+ return "";
}
template <typename DescriptorType>
std::string FullClassName(const DescriptorType* desc, bool is_descriptor) {
- string classname = GeneratedClassName(desc);
- return NamespacedName(classname, desc, is_descriptor);
+ string classname = GeneratedClassNameImpl(desc);
+ string php_namespace = RootPhpNamespace(desc, is_descriptor);
+ if (php_namespace != "") {
+ return php_namespace + "\\" + classname;
+ }
+ return classname;
}
-std::string FullClassName(const ServiceDescriptor* desc, bool is_descriptor) {
- string classname = GeneratedClassName(desc);
- return NamespacedName(classname, desc, is_descriptor);
+template <typename DescriptorType>
+std::string LegacyFullClassName(const DescriptorType* desc, bool is_descriptor) {
+ string classname = LegacyGeneratedClassName(desc);
+ string php_namespace = RootPhpNamespace(desc, is_descriptor);
+ if (php_namespace != "") {
+ return php_namespace + "\\" + classname;
+ }
+ return classname;
}
std::string PhpName(const std::string& full_name, bool is_descriptor) {
@@ -229,20 +277,23 @@ std::string PhpName(const std::string& full_name, bool is_descriptor) {
return kDescriptorPackageName;
}
+ std::string segment;
std::string result;
bool cap_next_letter = true;
for (int i = 0; i < full_name.size(); i++) {
if ('a' <= full_name[i] && full_name[i] <= 'z' && cap_next_letter) {
- result += full_name[i] + ('A' - 'a');
+ segment += full_name[i] + ('A' - 'a');
cap_next_letter = false;
} else if (full_name[i] == '.') {
- result += '\\';
+ result += ClassNamePrefix(segment) + segment + '\\';
+ segment = "";
cap_next_letter = true;
} else {
- result += full_name[i];
+ segment += full_name[i];
cap_next_letter = false;
}
}
+ result += ClassNamePrefix(segment) + segment;
return result;
}
@@ -270,11 +321,13 @@ std::string DefaultForField(const FieldDescriptor* field) {
}
}
-std::string GeneratedMetadataFileName(const std::string& proto_file,
+std::string GeneratedMetadataFileName(const FileDescriptor* file,
bool is_descriptor) {
+ const string& proto_file = file->name();
int start_index = 0;
int first_index = proto_file.find_first_of("/", start_index);
- std::string result = "GPBMetadata/";
+ std::string result = "";
+ std::string segment = "";
if (proto_file == kEmptyFile) {
return kEmptyMetadataFile;
@@ -292,24 +345,44 @@ std::string GeneratedMetadataFileName(const std::string& proto_file,
file_no_suffix = proto_file.substr(0, lastindex);
}
- while (first_index != string::npos) {
- result += UnderscoresToCamelCase(
- file_no_suffix.substr(start_index, first_index - start_index), true);
- result += "/";
- start_index = first_index + 1;
- first_index = file_no_suffix.find_first_of("/", start_index);
+ if (file->options().has_php_metadata_namespace()) {
+ const string& php_metadata_namespace =
+ file->options().php_metadata_namespace();
+ if (php_metadata_namespace != "" && php_metadata_namespace != "\\") {
+ result += php_metadata_namespace;
+ std::replace(result.begin(), result.end(), '\\', '/');
+ if (result.at(result.size() - 1) != '/') {
+ result += "/";
+ }
+ }
+ } else {
+ result += "GPBMetadata/";
+ while (first_index != string::npos) {
+ segment = UnderscoresToCamelCase(
+ file_no_suffix.substr(start_index, first_index - start_index), true);
+ result += ReservedNamePrefix(segment, file) + segment + "/";
+ start_index = first_index + 1;
+ first_index = file_no_suffix.find_first_of("/", start_index);
+ }
}
// Append file name.
- result += RenameEmpty(UnderscoresToCamelCase(
- file_no_suffix.substr(start_index, first_index - start_index), true));
+ int file_name_start = file_no_suffix.find_last_of("/");
+ if (file_name_start == string::npos) {
+ file_name_start = 0;
+ } else {
+ file_name_start += 1;
+ }
+ segment = UnderscoresToCamelCase(
+ file_no_suffix.substr(file_name_start, first_index - file_name_start), true);
- return result += ".php";
+ return result + ReservedNamePrefix(segment, file) + segment + ".php";
}
-std::string GeneratedMessageFileName(const Descriptor* message,
+template <typename DescriptorType>
+std::string GeneratedClassFileName(const DescriptorType* desc,
bool is_descriptor) {
- std::string result = FullClassName(message, is_descriptor);
+ std::string result = FullClassName(desc, is_descriptor);
for (int i = 0; i < result.size(); i++) {
if (result[i] == '\\') {
result[i] = '/';
@@ -318,9 +391,11 @@ std::string GeneratedMessageFileName(const Descriptor* message,
return result + ".php";
}
-std::string GeneratedEnumFileName(const EnumDescriptor* en,
- bool is_descriptor) {
- std::string result = FullClassName(en, is_descriptor);
+template <typename DescriptorType>
+std::string LegacyGeneratedClassFileName(const DescriptorType* desc,
+ bool is_descriptor) {
+ std::string result = LegacyFullClassName(desc, is_descriptor);
+
for (int i = 0; i < result.size(); i++) {
if (result[i] == '\\') {
result[i] = '/';
@@ -463,10 +538,10 @@ std::string PhpGetterTypeName(const FieldDescriptor* field, bool is_descriptor)
std::string EnumOrMessageSuffix(
const FieldDescriptor* field, bool is_descriptor) {
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- return ", '" + MessageFullName(field->message_type(), is_descriptor) + "'";
+ return ", '" + DescriptorFullName(field->message_type(), is_descriptor) + "'";
}
if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
- return ", '" + EnumFullName(field->enum_type(), is_descriptor) + "'";
+ return ", '" + DescriptorFullName(field->enum_type(), is_descriptor) + "'";
}
return "";
}
@@ -653,11 +728,11 @@ void GenerateFieldAccessor(const FieldDescriptor* field, bool is_descriptor,
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
printer->Print(
"GPBUtil::checkMessage($var, \\^class_name^::class);\n",
- "class_name", FullClassName(field->message_type(), is_descriptor));
+ "class_name", LegacyFullClassName(field->message_type(), is_descriptor));
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
printer->Print(
"GPBUtil::checkEnum($var, \\^class_name^::class);\n",
- "class_name", FullClassName(field->enum_type(), is_descriptor));
+ "class_name", LegacyFullClassName(field->enum_type(), is_descriptor));
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
printer->Print(
"GPBUtil::checkString($var, ^utf8^);\n",
@@ -713,7 +788,7 @@ void GenerateEnumToPool(const EnumDescriptor* en, io::Printer* printer) {
printer->Print(
"$pool->addEnum('^name^', "
"\\Google\\Protobuf\\Internal\\^class_name^::class)\n",
- "name", EnumFullName(en, true),
+ "name", DescriptorFullName(en, true),
"class_name", en->name());
Indent(printer);
@@ -745,13 +820,13 @@ void GenerateMessageToPool(const string& name_prefix, const Descriptor* message,
if (message->options().map_entry()) {
return;
}
- string class_name = name_prefix.empty()?
- message->name() : name_prefix + "_" + message->name();
+ string class_name = (name_prefix.empty() ? "" : name_prefix + "\\") +
+ ReservedNamePrefix(message->name(), message->file()) + message->name();
printer->Print(
"$pool->addMessage('^message^', "
"\\Google\\Protobuf\\Internal\\^class_name^::class)\n",
- "message", MessageFullName(message, true),
+ "message", DescriptorFullName(message, true),
"class_name", class_name);
Indent(printer);
@@ -853,7 +928,7 @@ void GenerateAddFileToPool(const FileDescriptor* file, bool is_descriptor,
continue;
}
std::string dependency_filename =
- GeneratedMetadataFileName(name, is_descriptor);
+ GeneratedMetadataFileName(file->dependency(i), is_descriptor);
printer->Print(
"\\^name^::initOnce();\n",
"name", FilenameToClassname(dependency_filename));
@@ -947,8 +1022,8 @@ std::string FilenameToClassname(const string& filename) {
void GenerateMetadataFile(const FileDescriptor* file,
bool is_descriptor,
GeneratorContext* generator_context) {
- std::string filename = GeneratedMetadataFileName(file->name(), is_descriptor);
- scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::string filename = GeneratedMetadataFileName(file, is_descriptor);
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(filename));
io::Printer printer(output.get(), '^');
@@ -957,12 +1032,12 @@ void GenerateMetadataFile(const FileDescriptor* file,
std::string fullname = FilenameToClassname(filename);
int lastindex = fullname.find_last_of("\\");
- printer.Print(
- "namespace ^name^;\n\n",
- "name", fullname.substr(0, lastindex));
-
if (lastindex != string::npos) {
printer.Print(
+ "namespace ^name^;\n\n",
+ "name", fullname.substr(0, lastindex));
+
+ printer.Print(
"class ^name^\n"
"{\n",
"name", fullname.substr(lastindex + 1));
@@ -980,10 +1055,48 @@ void GenerateMetadataFile(const FileDescriptor* file,
printer.Print("}\n\n");
}
+template <typename DescriptorType>
+void LegacyGenerateClassFile(const FileDescriptor* file, const DescriptorType* desc,
+ bool is_descriptor,
+ GeneratorContext* generator_context) {
+
+ std::string filename = LegacyGeneratedClassFileName(desc, is_descriptor);
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
+ generator_context->Open(filename));
+ io::Printer printer(output.get(), '^');
+
+ GenerateHead(file, &printer);
+
+ std::string php_namespace = RootPhpNamespace(desc, is_descriptor);
+ if (php_namespace != "") {
+ printer.Print(
+ "namespace ^name^;\n\n",
+ "name", php_namespace);
+ }
+ std::string newname = FullClassName(desc, is_descriptor);
+ printer.Print("if (false) {\n");
+ Indent(&printer);
+ printer.Print("/**\n");
+ printer.Print(" * This class is deprecated. Use ^new^ instead.\n",
+ "new", newname);
+ printer.Print(" * @deprecated\n");
+ printer.Print(" */\n");
+ printer.Print("class ^old^ {}\n",
+ "old", LegacyGeneratedClassName(desc));
+ Outdent(&printer);
+ printer.Print("}\n");
+ printer.Print("class_exists(^new^::class);\n",
+ "new", GeneratedClassNameImpl(desc));
+ printer.Print("@trigger_error('^old^ is deprecated and will be removed in "
+ "the next major release. Use ^fullname^ instead', E_USER_DEPRECATED);\n\n",
+ "old", LegacyFullClassName(desc, is_descriptor),
+ "fullname", newname);
+}
+
void GenerateEnumFile(const FileDescriptor* file, const EnumDescriptor* en,
bool is_descriptor, GeneratorContext* generator_context) {
- std::string filename = GeneratedEnumFileName(en, is_descriptor);
- scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::string filename = GeneratedClassFileName(en, is_descriptor);
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(filename));
io::Printer printer(output.get(), '^');
@@ -992,32 +1105,22 @@ void GenerateEnumFile(const FileDescriptor* file, const EnumDescriptor* en,
std::string fullname = FilenameToClassname(filename);
int lastindex = fullname.find_last_of("\\");
- if (file->options().has_php_namespace()) {
- const string& php_namespace = file->options().php_namespace();
- if (!php_namespace.empty()) {
- printer.Print(
- "namespace ^name^;\n\n",
- "name", php_namespace);
- }
- } else if (!file->package().empty()) {
+ if (lastindex != string::npos) {
printer.Print(
"namespace ^name^;\n\n",
"name", fullname.substr(0, lastindex));
}
- GenerateEnumDocComment(&printer, en, is_descriptor);
-
if (lastindex != string::npos) {
- printer.Print(
- "class ^name^\n"
- "{\n",
- "name", fullname.substr(lastindex + 1));
- } else {
- printer.Print(
- "class ^name^\n"
- "{\n",
- "name", fullname);
+ fullname = fullname.substr(lastindex + 1);
}
+
+ GenerateEnumDocComment(&printer, en, is_descriptor);
+
+ printer.Print(
+ "class ^name^\n"
+ "{\n",
+ "name", fullname);
Indent(&printer);
for (int i = 0; i < en->value_count(); i++) {
@@ -1030,6 +1133,17 @@ void GenerateEnumFile(const FileDescriptor* file, const EnumDescriptor* en,
Outdent(&printer);
printer.Print("}\n\n");
+
+ // write legacy file for backwards compatiblity with nested messages and enums
+ if (en->containing_type() != NULL) {
+ printer.Print(
+ "// Adding a class alias for backwards compatibility with the previous class name.\n");
+ printer.Print(
+ "class_alias(^new^::class, \\^old^::class);\n\n",
+ "new", fullname,
+ "old", LegacyFullClassName(en, is_descriptor));
+ LegacyGenerateClassFile(file, en, is_descriptor, generator_context);
+ }
}
void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message,
@@ -1041,8 +1155,8 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message,
return;
}
- std::string filename = GeneratedMessageFileName(message, is_descriptor);
- scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::string filename = GeneratedClassFileName(message, is_descriptor);
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(filename));
io::Printer printer(output.get(), '^');
@@ -1051,14 +1165,7 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message,
std::string fullname = FilenameToClassname(filename);
int lastindex = fullname.find_last_of("\\");
- if (file->options().has_php_namespace()) {
- const string& php_namespace = file->options().php_namespace();
- if (!php_namespace.empty()) {
- printer.Print(
- "namespace ^name^;\n\n",
- "name", php_namespace);
- }
- } else if (!file->package().empty()) {
+ if (lastindex != string::npos) {
printer.Print(
"namespace ^name^;\n\n",
"name", fullname.substr(0, lastindex));
@@ -1068,16 +1175,13 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message,
GenerateMessageDocComment(&printer, message, is_descriptor);
if (lastindex != string::npos) {
- printer.Print(
- "class ^name^ extends \\Google\\Protobuf\\Internal\\Message\n"
- "{\n",
- "name", fullname.substr(lastindex + 1));
- } else {
- printer.Print(
- "class ^name^ extends \\Google\\Protobuf\\Internal\\Message\n"
- "{\n",
- "name", fullname);
+ fullname = fullname.substr(lastindex + 1);
}
+
+ printer.Print(
+ "class ^name^ extends \\Google\\Protobuf\\Internal\\Message\n"
+ "{\n",
+ "name", fullname);
Indent(&printer);
// Field and oneof definitions.
@@ -1091,16 +1195,17 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message,
}
printer.Print("\n");
+ GenerateMessageConstructorDocComment(&printer, message, is_descriptor);
printer.Print(
- "public function __construct() {\n");
+ "public function __construct($data = NULL) {\n");
Indent(&printer);
std::string metadata_filename =
- GeneratedMetadataFileName(file->name(), is_descriptor);
+ GeneratedMetadataFileName(file, is_descriptor);
std::string metadata_fullname = FilenameToClassname(metadata_filename);
printer.Print(
"\\^fullname^::initOnce();\n"
- "parent::__construct();\n",
+ "parent::__construct($data);\n",
"fullname", metadata_fullname);
Outdent(&printer);
@@ -1128,6 +1233,17 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message,
Outdent(&printer);
printer.Print("}\n\n");
+ // write legacy file for backwards compatiblity with nested messages and enums
+ if (message->containing_type() != NULL) {
+ printer.Print(
+ "// Adding a class alias for backwards compatibility with the previous class name.\n");
+ printer.Print(
+ "class_alias(^new^::class, \\^old^::class);\n\n",
+ "new", fullname,
+ "old", LegacyFullClassName(message, is_descriptor));
+ LegacyGenerateClassFile(file, message, is_descriptor, generator_context);
+ }
+
// Nested messages and enums.
for (int i = 0; i < message->nested_type_count(); i++) {
GenerateMessageFile(file, message->nested_type(i), is_descriptor,
@@ -1143,7 +1259,7 @@ void GenerateServiceFile(const FileDescriptor* file,
const ServiceDescriptor* service, bool is_descriptor,
GeneratorContext* generator_context) {
std::string filename = GeneratedServiceFileName(service, is_descriptor);
- scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(filename));
io::Printer printer(output.get(), '^');
@@ -1152,14 +1268,9 @@ void GenerateServiceFile(const FileDescriptor* file,
std::string fullname = FilenameToClassname(filename);
int lastindex = fullname.find_last_of("\\");
- if (file->options().has_php_namespace()) {
- const string& php_namespace = file->options().php_namespace();
- if (!php_namespace.empty()) {
- printer.Print(
- "namespace ^name^;\n\n",
- "name", php_namespace);
- }
- } else if (!file->package().empty()) {
+ if (!file->options().php_namespace().empty() ||
+ (!file->options().has_php_namespace() && !file->package().empty()) ||
+ lastindex != string::npos) {
printer.Print(
"namespace ^name^;\n\n",
"name", fullname.substr(0, lastindex));
@@ -1253,7 +1364,8 @@ static string EscapePhpdoc(const string& input) {
}
static void GenerateDocCommentBodyForLocation(
- io::Printer* printer, const SourceLocation& location) {
+ io::Printer* printer, const SourceLocation& location, bool trailingNewline,
+ int indentCount) {
string comments = location.leading_comments.empty() ?
location.trailing_comments : location.leading_comments;
if (!comments.empty()) {
@@ -1274,14 +1386,16 @@ static void GenerateDocCommentBodyForLocation(
// Most lines should start with a space. Watch out for lines that start
// with a /, since putting that right after the leading asterisk will
// close the comment.
- if (!lines[i].empty() && lines[i][0] == '/') {
+ if (indentCount == 0 && !lines[i].empty() && lines[i][0] == '/') {
printer->Print(" * ^line^\n", "line", lines[i]);
} else {
- printer->Print(" *^line^\n", "line", lines[i]);
+ std::string indent = std::string(indentCount, ' ');
+ printer->Print(" *^ind^^line^\n", "ind", indent, "line", lines[i]);
}
}
- printer->Print(
- " *\n");
+ if (trailingNewline) {
+ printer->Print(" *\n");
+ }
}
}
@@ -1290,7 +1404,7 @@ static void GenerateDocCommentBody(
io::Printer* printer, const DescriptorType* descriptor) {
SourceLocation location;
if (descriptor->GetSourceLocation(&location)) {
- GenerateDocCommentBodyForLocation(printer, location);
+ GenerateDocCommentBodyForLocation(printer, location, true, 0);
}
}
@@ -1312,10 +1426,41 @@ void GenerateMessageDocComment(io::Printer* printer,
printer->Print(
" * Generated from protobuf message <code>^messagename^</code>\n"
" */\n",
- "fullname", EscapePhpdoc(PhpName(message->full_name(), is_descriptor)),
+ "fullname", EscapePhpdoc(FullClassName(message, is_descriptor)),
"messagename", EscapePhpdoc(message->full_name()));
}
+void GenerateMessageConstructorDocComment(io::Printer* printer,
+ const Descriptor* message,
+ int is_descriptor) {
+ // In theory we should have slightly different comments for setters, getters,
+ // etc., but in practice everyone already knows the difference between these
+ // so it's redundant information.
+
+ // We start the comment with the main body based on the comments from the
+ // .proto file (if present). We then end with the field declaration, e.g.:
+ // optional string foo = 5;
+ // If the field is a group, the debug string might end with {.
+ printer->Print("/**\n");
+ printer->Print(" * Constructor.\n");
+ printer->Print(" *\n");
+ printer->Print(" * @param array $data {\n");
+ printer->Print(" * Optional. Data for populating the Message object.\n");
+ printer->Print(" *\n");
+ for (int i = 0; i < message->field_count(); i++) {
+ const FieldDescriptor* field = message->field(i);
+ printer->Print(" * @type ^php_type^ $^var^\n",
+ "php_type", PhpSetterTypeName(field, is_descriptor),
+ "var", field->name());
+ SourceLocation location;
+ if (field->GetSourceLocation(&location)) {
+ GenerateDocCommentBodyForLocation(printer, location, false, 10);
+ }
+ }
+ printer->Print(" * }\n");
+ printer->Print(" */\n");
+}
+
void GenerateServiceDocComment(io::Printer* printer,
const ServiceDescriptor* service) {
printer->Print("/**\n");
@@ -1357,9 +1502,9 @@ void GenerateEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_,
printer->Print("/**\n");
GenerateDocCommentBody(printer, enum_);
printer->Print(
- " * Protobuf enum <code>^fullname^</code>\n"
+ " * Protobuf type <code>^fullname^</code>\n"
" */\n",
- "fullname", EscapePhpdoc(PhpName(enum_->full_name(), is_descriptor)));
+ "fullname", EscapePhpdoc(enum_->full_name()));
}
void GenerateEnumValueDocComment(io::Printer* printer,
@@ -1412,31 +1557,6 @@ bool Generator::Generate(const FileDescriptor* file, const string& parameter,
return true;
}
-std::string GeneratedClassName(const Descriptor* desc) {
- std::string classname = desc->name();
- const Descriptor* containing = desc->containing_type();
- while (containing != NULL) {
- classname = containing->name() + '_' + classname;
- containing = containing->containing_type();
- }
- return ClassNamePrefix(classname, desc) + classname;
-}
-
-std::string GeneratedClassName(const EnumDescriptor* desc) {
- std::string classname = desc->name();
- const Descriptor* containing = desc->containing_type();
- while (containing != NULL) {
- classname = containing->name() + '_' + classname;
- containing = containing->containing_type();
- }
- return ClassNamePrefix(classname, desc) + classname;
-}
-
-std::string GeneratedClassName(const ServiceDescriptor* desc) {
- std::string classname = desc->name();
- return ClassNamePrefix(classname, desc) + classname;
-}
-
} // namespace php
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/php/php_generator.h b/src/google/protobuf/compiler/php/php_generator.h
index 67e70bc7..b851d9b4 100644
--- a/src/google/protobuf/compiler/php/php_generator.h
+++ b/src/google/protobuf/compiler/php/php_generator.h
@@ -48,15 +48,17 @@ class LIBPROTOC_EXPORT Generator
const string& parameter,
GeneratorContext* generator_context,
string* error) const;
-
};
// To skip reserved keywords in php, some generated classname are prefixed.
// Other code generators may need following API to figure out the actual
// classname.
-std::string GeneratedClassName(const google::protobuf::Descriptor* desc);
-std::string GeneratedClassName(const google::protobuf::EnumDescriptor* desc);
-std::string GeneratedClassName(const google::protobuf::ServiceDescriptor* desc);
+LIBPROTOC_EXPORT std::string GeneratedClassName(
+ const google::protobuf::Descriptor* desc);
+LIBPROTOC_EXPORT std::string GeneratedClassName(
+ const google::protobuf::EnumDescriptor* desc);
+LIBPROTOC_EXPORT std::string GeneratedClassName(
+ const google::protobuf::ServiceDescriptor* desc);
} // namespace php
} // namespace compiler
diff --git a/src/google/protobuf/compiler/plugin.cc b/src/google/protobuf/compiler/plugin.cc
index bde3d798..9c1c757c 100644
--- a/src/google/protobuf/compiler/plugin.cc
+++ b/src/google/protobuf/compiler/plugin.cc
@@ -45,8 +45,8 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/plugin.pb.h>
#include <google/protobuf/compiler/code_generator.h>
-#include <google/protobuf/descriptor.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
+#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/io_win32.h>
diff --git a/src/google/protobuf/compiler/plugin.pb.cc b/src/google/protobuf/compiler/plugin.pb.cc
index d13ad2b3..20aa82c7 100644
--- a/src/google/protobuf/compiler/plugin.pb.cc
+++ b/src/google/protobuf/compiler/plugin.pb.cc
@@ -7,7 +7,6 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
@@ -19,6 +18,14 @@
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
+
+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
namespace google {
namespace protobuf {
namespace compiler {
@@ -46,14 +53,9 @@ class CodeGeneratorResponseDefaultTypeInternal {
} // namespace protobuf
} // namespace google
namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto {
-void InitDefaultsVersionImpl() {
+static void InitDefaultsVersion() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::compiler::_Version_default_instance_;
new (ptr) ::google::protobuf::compiler::Version();
@@ -62,21 +64,12 @@ void InitDefaultsVersionImpl() {
::google::protobuf::compiler::Version::InitAsDefaultInstance();
}
-void InitDefaultsVersion() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsVersionImpl);
-}
+LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Version =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsVersion}, {}};
-void InitDefaultsCodeGeneratorRequestImpl() {
+static void InitDefaultsCodeGeneratorRequest() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto();
- protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersion();
{
void* ptr = &::google::protobuf::compiler::_CodeGeneratorRequest_default_instance_;
new (ptr) ::google::protobuf::compiler::CodeGeneratorRequest();
@@ -85,19 +78,14 @@ void InitDefaultsCodeGeneratorRequestImpl() {
::google::protobuf::compiler::CodeGeneratorRequest::InitAsDefaultInstance();
}
-void InitDefaultsCodeGeneratorRequest() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsCodeGeneratorRequestImpl);
-}
+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,}};
-void InitDefaultsCodeGeneratorResponse_FileImpl() {
+static void InitDefaultsCodeGeneratorResponse_File() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::compiler::_CodeGeneratorResponse_File_default_instance_;
new (ptr) ::google::protobuf::compiler::CodeGeneratorResponse_File();
@@ -106,20 +94,12 @@ void InitDefaultsCodeGeneratorResponse_FileImpl() {
::google::protobuf::compiler::CodeGeneratorResponse_File::InitAsDefaultInstance();
}
-void InitDefaultsCodeGeneratorResponse_File() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsCodeGeneratorResponse_FileImpl);
-}
+LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCodeGeneratorResponse_File}, {}};
-void InitDefaultsCodeGeneratorResponseImpl() {
+static void InitDefaultsCodeGeneratorResponse() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_File();
{
void* ptr = &::google::protobuf::compiler::_CodeGeneratorResponse_default_instance_;
new (ptr) ::google::protobuf::compiler::CodeGeneratorResponse();
@@ -128,9 +108,15 @@ void InitDefaultsCodeGeneratorResponseImpl() {
::google::protobuf::compiler::CodeGeneratorResponse::InitAsDefaultInstance();
}
-void InitDefaultsCodeGeneratorResponse() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsCodeGeneratorResponseImpl);
+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,}};
+
+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);
}
::google::protobuf::Metadata file_level_metadata[4];
@@ -197,17 +183,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::compiler::_CodeGeneratorResponse_default_instance_),
};
-void protobuf_AssignDescriptors() {
+static void protobuf_AssignDescriptors() {
AddDescriptors();
- ::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/compiler/plugin.proto", schemas, file_default_instances, TableStruct::offsets, factory,
+ "google/protobuf/compiler/plugin.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
-void protobuf_AssignDescriptorsOnce() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
+static 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;
@@ -216,7 +201,7 @@ void protobuf_RegisterTypes(const ::std::string&) {
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 4);
}
-void AddDescriptorsImpl() {
+static void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n%google/protobuf/compiler/plugin.proto\022"
@@ -244,8 +229,8 @@ void AddDescriptorsImpl() {
}
void AddDescriptors() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
+ 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 {
@@ -271,17 +256,15 @@ const int Version::kSuffixFieldNumber;
Version::Version()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersion();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.compiler.Version)
}
Version::Version(const Version& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- _has_bits_(from._has_bits_),
- _cached_size_(0) {
+ _has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
suffix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_suffix()) {
@@ -294,7 +277,6 @@ Version::Version(const Version& from)
}
void Version::SharedCtor() {
- _cached_size_ = 0;
suffix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&major_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&patch_) -
@@ -311,9 +293,7 @@ void Version::SharedDtor() {
}
void Version::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Version::descriptor() {
::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
@@ -321,7 +301,7 @@ const ::google::protobuf::Descriptor* Version::descriptor() {
}
const Version& Version::default_instance() {
- ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersion();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base);
return *internal_default_instance();
}
@@ -334,8 +314,7 @@ void Version::Clear() {
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!suffix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- suffix_.UnsafeMutablePointer()->clear();
+ suffix_.ClearNonDefaultToEmptyNoArena();
}
if (cached_has_bits & 14u) {
::memset(&major_, 0, static_cast<size_t>(
@@ -352,7 +331,7 @@ bool Version::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.compiler.Version)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -555,9 +534,7 @@ size_t Version::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -626,13 +603,13 @@ void Version::Swap(Version* other) {
}
void Version::InternalSwap(Version* other) {
using std::swap;
- suffix_.Swap(&other->suffix_);
+ 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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Version::GetMetadata() const {
@@ -659,9 +636,8 @@ const int CodeGeneratorRequest::kCompilerVersionFieldNumber;
CodeGeneratorRequest::CodeGeneratorRequest()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorRequest();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorRequest.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorRequest)
}
@@ -669,7 +645,6 @@ CodeGeneratorRequest::CodeGeneratorRequest(const CodeGeneratorRequest& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
file_to_generate_(from.file_to_generate_),
proto_file_(from.proto_file_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
@@ -686,7 +661,6 @@ CodeGeneratorRequest::CodeGeneratorRequest(const CodeGeneratorRequest& from)
}
void CodeGeneratorRequest::SharedCtor() {
- _cached_size_ = 0;
parameter_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
compiler_version_ = NULL;
}
@@ -702,9 +676,7 @@ void CodeGeneratorRequest::SharedDtor() {
}
void CodeGeneratorRequest::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* CodeGeneratorRequest::descriptor() {
::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
@@ -712,7 +684,7 @@ const ::google::protobuf::Descriptor* CodeGeneratorRequest::descriptor() {
}
const CodeGeneratorRequest& CodeGeneratorRequest::default_instance() {
- ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorRequest();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorRequest.base);
return *internal_default_instance();
}
@@ -728,8 +700,7 @@ void CodeGeneratorRequest::Clear() {
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 3u) {
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!parameter_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- parameter_.UnsafeMutablePointer()->clear();
+ parameter_.ClearNonDefaultToEmptyNoArena();
}
if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(compiler_version_ != NULL);
@@ -746,7 +717,7 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorRequest)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -857,7 +828,7 @@ void CodeGeneratorRequest::SerializeWithCachedSizes(
// optional .google.protobuf.compiler.Version compiler_version = 3;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, *compiler_version_, output);
+ 3, this->_internal_compiler_version(), output);
}
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
@@ -909,7 +880,7 @@ void CodeGeneratorRequest::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 3, *compiler_version_, deterministic, target);
+ 3, this->_internal_compiler_version(), deterministic, target);
}
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
@@ -973,9 +944,7 @@ size_t CodeGeneratorRequest::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -1042,11 +1011,11 @@ void CodeGeneratorRequest::InternalSwap(CodeGeneratorRequest* other) {
using std::swap;
file_to_generate_.InternalSwap(CastToBase(&other->file_to_generate_));
CastToBase(&proto_file_)->InternalSwap(CastToBase(&other->proto_file_));
- parameter_.Swap(&other->parameter_);
+ 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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata CodeGeneratorRequest::GetMetadata() const {
@@ -1067,17 +1036,15 @@ const int CodeGeneratorResponse_File::kContentFieldNumber;
CodeGeneratorResponse_File::CodeGeneratorResponse_File()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_File();
- }
+ ::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)
}
CodeGeneratorResponse_File::CodeGeneratorResponse_File(const CodeGeneratorResponse_File& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- _has_bits_(from._has_bits_),
- _cached_size_(0) {
+ _has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name()) {
@@ -1095,7 +1062,6 @@ CodeGeneratorResponse_File::CodeGeneratorResponse_File(const CodeGeneratorRespon
}
void CodeGeneratorResponse_File::SharedCtor() {
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
insertion_point_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
content_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -1113,9 +1079,7 @@ void CodeGeneratorResponse_File::SharedDtor() {
}
void CodeGeneratorResponse_File::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* CodeGeneratorResponse_File::descriptor() {
::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
@@ -1123,7 +1087,7 @@ const ::google::protobuf::Descriptor* CodeGeneratorResponse_File::descriptor() {
}
const CodeGeneratorResponse_File& CodeGeneratorResponse_File::default_instance() {
- ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_File();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base);
return *internal_default_instance();
}
@@ -1137,16 +1101,13 @@ void CodeGeneratorResponse_File::Clear() {
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 7u) {
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- name_.UnsafeMutablePointer()->clear();
+ name_.ClearNonDefaultToEmptyNoArena();
}
if (cached_has_bits & 0x00000002u) {
- GOOGLE_DCHECK(!insertion_point_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- insertion_point_.UnsafeMutablePointer()->clear();
+ insertion_point_.ClearNonDefaultToEmptyNoArena();
}
if (cached_has_bits & 0x00000004u) {
- GOOGLE_DCHECK(!content_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- content_.UnsafeMutablePointer()->clear();
+ content_.ClearNonDefaultToEmptyNoArena();
}
}
_has_bits_.Clear();
@@ -1159,7 +1120,7 @@ bool CodeGeneratorResponse_File::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorResponse.File)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -1357,9 +1318,7 @@ size_t CodeGeneratorResponse_File::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -1426,12 +1385,14 @@ void CodeGeneratorResponse_File::Swap(CodeGeneratorResponse_File* other) {
}
void CodeGeneratorResponse_File::InternalSwap(CodeGeneratorResponse_File* other) {
using std::swap;
- name_.Swap(&other->name_);
- insertion_point_.Swap(&other->insertion_point_);
- content_.Swap(&other->content_);
+ 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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata CodeGeneratorResponse_File::GetMetadata() const {
@@ -1451,9 +1412,8 @@ const int CodeGeneratorResponse::kFileFieldNumber;
CodeGeneratorResponse::CodeGeneratorResponse()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse)
}
@@ -1461,7 +1421,6 @@ CodeGeneratorResponse::CodeGeneratorResponse(const CodeGeneratorResponse& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
file_(from.file_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
error_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -1472,7 +1431,6 @@ CodeGeneratorResponse::CodeGeneratorResponse(const CodeGeneratorResponse& from)
}
void CodeGeneratorResponse::SharedCtor() {
- _cached_size_ = 0;
error_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -1486,9 +1444,7 @@ void CodeGeneratorResponse::SharedDtor() {
}
void CodeGeneratorResponse::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* CodeGeneratorResponse::descriptor() {
::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
@@ -1496,7 +1452,7 @@ const ::google::protobuf::Descriptor* CodeGeneratorResponse::descriptor() {
}
const CodeGeneratorResponse& CodeGeneratorResponse::default_instance() {
- ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse.base);
return *internal_default_instance();
}
@@ -1510,8 +1466,7 @@ void CodeGeneratorResponse::Clear() {
file_.Clear();
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!error_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- error_.UnsafeMutablePointer()->clear();
+ error_.ClearNonDefaultToEmptyNoArena();
}
_has_bits_.Clear();
_internal_metadata_.Clear();
@@ -1523,7 +1478,7 @@ bool CodeGeneratorResponse::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorResponse)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -1671,9 +1626,7 @@ size_t CodeGeneratorResponse::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -1731,10 +1684,10 @@ void CodeGeneratorResponse::Swap(CodeGeneratorResponse* other) {
void CodeGeneratorResponse::InternalSwap(CodeGeneratorResponse* other) {
using std::swap;
CastToBase(&file_)->InternalSwap(CastToBase(&other->file_));
- error_.Swap(&other->error_);
+ error_.Swap(&other->error_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata CodeGeneratorResponse::GetMetadata() const {
@@ -1749,16 +1702,16 @@ void CodeGeneratorResponse::InternalSwap(CodeGeneratorResponse* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::Version* Arena::Create< ::google::protobuf::compiler::Version >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::Create< ::google::protobuf::compiler::CodeGeneratorRequest >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::Create< ::google::protobuf::compiler::CodeGeneratorResponse_File >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::Create< ::google::protobuf::compiler::CodeGeneratorResponse >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorResponse >(arena);
}
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/plugin.pb.h b/src/google/protobuf/compiler/plugin.pb.h
index a6c1300e..d5b70a88 100644
--- a/src/google/protobuf/compiler/plugin.pb.h
+++ b/src/google/protobuf/compiler/plugin.pb.h
@@ -1,19 +1,19 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/compiler/plugin.proto
-#ifndef PROTOBUF_google_2fprotobuf_2fcompiler_2fplugin_2eproto_INCLUDED
-#define PROTOBUF_google_2fprotobuf_2fcompiler_2fplugin_2eproto_INCLUDED
+#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto
+#define PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3005000
+#if GOOGLE_PROTOBUF_VERSION < 3006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3005001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -24,6 +24,7 @@
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -31,6 +32,7 @@
#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
#ifdef major
#undef major
#endif
@@ -49,20 +51,6 @@ struct LIBPROTOC_EXPORT TableStruct {
static const ::google::protobuf::uint32 offsets[];
};
void LIBPROTOC_EXPORT AddDescriptors();
-void LIBPROTOC_EXPORT InitDefaultsVersionImpl();
-void LIBPROTOC_EXPORT InitDefaultsVersion();
-void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorRequestImpl();
-void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorRequest();
-void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponse_FileImpl();
-void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponse_File();
-void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponseImpl();
-void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponse();
-inline void LIBPROTOC_EXPORT InitDefaults() {
- InitDefaultsVersion();
- InitDefaultsCodeGeneratorRequest();
- InitDefaultsCodeGeneratorResponse_File();
- InitDefaultsCodeGeneratorResponse();
-}
} // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto
namespace google {
namespace protobuf {
@@ -84,10 +72,10 @@ LIBPROTOC_EXPORT extern VersionDefaultTypeInternal _Version_default_instance_;
} // namespace google
namespace google {
namespace protobuf {
-template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorRequest* Arena::Create< ::google::protobuf::compiler::CodeGeneratorRequest>(Arena*);
-template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse* Arena::Create< ::google::protobuf::compiler::CodeGeneratorResponse>(Arena*);
-template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::Create< ::google::protobuf::compiler::CodeGeneratorResponse_File>(Arena*);
-template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::Version* Arena::Create< ::google::protobuf::compiler::Version>(Arena*);
+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*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -137,7 +125,7 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_
return reinterpret_cast<const Version*>(
&_Version_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
0;
void Swap(Version* other);
@@ -147,32 +135,33 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_
// implements Message ----------------------------------------------
- inline Version* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<Version>(NULL);
+ inline Version* New() const final {
+ return CreateMaybeMessage<Version>(NULL);
}
- Version* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<Version>(arena);
+ Version* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Version>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Version& from);
void MergeFrom(const Version& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Version* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
@@ -183,7 +172,7 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -238,13 +227,12 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::internal::ArenaStringPtr suffix_;
::google::protobuf::int32 major_;
::google::protobuf::int32 minor_;
::google::protobuf::int32 patch_;
friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersionImpl();
};
// -------------------------------------------------------------------
@@ -289,7 +277,7 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
return reinterpret_cast<const CodeGeneratorRequest*>(
&_CodeGeneratorRequest_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
1;
void Swap(CodeGeneratorRequest* other);
@@ -299,32 +287,33 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
// implements Message ----------------------------------------------
- inline CodeGeneratorRequest* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<CodeGeneratorRequest>(NULL);
+ inline CodeGeneratorRequest* New() const final {
+ return CreateMaybeMessage<CodeGeneratorRequest>(NULL);
}
- CodeGeneratorRequest* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<CodeGeneratorRequest>(arena);
+ CodeGeneratorRequest* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<CodeGeneratorRequest>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const CodeGeneratorRequest& from);
void MergeFrom(const CodeGeneratorRequest& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(CodeGeneratorRequest* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
@@ -335,7 +324,7 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -394,6 +383,9 @@ 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();
@@ -408,13 +400,12 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::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 void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorRequestImpl();
};
// -------------------------------------------------------------------
@@ -459,7 +450,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
return reinterpret_cast<const CodeGeneratorResponse_File*>(
&_CodeGeneratorResponse_File_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
2;
void Swap(CodeGeneratorResponse_File* other);
@@ -469,32 +460,33 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
// implements Message ----------------------------------------------
- inline CodeGeneratorResponse_File* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<CodeGeneratorResponse_File>(NULL);
+ inline CodeGeneratorResponse_File* New() const final {
+ return CreateMaybeMessage<CodeGeneratorResponse_File>(NULL);
}
- CodeGeneratorResponse_File* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<CodeGeneratorResponse_File>(arena);
+ CodeGeneratorResponse_File* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<CodeGeneratorResponse_File>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const CodeGeneratorResponse_File& from);
void MergeFrom(const CodeGeneratorResponse_File& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(CodeGeneratorResponse_File* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
@@ -505,7 +497,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -567,12 +559,11 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::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 void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_FileImpl();
};
// -------------------------------------------------------------------
@@ -617,7 +608,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
return reinterpret_cast<const CodeGeneratorResponse*>(
&_CodeGeneratorResponse_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
3;
void Swap(CodeGeneratorResponse* other);
@@ -627,32 +618,33 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
// implements Message ----------------------------------------------
- inline CodeGeneratorResponse* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<CodeGeneratorResponse>(NULL);
+ inline CodeGeneratorResponse* New() const final {
+ return CreateMaybeMessage<CodeGeneratorResponse>(NULL);
}
- CodeGeneratorResponse* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<CodeGeneratorResponse>(arena);
+ CodeGeneratorResponse* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<CodeGeneratorResponse>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const CodeGeneratorResponse& from);
void MergeFrom(const CodeGeneratorResponse& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(CodeGeneratorResponse* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
@@ -663,7 +655,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -705,11 +697,10 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ 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 void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponseImpl();
};
// ===================================================================
@@ -844,8 +835,11 @@ inline ::std::string* Version::mutable_suffix() {
}
inline ::std::string* Version::release_suffix() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.Version.suffix)
+ if (!has_suffix()) {
+ return NULL;
+ }
clear_has_suffix();
- return suffix_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return suffix_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void Version::set_allocated_suffix(::std::string* suffix) {
if (suffix != NULL) {
@@ -980,8 +974,11 @@ inline ::std::string* CodeGeneratorRequest::mutable_parameter() {
}
inline ::std::string* CodeGeneratorRequest::release_parameter() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.parameter)
+ if (!has_parameter()) {
+ return NULL;
+ }
clear_has_parameter();
- return parameter_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return parameter_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void CodeGeneratorRequest::set_allocated_parameter(::std::string* parameter) {
if (parameter != NULL) {
@@ -1034,6 +1031,9 @@ 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_;
+}
inline const ::google::protobuf::compiler::Version& CodeGeneratorRequest::compiler_version() const {
const ::google::protobuf::compiler::Version* p = compiler_version_;
// @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
@@ -1050,8 +1050,8 @@ inline ::google::protobuf::compiler::Version* CodeGeneratorRequest::release_comp
inline ::google::protobuf::compiler::Version* CodeGeneratorRequest::mutable_compiler_version() {
set_has_compiler_version();
if (compiler_version_ == NULL) {
- compiler_version_ = ::google::protobuf::Arena::Create< ::google::protobuf::compiler::Version >(
- GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<::google::protobuf::compiler::Version>(GetArenaNoVirtual());
+ compiler_version_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
return compiler_version_;
@@ -1129,8 +1129,11 @@ inline ::std::string* CodeGeneratorResponse_File::mutable_name() {
}
inline ::std::string* CodeGeneratorResponse_File::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.name)
+ if (!has_name()) {
+ return NULL;
+ }
clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void CodeGeneratorResponse_File::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -1192,8 +1195,11 @@ inline ::std::string* CodeGeneratorResponse_File::mutable_insertion_point() {
}
inline ::std::string* CodeGeneratorResponse_File::release_insertion_point() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
+ if (!has_insertion_point()) {
+ return NULL;
+ }
clear_has_insertion_point();
- return insertion_point_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return insertion_point_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void CodeGeneratorResponse_File::set_allocated_insertion_point(::std::string* insertion_point) {
if (insertion_point != NULL) {
@@ -1255,8 +1261,11 @@ inline ::std::string* CodeGeneratorResponse_File::mutable_content() {
}
inline ::std::string* CodeGeneratorResponse_File::release_content() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.content)
+ if (!has_content()) {
+ return NULL;
+ }
clear_has_content();
- return content_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return content_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void CodeGeneratorResponse_File::set_allocated_content(::std::string* content) {
if (content != NULL) {
@@ -1322,8 +1331,11 @@ inline ::std::string* CodeGeneratorResponse::mutable_error() {
}
inline ::std::string* CodeGeneratorResponse::release_error() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.error)
+ if (!has_error()) {
+ return NULL;
+ }
clear_has_error();
- return error_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return error_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void CodeGeneratorResponse::set_allocated_error(::std::string* error) {
if (error != NULL) {
@@ -1383,4 +1395,4 @@ CodeGeneratorResponse::file() const {
// @@protoc_insertion_point(global_scope)
-#endif // PROTOBUF_google_2fprotobuf_2fcompiler_2fplugin_2eproto_INCLUDED
+#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 5ca6b4ee..01f28b37 100644
--- a/src/google/protobuf/compiler/python/python_generator.cc
+++ b/src/google/protobuf/compiler/python/python_generator.cc
@@ -49,9 +49,6 @@
#include <limits>
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
#include <utility>
#include <vector>
@@ -202,11 +199,6 @@ void PrintTopBoilerplate(
"from google.protobuf import service_reflection\n");
}
- // Avoid circular imports if this module is descriptor_pb2.
- if (!descriptor_proto) {
- printer->Print(
- "from google.protobuf import descriptor_pb2\n");
- }
printer->Print(
"# @@protoc_insertion_point(imports)\n\n"
"_sym_db = _symbol_database.Default()\n");
@@ -338,7 +330,7 @@ bool Generator::Generate(const FileDescriptor* file,
fdp.SerializeToString(&file_descriptor_serialized_);
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
+ std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
GOOGLE_CHECK(output.get());
io::Printer printer(output.get(), '$');
printer_ = &printer;
@@ -422,11 +414,13 @@ void Generator::PrintFileDescriptor() const {
m["name"] = file_->name();
m["package"] = file_->package();
m["syntax"] = StringifySyntax(file_->syntax());
+ m["options"] = OptionsValue(file_->options().SerializeAsString());
const char file_descriptor_template[] =
"$descriptor_name$ = _descriptor.FileDescriptor(\n"
" name='$name$',\n"
" package='$package$',\n"
- " syntax='$syntax$',\n";
+ " syntax='$syntax$',\n"
+ " serialized_options=$options$,\n";
printer_->Print(m, file_descriptor_template);
printer_->Indent();
printer_->Print(
@@ -526,9 +520,9 @@ void Generator::PrintEnum(const EnumDescriptor& enum_descriptor) const {
printer_->Outdent();
printer_->Print("],\n");
printer_->Print("containing_type=None,\n");
- printer_->Print("options=$options_value$,\n",
+ printer_->Print("serialized_options=$options_value$,\n",
"options_value",
- OptionsValue("EnumOptions", options_string));
+ OptionsValue(options_string));
EnumDescriptorProto edp;
PrintSerializedPbInterval(enum_descriptor, edp);
printer_->Outdent();
@@ -606,13 +600,13 @@ void Generator::PrintServiceDescriptor(
m["full_name"] = descriptor.full_name();
m["file"] = kDescriptorKey;
m["index"] = SimpleItoa(descriptor.index());
- m["options_value"] = OptionsValue("ServiceOptions", options_string);
+ m["options_value"] = OptionsValue(options_string);
const char required_function_arguments[] =
"name='$name$',\n"
"full_name='$full_name$',\n"
"file=$file$,\n"
"index=$index$,\n"
- "options=$options_value$,\n";
+ "serialized_options=$options_value$,\n";
printer_->Print(m, required_function_arguments);
ServiceDescriptorProto sdp;
@@ -630,7 +624,7 @@ void Generator::PrintServiceDescriptor(
m["serialized_options"] = CEscape(options_string);
m["input_type"] = ModuleLevelDescriptorName(*(method->input_type()));
m["output_type"] = ModuleLevelDescriptorName(*(method->output_type()));
- m["options_value"] = OptionsValue("MethodOptions", options_string);
+ m["options_value"] = OptionsValue(options_string);
printer_->Print("_descriptor.MethodDescriptor(\n");
printer_->Indent();
printer_->Print(
@@ -641,7 +635,7 @@ void Generator::PrintServiceDescriptor(
"containing_service=None,\n"
"input_type=$input_type$,\n"
"output_type=$output_type$,\n"
- "options=$options_value$,\n");
+ "serialized_options=$options_value$,\n");
printer_->Outdent();
printer_->Print("),\n");
}
@@ -737,10 +731,10 @@ void Generator::PrintDescriptor(const Descriptor& message_descriptor) const {
string options_string;
message_descriptor.options().SerializeToString(&options_string);
printer_->Print(
- "options=$options_value$,\n"
+ "serialized_options=$options_value$,\n"
"is_extendable=$extendable$,\n"
"syntax='$syntax$'",
- "options_value", OptionsValue("MessageOptions", options_string),
+ "options_value", OptionsValue(options_string),
"extendable", message_descriptor.extension_range_count() > 0 ?
"True" : "False",
"syntax", StringifySyntax(message_descriptor.file()->syntax()));
@@ -765,17 +759,18 @@ void Generator::PrintDescriptor(const Descriptor& message_descriptor) const {
m["full_name"] = desc->full_name();
m["index"] = SimpleItoa(desc->index());
string options_string =
- OptionsValue("OneofOptions", desc->options().SerializeAsString());
+ OptionsValue(desc->options().SerializeAsString());
if (options_string == "None") {
- m["options"] = "";
+ m["serialized_options"] = "";
} else {
- m["options"] = ", options=" + options_string;
+ m["serialized_options"] = ", serialized_options=" + options_string;
}
printer_->Print(
m,
"_descriptor.OneofDescriptor(\n"
" name='$name$', full_name='$full_name$',\n"
- " index=$index$, containing_type=None, fields=[]$options$),\n");
+ " index=$index$, containing_type=None, "
+ "fields=[]$serialized_options$),\n");
}
printer_->Outdent();
printer_->Print("],\n");
@@ -1098,27 +1093,22 @@ void Generator::PrintEnumValueDescriptor(
m["name"] = descriptor.name();
m["index"] = SimpleItoa(descriptor.index());
m["number"] = SimpleItoa(descriptor.number());
- m["options"] = OptionsValue("EnumValueOptions", options_string);
+ m["options"] = OptionsValue(options_string);
printer_->Print(
m,
"_descriptor.EnumValueDescriptor(\n"
" name='$name$', index=$index$, number=$number$,\n"
- " options=$options$,\n"
+ " serialized_options=$options$,\n"
" type=None)");
}
-// Returns a Python expression that calls descriptor._ParseOptions using
-// the given descriptor class name and serialized options protobuf string.
-string Generator::OptionsValue(
- const string& class_name, const string& serialized_options) const {
+// Returns a CEscaped string of serialized_options.
+string Generator::OptionsValue(const string& serialized_options) const {
if (serialized_options.length() == 0 || GeneratingDescriptorProto()) {
return "None";
} else {
- string full_class_name = "descriptor_pb2." + class_name;
-//##!PY25 return "_descriptor._ParseOptions(" + full_class_name + "(), b'"
-//##!PY25 + CEscape(serialized_options)+ "')";
- return "_descriptor._ParseOptions(" + full_class_name + "(), _b('" //##PY25
- + CEscape(serialized_options)+ "'))"; //##PY25
+//##!PY25 return "b'('" + CEscape(serialized_options)+ "')";
+ return "_b('"+ CEscape(serialized_options) + "')"; //##PY25
}
}
@@ -1138,7 +1128,7 @@ void Generator::PrintFieldDescriptor(
m["has_default_value"] = field.has_default_value() ? "True" : "False";
m["default_value"] = StringifyDefaultValue(field);
m["is_extension"] = is_extension ? "True" : "False";
- m["options"] = OptionsValue("FieldOptions", options_string);
+ m["serialized_options"] = OptionsValue(options_string);
m["json_name"] = field.has_json_name() ?
", json_name='" + field.json_name() + "'": "";
// We always set message_type and enum_type to None at this point, and then
@@ -1151,7 +1141,7 @@ void Generator::PrintFieldDescriptor(
" has_default_value=$has_default_value$, default_value=$default_value$,\n"
" message_type=None, enum_type=None, containing_type=None,\n"
" is_extension=$is_extension$, extension_scope=None,\n"
- " options=$options$$json_name$, file=DESCRIPTOR)";
+ " serialized_options=$serialized_options$$json_name$, file=DESCRIPTOR)";
printer_->Print(m, field_descriptor_decl);
}
@@ -1280,23 +1270,18 @@ namespace {
void PrintDescriptorOptionsFixingCode(const string& descriptor,
const string& options,
io::Printer* printer) {
- // TODO(xiaofeng): I have added a method _SetOptions() to DescriptorBase
- // in proto2 python runtime but it couldn't be used here because appengine
- // uses a snapshot version of the library in which the new method is not
- // yet present. After appengine has synced their runtime library, the code
- // below should be cleaned up to use _SetOptions().
+ // Reset the _options to None thus DescriptorBase.GetOptions() can
+ // parse _options again after extensions are registered.
printer->Print(
- "$descriptor$.has_options = True\n"
- "$descriptor$._options = $options$\n",
- "descriptor", descriptor, "options", options);
+ "$descriptor$._options = None\n",
+ "descriptor", descriptor);
}
} // namespace
// Prints expressions that set the options field of all descriptors.
void Generator::FixAllDescriptorOptions() const {
// Prints an expression that sets the file descriptor's options.
- string file_options = OptionsValue(
- "FileOptions", file_->options().SerializeAsString());
+ string file_options = OptionsValue(file_->options().SerializeAsString());
if (file_options != "None") {
PrintDescriptorOptionsFixingCode(kDescriptorKey, file_options, printer_);
}
@@ -1318,8 +1303,7 @@ void Generator::FixAllDescriptorOptions() const {
}
void Generator::FixOptionsForOneof(const OneofDescriptor& oneof) const {
- string oneof_options = OptionsValue(
- "OneofOptions", oneof.options().SerializeAsString());
+ string oneof_options = OptionsValue(oneof.options().SerializeAsString());
if (oneof_options != "None") {
string oneof_name = strings::Substitute(
"$0.$1['$2']",
@@ -1334,14 +1318,14 @@ void Generator::FixOptionsForOneof(const OneofDescriptor& oneof) const {
void Generator::FixOptionsForEnum(const EnumDescriptor& enum_descriptor) const {
string descriptor_name = ModuleLevelDescriptorName(enum_descriptor);
string enum_options = OptionsValue(
- "EnumOptions", enum_descriptor.options().SerializeAsString());
+ enum_descriptor.options().SerializeAsString());
if (enum_options != "None") {
PrintDescriptorOptionsFixingCode(descriptor_name, enum_options, printer_);
}
for (int i = 0; i < enum_descriptor.value_count(); ++i) {
const EnumValueDescriptor& value_descriptor = *enum_descriptor.value(i);
string value_options = OptionsValue(
- "EnumValueOptions", value_descriptor.options().SerializeAsString());
+ value_descriptor.options().SerializeAsString());
if (value_options != "None") {
PrintDescriptorOptionsFixingCode(
StringPrintf("%s.values_by_name[\"%s\"]", descriptor_name.c_str(),
@@ -1355,8 +1339,7 @@ void Generator::FixOptionsForEnum(const EnumDescriptor& enum_descriptor) const {
// extensions).
void Generator::FixOptionsForField(
const FieldDescriptor& field) const {
- string field_options = OptionsValue(
- "FieldOptions", field.options().SerializeAsString());
+ string field_options = OptionsValue(field.options().SerializeAsString());
if (field_options != "None") {
string field_name;
if (field.is_extension()) {
@@ -1402,7 +1385,7 @@ void Generator::FixOptionsForMessage(const Descriptor& descriptor) const {
}
// Message option for this message.
string message_options = OptionsValue(
- "MessageOptions", descriptor.options().SerializeAsString());
+ descriptor.options().SerializeAsString());
if (message_options != "None") {
string descriptor_name = ModuleLevelDescriptorName(descriptor);
PrintDescriptorOptionsFixingCode(descriptor_name,
diff --git a/src/google/protobuf/compiler/python/python_generator.h b/src/google/protobuf/compiler/python/python_generator.h
index 2b5a028b..8e4050de 100644
--- a/src/google/protobuf/compiler/python/python_generator.h
+++ b/src/google/protobuf/compiler/python/python_generator.h
@@ -135,8 +135,7 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator {
const ServiceDescriptor& descriptor) const;
void PrintEnumValueDescriptor(const EnumValueDescriptor& descriptor) const;
- string OptionsValue(const string& class_name,
- const string& serialized_options) const;
+ string OptionsValue(const string& serialized_options) const;
bool GeneratingDescriptorProto() const;
template <typename DescriptorT>
diff --git a/src/google/protobuf/compiler/python/python_plugin_unittest.cc b/src/google/protobuf/compiler/python/python_plugin_unittest.cc
index 34f857fd..2f096808 100644
--- a/src/google/protobuf/compiler/python/python_plugin_unittest.cc
+++ b/src/google/protobuf/compiler/python/python_plugin_unittest.cc
@@ -35,9 +35,6 @@
// worth.
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/compiler/python/python_generator.h>
#include <google/protobuf/compiler/command_line_interface.h>
@@ -74,7 +71,7 @@ class TestGenerator : public CodeGenerator {
void TryInsert(const string& filename, const string& insertion_point,
GeneratorContext* context) const {
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
context->OpenForInsert(filename, insertion_point));
io::Printer printer(output.get(), '$');
printer.Print("// inserted $name$\n", "name", insertion_point);
diff --git a/src/google/protobuf/compiler/ruby/ruby_generator.cc b/src/google/protobuf/compiler/ruby/ruby_generator.cc
index fbe3b4cb..bd737c02 100644
--- a/src/google/protobuf/compiler/ruby/ruby_generator.cc
+++ b/src/google/protobuf/compiler/ruby/ruby_generator.cc
@@ -39,8 +39,6 @@
#include <google/protobuf/compiler/ruby/ruby_generator.h>
-using google::protobuf::internal::scoped_ptr;
-
namespace google {
namespace protobuf {
namespace compiler {
@@ -339,9 +337,20 @@ void GenerateEnumAssignment(
}
int GeneratePackageModules(
- std::string package_name,
+ const FileDescriptor* file,
google::protobuf::io::Printer* printer) {
int levels = 0;
+ bool need_change_to_module;
+ std::string package_name;
+
+ if (file->options().has_ruby_package()) {
+ package_name = file->options().ruby_package();
+ need_change_to_module = false;
+ } else {
+ package_name = file->package();
+ need_change_to_module = true;
+ }
+
while (!package_name.empty()) {
size_t dot_index = package_name.find(".");
string component;
@@ -352,7 +361,9 @@ int GeneratePackageModules(
component = package_name.substr(0, dot_index);
package_name = package_name.substr(dot_index + 1);
}
- component = PackageToModule(component);
+ if (need_change_to_module) {
+ component = PackageToModule(component);
+ }
printer->Print(
"module $name$\n",
"name", component);
@@ -464,7 +475,7 @@ bool GenerateFile(const FileDescriptor* file, io::Printer* printer,
printer->Print(
"end\n\n");
- int levels = GeneratePackageModules(file->package(), printer);
+ int levels = GeneratePackageModules(file, printer);
for (int i = 0; i < file->message_type_count(); i++) {
GenerateMessageAssignment("", file->message_type(i), printer);
}
@@ -488,7 +499,7 @@ bool Generator::Generate(
return false;
}
- scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(GetOutputFilename(file->name())));
io::Printer printer(output.get(), '$');
diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc
index 9d48bfba..58dd0ac4 100644
--- a/src/google/protobuf/descriptor.cc
+++ b/src/google/protobuf/descriptor.cc
@@ -38,24 +38,22 @@
#include <limits>
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <set>
#include <string>
#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>
#include <google/protobuf/io/strtod.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/tokenizer.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
-#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor_database.h>
#include <google/protobuf/dynamic_message.h>
@@ -65,6 +63,7 @@
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/substitute.h>
+
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/stl_util.h>
@@ -347,14 +346,14 @@ class PrefixRemover {
}
if (ascii_tolower(str[i]) != prefix_[j++]) {
- return str.as_string();
+ return string(str);
}
}
// If we didn't make it through the prefix, we've failed to strip the
// prefix.
if (j < prefix_.size()) {
- return str.as_string();
+ return string(str);
}
// Skip underscores between prefix and further characters.
@@ -364,12 +363,12 @@ class PrefixRemover {
// Enum label can't be the empty string.
if (i == str.size()) {
- return str.as_string();
+ return string(str);
}
// We successfully stripped the prefix.
str.remove_prefix(i);
- return str.as_string();
+ return string(str);
}
private:
@@ -407,9 +406,10 @@ typedef std::pair<const EnumDescriptor*, int> EnumIntPair;
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
@@ -425,11 +425,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
@@ -776,10 +775,10 @@ class FileDescriptorTables {
SymbolsByParentMap symbols_by_parent_;
mutable FieldsByNameMap fields_by_lowercase_name_;
- mutable FieldsByNameMap* fields_by_lowercase_name_tmp_;
+ std::unique_ptr<FieldsByNameMap> fields_by_lowercase_name_tmp_;
mutable GoogleOnceDynamic fields_by_lowercase_name_once_;
mutable FieldsByNameMap fields_by_camelcase_name_;
- mutable FieldsByNameMap* fields_by_camelcase_name_tmp_;
+ std::unique_ptr<FieldsByNameMap> fields_by_camelcase_name_tmp_;
mutable GoogleOnceDynamic fields_by_camelcase_name_once_;
FieldsByNumberMap fields_by_number_; // Not including extensions.
EnumValuesByNumberMap enum_values_by_number_;
@@ -1147,10 +1146,8 @@ bool DescriptorPool::Tables::AddFile(const FileDescriptor* file) {
void FileDescriptorTables::FinalizeTables() {
// Clean up the temporary maps used by AddFieldByStylizedNames().
- delete fields_by_lowercase_name_tmp_;
- fields_by_lowercase_name_tmp_ = NULL;
- delete fields_by_camelcase_name_tmp_;
- fields_by_camelcase_name_tmp_ = NULL;
+ fields_by_lowercase_name_tmp_ = nullptr;
+ fields_by_camelcase_name_tmp_ = nullptr;
}
void FileDescriptorTables::AddFieldByStylizedNames(
@@ -1165,7 +1162,7 @@ void FileDescriptorTables::AddFieldByStylizedNames(
// entries from fields_by_number_.
PointerStringPair lowercase_key(parent, field->lowercase_name().c_str());
- if (!InsertIfNotPresent(fields_by_lowercase_name_tmp_, lowercase_key,
+ if (!InsertIfNotPresent(fields_by_lowercase_name_tmp_.get(), lowercase_key,
field)) {
InsertIfNotPresent(
&fields_by_lowercase_name_, lowercase_key,
@@ -1173,7 +1170,7 @@ void FileDescriptorTables::AddFieldByStylizedNames(
}
PointerStringPair camelcase_key(parent, field->camelcase_name().c_str());
- if (!InsertIfNotPresent(fields_by_camelcase_name_tmp_, camelcase_key,
+ if (!InsertIfNotPresent(fields_by_camelcase_name_tmp_.get(), camelcase_key,
field)) {
InsertIfNotPresent(
&fields_by_camelcase_name_, camelcase_key,
@@ -1802,6 +1799,15 @@ FileDescriptor::FindExtensionByCamelcaseName(const string& key) const {
}
}
+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()) {
+ *proto->mutable_options() = *options_;
+ }
+}
+
const Descriptor::ExtensionRange*
Descriptor::FindExtensionRangeContainingNumber(int number) const {
// Linear search should be fine because we don't expect a message to have
@@ -2069,13 +2075,7 @@ void Descriptor::CopyTo(DescriptorProto* proto) const {
enum_type(i)->CopyTo(proto->add_enum_type());
}
for (int i = 0; i < extension_range_count(); i++) {
- DescriptorProto::ExtensionRange* range = proto->add_extension_range();
- range->set_start(extension_range(i)->start);
- range->set_end(extension_range(i)->end);
- const ExtensionRangeOptions* options = extension_range(i)->options_;
- if (options != &ExtensionRangeOptions::default_instance()) {
- range->mutable_options()->CopyFrom(*options);
- }
+ extension_range(i)->CopyTo(proto->add_extension_range());
}
for (int i = 0; i < extension_count(); i++) {
extension(i)->CopyTo(proto->add_extension());
@@ -2306,7 +2306,7 @@ bool RetrieveOptions(int depth, const Message& options,
return RetrieveOptionsAssumingRightPool(depth, options, option_entries);
}
DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<Message> dynamic_options(
+ std::unique_ptr<Message> dynamic_options(
factory.GetPrototype(option_descriptor)->New());
if (dynamic_options->ParseFromString(options.SerializeAsString())) {
return RetrieveOptionsAssumingRightPool(depth, *dynamic_options,
@@ -3116,15 +3116,18 @@ namespace {
struct OptionsToInterpret {
OptionsToInterpret(const string& ns,
const string& el,
+ 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) {
}
string name_scope;
string element_name;
+ std::vector<int> element_path;
const Message* original_options;
Message* options;
};
@@ -3291,7 +3294,7 @@ class DescriptorBuilder {
// descriptor.proto.
template<class DescriptorT> void AllocateOptions(
const typename DescriptorT::OptionsType& orig_options,
- DescriptorT* descriptor);
+ DescriptorT* descriptor, int options_field_tag);
// Specialization for FileOptions.
void AllocateOptions(const FileOptions& orig_options,
FileDescriptor* descriptor);
@@ -3301,7 +3304,8 @@ class DescriptorBuilder {
const string& name_scope,
const string& element_name,
const typename DescriptorT::OptionsType& orig_options,
- DescriptorT* descriptor);
+ DescriptorT* descriptor,
+ std::vector<int>& options_path);
// These methods all have the same signature for the sake of the BUILD_ARRAY
// macro, below.
@@ -3390,13 +3394,21 @@ class DescriptorBuilder {
// Otherwise returns true.
bool InterpretOptions(OptionsToInterpret* options_to_interpret);
+ // Updates the given source code info by re-writing uninterpreted option
+ // locations to refer to the corresponding interpreted option.
+ void UpdateSourceCodeInfo(SourceCodeInfo* info);
+
class AggregateOptionFinder;
private:
// Interprets uninterpreted_option_ on the specified message, which
// must be the mutable copy of the original options message to which
- // uninterpreted_option_ belongs.
- bool InterpretSingleOption(Message* options);
+ // uninterpreted_option_ belongs. The given src_path is the source
+ // 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);
// Adds the uninterpreted_option to the given options message verbatim.
// Used when AllowUnknownDependencies() is in effect and we can't find
@@ -3471,6 +3483,16 @@ class DescriptorBuilder {
// can use it to find locations recorded by the parser.
const UninterpretedOption* uninterpreted_option_;
+ // This maps the element path of uninterpreted options to the element path
+ // of the resulting interpreted option. This is used to modify a file's
+ // source code info to account for option interpretation.
+ std::map<std::vector<int>, std::vector<int>> interpreted_paths_;
+
+ // This maps the path to a repeated option field to the known number of
+ // elements the field contains. This is used to track the compute the
+ // index portion of the element path when interpreting a single option.
+ std::map<std::vector<int>, int> repeated_option_counts_;
+
// Factory used to create the dynamic messages we need to parse
// any aggregate option values we encounter.
DynamicMessageFactory dynamic_factory_;
@@ -4088,24 +4110,30 @@ void DescriptorBuilder::ValidateSymbolName(
// FileDescriptor.
template<class DescriptorT> void DescriptorBuilder::AllocateOptions(
const typename DescriptorT::OptionsType& orig_options,
- DescriptorT* descriptor) {
+ DescriptorT* descriptor, int options_field_tag) {
+ std::vector<int> options_path;
+ descriptor->GetLocationPath(&options_path);
+ options_path.push_back(options_field_tag);
AllocateOptionsImpl(descriptor->full_name(), descriptor->full_name(),
- orig_options, descriptor);
+ orig_options, descriptor, options_path);
}
// We specialize for FileDescriptor.
void DescriptorBuilder::AllocateOptions(const FileOptions& orig_options,
FileDescriptor* descriptor) {
+ std::vector<int> options_path;
+ options_path.push_back(FileDescriptorProto::kOptionsFieldNumber);
// We add the dummy token so that LookupSymbol does the right thing.
AllocateOptionsImpl(descriptor->package() + ".dummy", descriptor->name(),
- orig_options, descriptor);
+ orig_options, descriptor, options_path);
}
template<class DescriptorT> void DescriptorBuilder::AllocateOptionsImpl(
const string& name_scope,
const string& element_name,
const typename DescriptorT::OptionsType& orig_options,
- DescriptorT* descriptor) {
+ DescriptorT* descriptor,
+ 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 =
@@ -4128,7 +4156,8 @@ template<class DescriptorT> void DescriptorBuilder::AllocateOptionsImpl(
// we're still trying to build it.
if (options->uninterpreted_option_size() > 0) {
options_to_interpret_.push_back(
- OptionsToInterpret(name_scope, element_name, &orig_options, options));
+ OptionsToInterpret(name_scope, element_name, options_path,
+ &orig_options, options));
}
}
@@ -4266,8 +4295,9 @@ FileDescriptor* DescriptorBuilder::BuildFileImpl(
result->is_placeholder_ = false;
result->finished_building_ = false;
+ SourceCodeInfo *info = NULL;
if (proto.has_source_code_info()) {
- SourceCodeInfo *info = tables_->AllocateMessage<SourceCodeInfo>();
+ info = tables_->AllocateMessage<SourceCodeInfo>();
info->CopyFrom(proto.source_code_info());
result->source_code_info_ = info;
} else {
@@ -4465,6 +4495,10 @@ FileDescriptor* DescriptorBuilder::BuildFileImpl(
option_interpreter.InterpretOptions(&(*iter));
}
options_to_interpret_.clear();
+
+ if (info != NULL) {
+ option_interpreter.UpdateSourceCodeInfo(info);
+ }
}
// Validate options. See comments at InternalSetLazilyBuildDependencies about
@@ -4536,7 +4570,8 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto,
if (!proto.has_options()) {
result->options_ = NULL; // Will set to default_instance later.
} else {
- AllocateOptions(proto.options(), result);
+ AllocateOptions(proto.options(), result,
+ DescriptorProto::kOptionsFieldNumber);
}
AddSymbol(result->full_name(), parent, result->name(),
@@ -4916,7 +4951,8 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto,
if (!proto.has_options()) {
result->options_ = NULL; // Will set to default_instance later.
} else {
- AllocateOptions(proto.options(), result);
+ AllocateOptions(proto.options(), result,
+ FieldDescriptorProto::kOptionsFieldNumber);
}
@@ -4950,8 +4986,16 @@ void DescriptorBuilder::BuildExtensionRange(
if (!proto.has_options()) {
result->options_ = NULL; // Will set to default_instance later.
} else {
+ std::vector<int> options_path;
+ parent->GetLocationPath(&options_path);
+ 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++);
+ options_path.push_back(index);
+ options_path.push_back(DescriptorProto_ExtensionRange::kOptionsFieldNumber);
AllocateOptionsImpl(parent->full_name(), parent->full_name(),
- proto.options(), result);
+ proto.options(), result, options_path);
}
}
@@ -5003,7 +5047,8 @@ void DescriptorBuilder::BuildOneof(const OneofDescriptorProto& proto,
if (!proto.has_options()) {
result->options_ = NULL; // Will set to default_instance later.
} else {
- AllocateOptions(proto.options(), result);
+ AllocateOptions(proto.options(), result,
+ OneofDescriptorProto::kOptionsFieldNumber);
}
AddSymbol(result->full_name(), parent, result->name(),
@@ -5120,7 +5165,8 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto,
if (!proto.has_options()) {
result->options_ = NULL; // Will set to default_instance later.
} else {
- AllocateOptions(proto.options(), result);
+ AllocateOptions(proto.options(), result,
+ EnumDescriptorProto::kOptionsFieldNumber);
}
AddSymbol(result->full_name(), parent, result->name(),
@@ -5132,13 +5178,13 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto,
for (int j = i + 1; j < proto.reserved_range_size(); j++) {
const EnumDescriptorProto_EnumReservedRange& range2 =
proto.reserved_range(j);
- if (range1.end() > range2.start() && range2.end() > range1.start()) {
+ if (range1.end() >= range2.start() && range2.end() >= range1.start()) {
AddError(result->full_name(), proto.reserved_range(i),
DescriptorPool::ErrorCollector::NUMBER,
strings::Substitute("Reserved range $0 to $1 overlaps with "
"already-defined range $2 to $3.",
- range2.start(), range2.end() - 1,
- range1.start(), range1.end() - 1));
+ range2.start(), range2.end(),
+ range1.start(), range1.end()));
}
}
}
@@ -5197,7 +5243,8 @@ void DescriptorBuilder::BuildEnumValue(const EnumValueDescriptorProto& proto,
if (!proto.has_options()) {
result->options_ = NULL; // Will set to default_instance later.
} else {
- AllocateOptions(proto.options(), result);
+ AllocateOptions(proto.options(), result,
+ EnumValueDescriptorProto::kOptionsFieldNumber);
}
// Again, enum values are weird because we makes them appear as siblings
@@ -5264,7 +5311,8 @@ void DescriptorBuilder::BuildService(const ServiceDescriptorProto& proto,
if (!proto.has_options()) {
result->options_ = NULL; // Will set to default_instance later.
} else {
- AllocateOptions(proto.options(), result);
+ AllocateOptions(proto.options(), result,
+ ServiceDescriptorProto::kOptionsFieldNumber);
}
AddSymbol(result->full_name(), NULL, result->name(),
@@ -5292,7 +5340,8 @@ void DescriptorBuilder::BuildMethod(const MethodDescriptorProto& proto,
if (!proto.has_options()) {
result->options_ = NULL; // Will set to default_instance later.
} else {
- AllocateOptions(proto.options(), result);
+ AllocateOptions(proto.options(), result,
+ MethodDescriptorProto::kOptionsFieldNumber);
}
result->client_streaming_ = proto.client_streaming();
@@ -5661,13 +5710,15 @@ void DescriptorBuilder::CrossLinkField(
if (!tables_->AddExtension(field)) {
const FieldDescriptor* conflicting_field =
tables_->FindExtension(field->containing_type(), field->number());
+ string containing_type_name =
+ field->containing_type() == NULL
+ ? "unknown"
+ : field->containing_type()->full_name();
string error_msg = strings::Substitute(
"Extension number $0 has already been used in \"$1\" by extension "
"\"$2\" defined in $3.",
- field->number(),
- field->containing_type()->full_name(),
- conflicting_field->full_name(),
- conflicting_field->file()->name());
+ field->number(), containing_type_name,
+ conflicting_field->full_name(), conflicting_field->file()->name());
// Conflicting extension numbers should be an error. However, before
// turning this into an error we need to fix all existing broken
// protos first.
@@ -6262,6 +6313,9 @@ bool DescriptorBuilder::OptionInterpreter::InterpretOptions(
<< "No field named \"uninterpreted_option\" in the Options proto.";
options->GetReflection()->ClearField(options, uninterpreted_options_field);
+ std::vector<int> src_path = options_to_interpret->element_path;
+ src_path.push_back(uninterpreted_options_field->number());
+
// Find the uninterpreted_option field in the original options.
const FieldDescriptor* original_uninterpreted_options_field =
original_options->GetDescriptor()->
@@ -6272,14 +6326,17 @@ bool DescriptorBuilder::OptionInterpreter::InterpretOptions(
const int num_uninterpreted_options = original_options->GetReflection()->
FieldSize(*original_options, original_uninterpreted_options_field);
for (int i = 0; i < num_uninterpreted_options; ++i) {
+ src_path.push_back(i);
uninterpreted_option_ = down_cast<const UninterpretedOption*>(
&original_options->GetReflection()->GetRepeatedMessage(
*original_options, original_uninterpreted_options_field, i));
- if (!InterpretSingleOption(options)) {
+ if (!InterpretSingleOption(options, src_path,
+ options_to_interpret->element_path)) {
// Error already added by InterpretSingleOption().
failed = true;
break;
}
+ src_path.pop_back();
}
// Reset these, so we don't have any dangling pointers.
uninterpreted_option_ = NULL;
@@ -6312,7 +6369,7 @@ bool DescriptorBuilder::OptionInterpreter::InterpretOptions(
}
bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption(
- Message* options) {
+ Message* options, std::vector<int>& src_path, std::vector<int>& opts_path) {
// First do some basic validation.
if (uninterpreted_option_->name_size() == 0) {
// This should never happen unless the parser has gone seriously awry or
@@ -6358,6 +6415,8 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption(
std::vector<const FieldDescriptor*> intermediate_fields;
string debug_msg_name = "";
+ std::vector<int> dest_path = opts_path;
+
for (int i = 0; i < uninterpreted_option_->name_size(); ++i) {
const string& name_part = uninterpreted_option_->name(i).name_part();
if (debug_msg_name.size() > 0) {
@@ -6420,19 +6479,24 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption(
"\" is not a field or extension of message \"" +
descriptor->name() + "\".");
}
- } else if (i < uninterpreted_option_->name_size() - 1) {
- if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
- 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 +
- "\" is a repeated message. Repeated message "
- "options must be initialized using an "
- "aggregate value.");
- } else {
- // Drill down into the submessage.
- intermediate_fields.push_back(field);
- descriptor = field->message_type();
+ } else {
+ // accumulate field numbers to form path to interpreted option
+ dest_path.push_back(field->number());
+
+ if (i < uninterpreted_option_->name_size() - 1) {
+ if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
+ 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 +
+ "\" is a repeated message. Repeated message "
+ "options must be initialized using an "
+ "aggregate value.");
+ } else {
+ // Drill down into the submessage.
+ intermediate_fields.push_back(field);
+ descriptor = field->message_type();
+ }
}
}
}
@@ -6453,10 +6517,9 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption(
return false; // ExamineIfOptionIsSet() already added the error.
}
-
// First set the value on the UnknownFieldSet corresponding to the
// innermost message.
- google::protobuf::scoped_ptr<UnknownFieldSet> unknown_fields(new UnknownFieldSet());
+ std::unique_ptr<UnknownFieldSet> unknown_fields(new UnknownFieldSet());
if (!SetOptionValue(field, unknown_fields.get())) {
return false; // SetOptionValue() already added the error.
}
@@ -6466,7 +6529,7 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption(
for (std::vector<const FieldDescriptor*>::reverse_iterator iter =
intermediate_fields.rbegin();
iter != intermediate_fields.rend(); ++iter) {
- google::protobuf::scoped_ptr<UnknownFieldSet> parent_unknown_fields(
+ std::unique_ptr<UnknownFieldSet> parent_unknown_fields(
new UnknownFieldSet());
switch ((*iter)->type()) {
case FieldDescriptor::TYPE_MESSAGE: {
@@ -6499,9 +6562,110 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption(
options->GetReflection()->MutableUnknownFields(options)->MergeFrom(
*unknown_fields);
+ // record the element path of the interpreted option
+ if (field->is_repeated()) {
+ int index = repeated_option_counts_[dest_path]++;
+ dest_path.push_back(index);
+ }
+ interpreted_paths_[src_path] = dest_path;
+
return true;
}
+void DescriptorBuilder::OptionInterpreter::UpdateSourceCodeInfo(
+ SourceCodeInfo* info) {
+
+ if (interpreted_paths_.empty()) {
+ // nothing to do!
+ return;
+ }
+
+ // We find locations that match keys in interpreted_paths_ and
+ // 1) replace the path with the corresponding value in interpreted_paths_
+ // 2) remove any subsequent sub-locations (sub-location is one whose path
+ // has the parent path as a prefix)
+ //
+ // To avoid quadratic behavior of removing interior rows as we go,
+ // we keep a copy. But we don't actually copy anything until we've
+ // found the first match (so if the source code info has no locations
+ // that need to be changed, there is zero copy overhead).
+
+ RepeatedPtrField<SourceCodeInfo_Location>* locs = info->mutable_location();
+ RepeatedPtrField<SourceCodeInfo_Location> new_locs;
+ bool copying = false;
+
+ std::vector<int> pathv;
+ bool matched = false;
+
+ 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;
+ if (loc->path_size() < pathv.size()) {
+ loc_matches = false;
+ } else {
+ for (int j = 0; j < pathv.size(); j++) {
+ if (loc->path(j) != pathv[j]) {
+ loc_matches = false;
+ break;
+ }
+ }
+ }
+
+ if (loc_matches) {
+ // don't copy this row since it is a sub-location that we're removing
+ continue;
+ }
+
+ matched = false;
+ }
+
+ pathv.clear();
+ for (int j = 0; j < loc->path_size(); j++) {
+ pathv.push_back(loc->path(j));
+ }
+
+ std::map<std::vector<int>, std::vector<int>>::iterator entry =
+ interpreted_paths_.find(pathv);
+
+ if (entry == interpreted_paths_.end()) {
+ // not a match
+ if (copying) {
+ new_locs.Add()->CopyFrom(*loc);
+ }
+ continue;
+ }
+
+ matched = true;
+
+ if (!copying) {
+ // initialize the copy we are building
+ copying = true;
+ new_locs.Reserve(locs->size());
+ for (RepeatedPtrField<SourceCodeInfo_Location>::iterator it =
+ locs->begin(); it != loc; it++) {
+ new_locs.Add()->CopyFrom(*it);
+ }
+ }
+
+ // add replacement and update its path
+ SourceCodeInfo_Location* replacement = new_locs.Add();
+ replacement->CopyFrom(*loc);
+ replacement->clear_path();
+ for (std::vector<int>::iterator rit = entry->second.begin();
+ rit != entry->second.end(); rit++) {
+ replacement->add_path(*rit);
+ }
+ }
+
+ // if we made a changed copy, put it in place
+ if (copying) {
+ *locs = new_locs;
+ }
+}
+
void DescriptorBuilder::OptionInterpreter::AddWithoutInterpreting(
const UninterpretedOption& uninterpreted_option, Message* options) {
const FieldDescriptor* field =
@@ -6785,7 +6949,7 @@ class DescriptorBuilder::OptionInterpreter::AggregateOptionFinder
DescriptorBuilder* builder_;
virtual const FieldDescriptor* FindExtension(
- Message* message, const string& name) const {
+ Message* message, const string& name) const override {
assert_mutex_held(builder_->pool_);
const Descriptor* descriptor = message->GetDescriptor();
Symbol result = builder_->LookupSymbolNoPlaceholder(
@@ -6823,7 +6987,7 @@ class AggregateErrorCollector : public io::ErrorCollector {
string error_;
virtual void AddError(int /* line */, int /* column */,
- const string& message) {
+ const string& message) override {
if (!error_.empty()) {
error_ += "; ";
}
@@ -6831,7 +6995,7 @@ class AggregateErrorCollector : public io::ErrorCollector {
}
virtual void AddWarning(int /* line */, int /* column */,
- const string& /* message */) {
+ const string& /* message */) override {
// Ignore warnings
}
};
@@ -6854,7 +7018,7 @@ bool DescriptorBuilder::OptionInterpreter::SetAggregateOption(
}
const Descriptor* type = option_field->message_type();
- google::protobuf::scoped_ptr<Message> dynamic(dynamic_factory_.GetPrototype(type)->New());
+ std::unique_ptr<Message> dynamic(dynamic_factory_.GetPrototype(type)->New());
GOOGLE_CHECK(dynamic.get() != NULL)
<< "Could not create an instance of " << option_field->DebugString();
diff --git a/src/google/protobuf/descriptor.h b/src/google/protobuf/descriptor.h
index 5f5159a8..115d4ddc 100644
--- a/src/google/protobuf/descriptor.h
+++ b/src/google/protobuf/descriptor.h
@@ -55,9 +55,6 @@
#define GOOGLE_PROTOBUF_DESCRIPTOR_H__
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <set>
#include <string>
#include <vector>
@@ -87,6 +84,7 @@ class DescriptorPool;
// Defined in descriptor.proto
class DescriptorProto;
+class DescriptorProto_ExtensionRange;
class FieldDescriptorProto;
class OneofDescriptorProto;
class EnumDescriptorProto;
@@ -340,6 +338,9 @@ class LIBPROTOBUF_EXPORT Descriptor {
struct ExtensionRange {
typedef ExtensionRangeOptions OptionsType;
+ // See Descriptor::CopyTo().
+ void CopyTo(DescriptorProto_ExtensionRange* proto) const;
+
int start; // inclusive
int end; // exclusive
@@ -1802,7 +1803,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool {
// This class contains a lot of hash maps with complicated types that
// we'd like to keep out of the header.
class Tables;
- google::protobuf::scoped_ptr<Tables> tables_;
+ std::unique_ptr<Tables> tables_;
bool enforce_dependencies_;
bool lazily_build_dependencies_;
diff --git a/src/google/protobuf/descriptor.pb.cc b/src/google/protobuf/descriptor.pb.cc
index c8362376..f3522ec1 100644
--- a/src/google/protobuf/descriptor.pb.cc
+++ b/src/google/protobuf/descriptor.pb.cc
@@ -7,7 +7,6 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
@@ -19,6 +18,34 @@
#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
namespace google {
namespace protobuf {
class FileDescriptorSetDefaultTypeInternal {
@@ -159,15 +186,9 @@ class GeneratedCodeInfoDefaultTypeInternal {
} // namespace protobuf
} // namespace google
namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto {
-void InitDefaultsFileDescriptorSetImpl() {
+static void InitDefaultsFileDescriptorSet() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto();
{
void* ptr = &::google::protobuf::_FileDescriptorSet_default_instance_;
new (ptr) ::google::protobuf::FileDescriptorSet();
@@ -176,25 +197,13 @@ void InitDefaultsFileDescriptorSetImpl() {
::google::protobuf::FileDescriptorSet::InitAsDefaultInstance();
}
-void InitDefaultsFileDescriptorSet() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFileDescriptorSetImpl);
-}
+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,}};
-void InitDefaultsFileDescriptorProtoImpl() {
+static void InitDefaultsFileDescriptorProto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto();
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto();
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto();
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto();
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions();
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo();
{
void* ptr = &::google::protobuf::_FileDescriptorProto_default_instance_;
new (ptr) ::google::protobuf::FileDescriptorProto();
@@ -203,20 +212,18 @@ void InitDefaultsFileDescriptorProtoImpl() {
::google::protobuf::FileDescriptorProto::InitAsDefaultInstance();
}
-void InitDefaultsFileDescriptorProto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFileDescriptorProtoImpl);
-}
+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,}};
-void InitDefaultsDescriptorProto_ExtensionRangeImpl() {
+static void InitDefaultsDescriptorProto_ExtensionRange() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions();
{
void* ptr = &::google::protobuf::_DescriptorProto_ExtensionRange_default_instance_;
new (ptr) ::google::protobuf::DescriptorProto_ExtensionRange();
@@ -225,19 +232,13 @@ void InitDefaultsDescriptorProto_ExtensionRangeImpl() {
::google::protobuf::DescriptorProto_ExtensionRange::InitAsDefaultInstance();
}
-void InitDefaultsDescriptorProto_ExtensionRange() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDescriptorProto_ExtensionRangeImpl);
-}
+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,}};
-void InitDefaultsDescriptorProto_ReservedRangeImpl() {
+static void InitDefaultsDescriptorProto_ReservedRange() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_DescriptorProto_ReservedRange_default_instance_;
new (ptr) ::google::protobuf::DescriptorProto_ReservedRange();
@@ -246,25 +247,12 @@ void InitDefaultsDescriptorProto_ReservedRangeImpl() {
::google::protobuf::DescriptorProto_ReservedRange::InitAsDefaultInstance();
}
-void InitDefaultsDescriptorProto_ReservedRange() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDescriptorProto_ReservedRangeImpl);
-}
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_DescriptorProto_ReservedRange =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDescriptorProto_ReservedRange}, {}};
-void InitDefaultsDescriptorProtoImpl() {
+static void InitDefaultsDescriptorProto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto();
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto();
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange();
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto();
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions();
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange();
{
void* ptr = &::google::protobuf::_DescriptorProto_default_instance_;
new (ptr) ::google::protobuf::DescriptorProto();
@@ -273,20 +261,18 @@ void InitDefaultsDescriptorProtoImpl() {
::google::protobuf::DescriptorProto::InitAsDefaultInstance();
}
-void InitDefaultsDescriptorProto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDescriptorProtoImpl);
-}
+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,}};
-void InitDefaultsExtensionRangeOptionsImpl() {
+static void InitDefaultsExtensionRangeOptions() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
{
void* ptr = &::google::protobuf::_ExtensionRangeOptions_default_instance_;
new (ptr) ::google::protobuf::ExtensionRangeOptions();
@@ -295,20 +281,13 @@ void InitDefaultsExtensionRangeOptionsImpl() {
::google::protobuf::ExtensionRangeOptions::InitAsDefaultInstance();
}
-void InitDefaultsExtensionRangeOptions() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsExtensionRangeOptionsImpl);
-}
+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,}};
-void InitDefaultsFieldDescriptorProtoImpl() {
+static void InitDefaultsFieldDescriptorProto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions();
{
void* ptr = &::google::protobuf::_FieldDescriptorProto_default_instance_;
new (ptr) ::google::protobuf::FieldDescriptorProto();
@@ -317,20 +296,13 @@ void InitDefaultsFieldDescriptorProtoImpl() {
::google::protobuf::FieldDescriptorProto::InitAsDefaultInstance();
}
-void InitDefaultsFieldDescriptorProto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldDescriptorProtoImpl);
-}
+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,}};
-void InitDefaultsOneofDescriptorProtoImpl() {
+static void InitDefaultsOneofDescriptorProto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions();
{
void* ptr = &::google::protobuf::_OneofDescriptorProto_default_instance_;
new (ptr) ::google::protobuf::OneofDescriptorProto();
@@ -339,19 +311,13 @@ void InitDefaultsOneofDescriptorProtoImpl() {
::google::protobuf::OneofDescriptorProto::InitAsDefaultInstance();
}
-void InitDefaultsOneofDescriptorProto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsOneofDescriptorProtoImpl);
-}
+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,}};
-void InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl() {
+static void InitDefaultsEnumDescriptorProto_EnumReservedRange() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_EnumDescriptorProto_EnumReservedRange_default_instance_;
new (ptr) ::google::protobuf::EnumDescriptorProto_EnumReservedRange();
@@ -360,22 +326,12 @@ void InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl() {
::google::protobuf::EnumDescriptorProto_EnumReservedRange::InitAsDefaultInstance();
}
-void InitDefaultsEnumDescriptorProto_EnumReservedRange() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl);
-}
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_EnumDescriptorProto_EnumReservedRange =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEnumDescriptorProto_EnumReservedRange}, {}};
-void InitDefaultsEnumDescriptorProtoImpl() {
+static void InitDefaultsEnumDescriptorProto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto();
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions();
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange();
{
void* ptr = &::google::protobuf::_EnumDescriptorProto_default_instance_;
new (ptr) ::google::protobuf::EnumDescriptorProto();
@@ -384,20 +340,15 @@ void InitDefaultsEnumDescriptorProtoImpl() {
::google::protobuf::EnumDescriptorProto::InitAsDefaultInstance();
}
-void InitDefaultsEnumDescriptorProto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumDescriptorProtoImpl);
-}
+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,}};
-void InitDefaultsEnumValueDescriptorProtoImpl() {
+static void InitDefaultsEnumValueDescriptorProto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions();
{
void* ptr = &::google::protobuf::_EnumValueDescriptorProto_default_instance_;
new (ptr) ::google::protobuf::EnumValueDescriptorProto();
@@ -406,21 +357,13 @@ void InitDefaultsEnumValueDescriptorProtoImpl() {
::google::protobuf::EnumValueDescriptorProto::InitAsDefaultInstance();
}
-void InitDefaultsEnumValueDescriptorProto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumValueDescriptorProtoImpl);
-}
+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,}};
-void InitDefaultsServiceDescriptorProtoImpl() {
+static void InitDefaultsServiceDescriptorProto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto();
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions();
{
void* ptr = &::google::protobuf::_ServiceDescriptorProto_default_instance_;
new (ptr) ::google::protobuf::ServiceDescriptorProto();
@@ -429,20 +372,14 @@ void InitDefaultsServiceDescriptorProtoImpl() {
::google::protobuf::ServiceDescriptorProto::InitAsDefaultInstance();
}
-void InitDefaultsServiceDescriptorProto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsServiceDescriptorProtoImpl);
-}
+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,}};
-void InitDefaultsMethodDescriptorProtoImpl() {
+static void InitDefaultsMethodDescriptorProto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions();
{
void* ptr = &::google::protobuf::_MethodDescriptorProto_default_instance_;
new (ptr) ::google::protobuf::MethodDescriptorProto();
@@ -451,20 +388,13 @@ void InitDefaultsMethodDescriptorProtoImpl() {
::google::protobuf::MethodDescriptorProto::InitAsDefaultInstance();
}
-void InitDefaultsMethodDescriptorProto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMethodDescriptorProtoImpl);
-}
+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,}};
-void InitDefaultsFileOptionsImpl() {
+static void InitDefaultsFileOptions() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
{
void* ptr = &::google::protobuf::_FileOptions_default_instance_;
new (ptr) ::google::protobuf::FileOptions();
@@ -473,20 +403,13 @@ void InitDefaultsFileOptionsImpl() {
::google::protobuf::FileOptions::InitAsDefaultInstance();
}
-void InitDefaultsFileOptions() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFileOptionsImpl);
-}
+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,}};
-void InitDefaultsMessageOptionsImpl() {
+static void InitDefaultsMessageOptions() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
{
void* ptr = &::google::protobuf::_MessageOptions_default_instance_;
new (ptr) ::google::protobuf::MessageOptions();
@@ -495,20 +418,13 @@ void InitDefaultsMessageOptionsImpl() {
::google::protobuf::MessageOptions::InitAsDefaultInstance();
}
-void InitDefaultsMessageOptions() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMessageOptionsImpl);
-}
+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,}};
-void InitDefaultsFieldOptionsImpl() {
+static void InitDefaultsFieldOptions() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
{
void* ptr = &::google::protobuf::_FieldOptions_default_instance_;
new (ptr) ::google::protobuf::FieldOptions();
@@ -517,20 +433,13 @@ void InitDefaultsFieldOptionsImpl() {
::google::protobuf::FieldOptions::InitAsDefaultInstance();
}
-void InitDefaultsFieldOptions() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldOptionsImpl);
-}
+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,}};
-void InitDefaultsOneofOptionsImpl() {
+static void InitDefaultsOneofOptions() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
{
void* ptr = &::google::protobuf::_OneofOptions_default_instance_;
new (ptr) ::google::protobuf::OneofOptions();
@@ -539,20 +448,13 @@ void InitDefaultsOneofOptionsImpl() {
::google::protobuf::OneofOptions::InitAsDefaultInstance();
}
-void InitDefaultsOneofOptions() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsOneofOptionsImpl);
-}
+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,}};
-void InitDefaultsEnumOptionsImpl() {
+static void InitDefaultsEnumOptions() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
{
void* ptr = &::google::protobuf::_EnumOptions_default_instance_;
new (ptr) ::google::protobuf::EnumOptions();
@@ -561,20 +463,13 @@ void InitDefaultsEnumOptionsImpl() {
::google::protobuf::EnumOptions::InitAsDefaultInstance();
}
-void InitDefaultsEnumOptions() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumOptionsImpl);
-}
+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,}};
-void InitDefaultsEnumValueOptionsImpl() {
+static void InitDefaultsEnumValueOptions() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
{
void* ptr = &::google::protobuf::_EnumValueOptions_default_instance_;
new (ptr) ::google::protobuf::EnumValueOptions();
@@ -583,20 +478,13 @@ void InitDefaultsEnumValueOptionsImpl() {
::google::protobuf::EnumValueOptions::InitAsDefaultInstance();
}
-void InitDefaultsEnumValueOptions() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumValueOptionsImpl);
-}
+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,}};
-void InitDefaultsServiceOptionsImpl() {
+static void InitDefaultsServiceOptions() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
{
void* ptr = &::google::protobuf::_ServiceOptions_default_instance_;
new (ptr) ::google::protobuf::ServiceOptions();
@@ -605,20 +493,13 @@ void InitDefaultsServiceOptionsImpl() {
::google::protobuf::ServiceOptions::InitAsDefaultInstance();
}
-void InitDefaultsServiceOptions() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsServiceOptionsImpl);
-}
+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,}};
-void InitDefaultsMethodOptionsImpl() {
+static void InitDefaultsMethodOptions() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
{
void* ptr = &::google::protobuf::_MethodOptions_default_instance_;
new (ptr) ::google::protobuf::MethodOptions();
@@ -627,19 +508,13 @@ void InitDefaultsMethodOptionsImpl() {
::google::protobuf::MethodOptions::InitAsDefaultInstance();
}
-void InitDefaultsMethodOptions() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMethodOptionsImpl);
-}
+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,}};
-void InitDefaultsUninterpretedOption_NamePartImpl() {
+static void InitDefaultsUninterpretedOption_NamePart() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_UninterpretedOption_NamePart_default_instance_;
new (ptr) ::google::protobuf::UninterpretedOption_NamePart();
@@ -648,20 +523,12 @@ void InitDefaultsUninterpretedOption_NamePartImpl() {
::google::protobuf::UninterpretedOption_NamePart::InitAsDefaultInstance();
}
-void InitDefaultsUninterpretedOption_NamePart() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsUninterpretedOption_NamePartImpl);
-}
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UninterpretedOption_NamePart =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsUninterpretedOption_NamePart}, {}};
-void InitDefaultsUninterpretedOptionImpl() {
+static void InitDefaultsUninterpretedOption() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart();
{
void* ptr = &::google::protobuf::_UninterpretedOption_default_instance_;
new (ptr) ::google::protobuf::UninterpretedOption();
@@ -670,19 +537,13 @@ void InitDefaultsUninterpretedOptionImpl() {
::google::protobuf::UninterpretedOption::InitAsDefaultInstance();
}
-void InitDefaultsUninterpretedOption() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsUninterpretedOptionImpl);
-}
+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,}};
-void InitDefaultsSourceCodeInfo_LocationImpl() {
+static void InitDefaultsSourceCodeInfo_Location() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_SourceCodeInfo_Location_default_instance_;
new (ptr) ::google::protobuf::SourceCodeInfo_Location();
@@ -691,20 +552,12 @@ void InitDefaultsSourceCodeInfo_LocationImpl() {
::google::protobuf::SourceCodeInfo_Location::InitAsDefaultInstance();
}
-void InitDefaultsSourceCodeInfo_Location() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSourceCodeInfo_LocationImpl);
-}
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_SourceCodeInfo_Location =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsSourceCodeInfo_Location}, {}};
-void InitDefaultsSourceCodeInfoImpl() {
+static void InitDefaultsSourceCodeInfo() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location();
{
void* ptr = &::google::protobuf::_SourceCodeInfo_default_instance_;
new (ptr) ::google::protobuf::SourceCodeInfo();
@@ -713,19 +566,13 @@ void InitDefaultsSourceCodeInfoImpl() {
::google::protobuf::SourceCodeInfo::InitAsDefaultInstance();
}
-void InitDefaultsSourceCodeInfo() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSourceCodeInfoImpl);
-}
+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,}};
-void InitDefaultsGeneratedCodeInfo_AnnotationImpl() {
+static void InitDefaultsGeneratedCodeInfo_Annotation() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_GeneratedCodeInfo_Annotation_default_instance_;
new (ptr) ::google::protobuf::GeneratedCodeInfo_Annotation();
@@ -734,20 +581,12 @@ void InitDefaultsGeneratedCodeInfo_AnnotationImpl() {
::google::protobuf::GeneratedCodeInfo_Annotation::InitAsDefaultInstance();
}
-void InitDefaultsGeneratedCodeInfo_Annotation() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsGeneratedCodeInfo_AnnotationImpl);
-}
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_GeneratedCodeInfo_Annotation =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsGeneratedCodeInfo_Annotation}, {}};
-void InitDefaultsGeneratedCodeInfoImpl() {
+static void InitDefaultsGeneratedCodeInfo() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation();
{
void* ptr = &::google::protobuf::_GeneratedCodeInfo_default_instance_;
new (ptr) ::google::protobuf::GeneratedCodeInfo();
@@ -756,9 +595,38 @@ void InitDefaultsGeneratedCodeInfoImpl() {
::google::protobuf::GeneratedCodeInfo::InitAsDefaultInstance();
}
-void InitDefaultsGeneratedCodeInfo() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsGeneratedCodeInfoImpl);
+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];
@@ -973,25 +841,29 @@ const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUT
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_),
0,
1,
- 9,
10,
11,
- 17,
- 2,
12,
+ 19,
+ 2,
13,
14,
15,
16,
- 8,
+ 17,
+ 18,
3,
4,
5,
6,
7,
+ 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_),
@@ -1159,20 +1031,20 @@ static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROT
{ 146, 154, sizeof(::google::protobuf::EnumValueDescriptorProto)},
{ 157, 165, sizeof(::google::protobuf::ServiceDescriptorProto)},
{ 168, 179, sizeof(::google::protobuf::MethodDescriptorProto)},
- { 185, 209, sizeof(::google::protobuf::FileOptions)},
- { 228, 238, sizeof(::google::protobuf::MessageOptions)},
- { 243, 255, sizeof(::google::protobuf::FieldOptions)},
- { 262, 268, sizeof(::google::protobuf::OneofOptions)},
- { 269, 277, sizeof(::google::protobuf::EnumOptions)},
- { 280, 287, sizeof(::google::protobuf::EnumValueOptions)},
- { 289, 296, sizeof(::google::protobuf::ServiceOptions)},
- { 298, 306, sizeof(::google::protobuf::MethodOptions)},
- { 309, 316, sizeof(::google::protobuf::UninterpretedOption_NamePart)},
- { 318, 330, sizeof(::google::protobuf::UninterpretedOption)},
- { 337, 347, sizeof(::google::protobuf::SourceCodeInfo_Location)},
- { 352, 358, sizeof(::google::protobuf::SourceCodeInfo)},
- { 359, 368, sizeof(::google::protobuf::GeneratedCodeInfo_Annotation)},
- { 372, 378, sizeof(::google::protobuf::GeneratedCodeInfo)},
+ { 185, 211, sizeof(::google::protobuf::FileOptions)},
+ { 232, 242, sizeof(::google::protobuf::MessageOptions)},
+ { 247, 259, sizeof(::google::protobuf::FieldOptions)},
+ { 266, 272, sizeof(::google::protobuf::OneofOptions)},
+ { 273, 281, sizeof(::google::protobuf::EnumOptions)},
+ { 284, 291, sizeof(::google::protobuf::EnumValueOptions)},
+ { 293, 300, sizeof(::google::protobuf::ServiceOptions)},
+ { 302, 310, sizeof(::google::protobuf::MethodOptions)},
+ { 313, 320, sizeof(::google::protobuf::UninterpretedOption_NamePart)},
+ { 322, 334, sizeof(::google::protobuf::UninterpretedOption)},
+ { 341, 351, sizeof(::google::protobuf::SourceCodeInfo_Location)},
+ { 356, 362, sizeof(::google::protobuf::SourceCodeInfo)},
+ { 363, 372, sizeof(::google::protobuf::GeneratedCodeInfo_Annotation)},
+ { 376, 382, sizeof(::google::protobuf::GeneratedCodeInfo)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
@@ -1205,17 +1077,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_GeneratedCodeInfo_default_instance_),
};
-void protobuf_AssignDescriptors() {
+static void protobuf_AssignDescriptors() {
AddDescriptors();
- ::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/descriptor.proto", schemas, file_default_instances, TableStruct::offsets, factory,
+ "google/protobuf/descriptor.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, file_level_enum_descriptors, NULL);
}
-void protobuf_AssignDescriptorsOnce() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
+static 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;
@@ -1224,7 +1095,7 @@ void protobuf_RegisterTypes(const ::std::string&) {
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 27);
}
-void AddDescriptorsImpl() {
+static void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n google/protobuf/descriptor.proto\022\017goog"
@@ -1300,7 +1171,7 @@ void AddDescriptorsImpl() {
"ut_type\030\003 \001(\t\022/\n\007options\030\004 \001(\0132\036.google."
"protobuf.MethodOptions\022\037\n\020client_streami"
"ng\030\005 \001(\010:\005false\022\037\n\020server_streaming\030\006 \001("
- "\010:\005false\"\360\005\n\013FileOptions\022\024\n\014java_package"
+ "\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"
@@ -1315,78 +1186,79 @@ void AddDescriptorsImpl() {
"\030\037 \001(\010:\005false\022\031\n\021objc_class_prefix\030$ \001(\t"
"\022\030\n\020csharp_namespace\030% \001(\t\022\024\n\014swift_pref"
"ix\030\' \001(\t\022\030\n\020php_class_prefix\030( \001(\t\022\025\n\rph"
- "p_namespace\030) \001(\t\022C\n\024uninterpreted_optio"
+ "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\":\n\014OptimizeMode\022\t\n\005SPEED\020\001\022\r\n\tCOD"
- "E_SIZE\020\002\022\020\n\014LITE_RUNTIME\020\003*\t\010\350\007\020\200\200\200\200\002J\004\010"
- "&\020\'\"\362\001\n\016MessageOptions\022&\n\027message_set_wi"
- "re_format\030\001 \001(\010:\005false\022.\n\037no_standard_de"
- "scriptor_accessor\030\002 \001(\010:\005false\022\031\n\ndeprec"
- "ated\030\003 \001(\010:\005false\022\021\n\tmap_entry\030\007 \001(\010\022C\n\024"
- "uninterpreted_option\030\347\007 \003(\0132$.google.pro"
- "tobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002J\004\010\010"
- "\020\tJ\004\010\t\020\n\"\236\003\n\014FieldOptions\022:\n\005ctype\030\001 \001(\016"
- "2#.google.protobuf.FieldOptions.CType:\006S"
- "TRING\022\016\n\006packed\030\002 \001(\010\022\?\n\006jstype\030\006 \001(\0162$."
- "google.protobuf.FieldOptions.JSType:\tJS_"
- "NORMAL\022\023\n\004lazy\030\005 \001(\010:\005false\022\031\n\ndeprecate"
- "d\030\003 \001(\010:\005false\022\023\n\004weak\030\n \001(\010:\005false\022C\n\024u"
- "ninterpreted_option\030\347\007 \003(\0132$.google.prot"
- "obuf.UninterpretedOption\"/\n\005CType\022\n\n\006STR"
- "ING\020\000\022\010\n\004CORD\020\001\022\020\n\014STRING_PIECE\020\002\"5\n\006JST"
- "ype\022\r\n\tJS_NORMAL\020\000\022\r\n\tJS_STRING\020\001\022\r\n\tJS_"
- "NUMBER\020\002*\t\010\350\007\020\200\200\200\200\002J\004\010\004\020\005\"^\n\014OneofOption"
- "s\022C\n\024uninterpreted_option\030\347\007 \003(\0132$.googl"
- "e.protobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200"
- "\002\"\223\001\n\013EnumOptions\022\023\n\013allow_alias\030\002 \001(\010\022\031"
- "\n\ndeprecated\030\003 \001(\010:\005false\022C\n\024uninterpret"
- "ed_option\030\347\007 \003(\0132$.google.protobuf.Unint"
- "erpretedOption*\t\010\350\007\020\200\200\200\200\002J\004\010\005\020\006\"}\n\020EnumV"
- "alueOptions\022\031\n\ndeprecated\030\001 \001(\010:\005false\022C"
- "\n\024uninterpreted_option\030\347\007 \003(\0132$.google.p"
- "rotobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\"{"
- "\n\016ServiceOptions\022\031\n\ndeprecated\030! \001(\010:\005fa"
- "lse\022C\n\024uninterpreted_option\030\347\007 \003(\0132$.goo"
- "gle.protobuf.UninterpretedOption*\t\010\350\007\020\200\200"
- "\200\200\002\"\255\002\n\rMethodOptions\022\031\n\ndeprecated\030! \001("
- "\010:\005false\022_\n\021idempotency_level\030\" \001(\0162/.go"
- "ogle.protobuf.MethodOptions.IdempotencyL"
- "evel:\023IDEMPOTENCY_UNKNOWN\022C\n\024uninterpret"
- "ed_option\030\347\007 \003(\0132$.google.protobuf.Unint"
- "erpretedOption\"P\n\020IdempotencyLevel\022\027\n\023ID"
- "EMPOTENCY_UNKNOWN\020\000\022\023\n\017NO_SIDE_EFFECTS\020\001"
- "\022\016\n\nIDEMPOTENT\020\002*\t\010\350\007\020\200\200\200\200\002\"\236\002\n\023Uninterp"
- "retedOption\022;\n\004name\030\002 \003(\0132-.google.proto"
- "buf.UninterpretedOption.NamePart\022\030\n\020iden"
- "tifier_value\030\003 \001(\t\022\032\n\022positive_int_value"
- "\030\004 \001(\004\022\032\n\022negative_int_value\030\005 \001(\003\022\024\n\014do"
- "uble_value\030\006 \001(\001\022\024\n\014string_value\030\007 \001(\014\022\027"
- "\n\017aggregate_value\030\010 \001(\t\0323\n\010NamePart\022\021\n\tn"
- "ame_part\030\001 \002(\t\022\024\n\014is_extension\030\002 \002(\010\"\325\001\n"
- "\016SourceCodeInfo\022:\n\010location\030\001 \003(\0132(.goog"
- "le.protobuf.SourceCodeInfo.Location\032\206\001\n\010"
- "Location\022\020\n\004path\030\001 \003(\005B\002\020\001\022\020\n\004span\030\002 \003(\005"
- "B\002\020\001\022\030\n\020leading_comments\030\003 \001(\t\022\031\n\021traili"
- "ng_comments\030\004 \001(\t\022!\n\031leading_detached_co"
- "mments\030\006 \003(\t\"\247\001\n\021GeneratedCodeInfo\022A\n\nan"
- "notation\030\001 \003(\0132-.google.protobuf.Generat"
- "edCodeInfo.Annotation\032O\n\nAnnotation\022\020\n\004p"
- "ath\030\001 \003(\005B\002\020\001\022\023\n\013source_file\030\002 \001(\t\022\r\n\005be"
- "gin\030\003 \001(\005\022\013\n\003end\030\004 \001(\005B\217\001\n\023com.google.pr"
- "otobufB\020DescriptorProtosH\001Z>github.com/g"
- "olang/protobuf/protoc-gen-go/descriptor;"
- "descriptor\370\001\001\242\002\003GPB\252\002\032Google.Protobuf.Re"
- "flection"
+ "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::DescriptorPool::InternalAddGeneratedFile(
- descriptor, 5968);
+ descriptor, 6022);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/descriptor.proto", &protobuf_RegisterTypes);
}
void AddDescriptors() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
+ 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 {
@@ -1576,9 +1448,8 @@ const int FileDescriptorSet::kFileFieldNumber;
FileDescriptorSet::FileDescriptorSet()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSet();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorSet.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorSet)
}
@@ -1586,7 +1457,7 @@ FileDescriptorSet::FileDescriptorSet(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
file_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSet();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorSet.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FileDescriptorSet)
@@ -1595,14 +1466,12 @@ FileDescriptorSet::FileDescriptorSet(const FileDescriptorSet& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
file_(from.file_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.FileDescriptorSet)
}
void FileDescriptorSet::SharedCtor() {
- _cached_size_ = 0;
}
FileDescriptorSet::~FileDescriptorSet() {
@@ -1618,12 +1487,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* FileDescriptorSet::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -1631,7 +1498,7 @@ const ::google::protobuf::Descriptor* FileDescriptorSet::descriptor() {
}
const FileDescriptorSet& FileDescriptorSet::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSet();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorSet.base);
return *internal_default_instance();
}
@@ -1653,7 +1520,7 @@ bool FileDescriptorSet::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.FileDescriptorSet)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -1755,9 +1622,7 @@ size_t FileDescriptorSet::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -1829,7 +1694,6 @@ void FileDescriptorSet::InternalSwap(FileDescriptorSet* other) {
CastToBase(&file_)->InternalSwap(CastToBase(&other->file_));
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata FileDescriptorSet::GetMetadata() const {
@@ -1889,9 +1753,8 @@ const int FileDescriptorProto::kSyntaxFieldNumber;
FileDescriptorProto::FileDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorProto)
}
@@ -1905,7 +1768,7 @@ FileDescriptorProto::FileDescriptorProto(::google::protobuf::Arena* arena)
extension_(arena),
public_dependency_(arena),
weak_dependency_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FileDescriptorProto)
@@ -1914,7 +1777,6 @@ FileDescriptorProto::FileDescriptorProto(const FileDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
dependency_(from.dependency_),
message_type_(from.message_type_),
enum_type_(from.enum_type_),
@@ -1952,7 +1814,6 @@ FileDescriptorProto::FileDescriptorProto(const FileDescriptorProto& from)
}
void FileDescriptorProto::SharedCtor() {
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
syntax_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -1979,12 +1840,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* FileDescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -1992,7 +1851,7 @@ const ::google::protobuf::Descriptor* FileDescriptorProto::descriptor() {
}
const FileDescriptorProto& FileDescriptorProto::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base);
return *internal_default_instance();
}
@@ -2013,16 +1872,13 @@ void FileDescriptorProto::Clear() {
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 31u) {
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
- GOOGLE_DCHECK(!package_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ package_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000004u) {
- GOOGLE_DCHECK(!syntax_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- syntax_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ syntax_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000008u) {
GOOGLE_DCHECK(options_ != NULL);
@@ -2043,7 +1899,7 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.FileDescriptorProto)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -2318,13 +2174,13 @@ void FileDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.FileOptions options = 8;
if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 8, *options_, output);
+ 8, this->_internal_options(), output);
}
// optional .google.protobuf.SourceCodeInfo source_code_info = 9;
if (cached_has_bits & 0x00000010u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 9, *source_code_info_, output);
+ 9, this->_internal_source_code_info(), output);
}
// repeated int32 public_dependency = 10;
@@ -2432,14 +2288,14 @@ void FileDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 8, *options_, deterministic, target);
+ 8, this->_internal_options(), deterministic, target);
}
// optional .google.protobuf.SourceCodeInfo source_code_info = 9;
if (cached_has_bits & 0x00000010u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 9, *source_code_info_, deterministic, target);
+ 9, this->_internal_source_code_info(), deterministic, target);
}
// repeated int32 public_dependency = 10;
@@ -2586,9 +2442,7 @@ size_t FileDescriptorProto::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -2694,14 +2548,16 @@ void FileDescriptorProto::InternalSwap(FileDescriptorProto* other) {
CastToBase(&extension_)->InternalSwap(CastToBase(&other->extension_));
public_dependency_.InternalSwap(&other->public_dependency_);
weak_dependency_.InternalSwap(&other->weak_dependency_);
- name_.Swap(&other->name_);
- package_.Swap(&other->package_);
- syntax_.Swap(&other->syntax_);
+ name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ package_.Swap(&other->package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ syntax_.Swap(&other->syntax_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ 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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata FileDescriptorProto::GetMetadata() const {
@@ -2737,16 +2593,15 @@ const int DescriptorProto_ExtensionRange::kOptionsFieldNumber;
DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange();
+ ::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)
@@ -2754,8 +2609,7 @@ DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(::google::protobu
DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(const DescriptorProto_ExtensionRange& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- _has_bits_(from._has_bits_),
- _cached_size_(0) {
+ _has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_options()) {
options_ = new ::google::protobuf::ExtensionRangeOptions(*from.options_);
@@ -2769,7 +2623,6 @@ DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(const DescriptorP
}
void DescriptorProto_ExtensionRange::SharedCtor() {
- _cached_size_ = 0;
::memset(&options_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&end_) -
reinterpret_cast<char*>(&options_)) + sizeof(end_));
@@ -2789,12 +2642,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* DescriptorProto_ExtensionRange::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -2802,7 +2653,7 @@ const ::google::protobuf::Descriptor* DescriptorProto_ExtensionRange::descriptor
}
const DescriptorProto_ExtensionRange& DescriptorProto_ExtensionRange::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base);
return *internal_default_instance();
}
@@ -2833,7 +2684,7 @@ bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto.ExtensionRange)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -2917,7 +2768,7 @@ void DescriptorProto_ExtensionRange::SerializeWithCachedSizes(
// optional .google.protobuf.ExtensionRangeOptions options = 3;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, *options_, output);
+ 3, this->_internal_options(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -2949,7 +2800,7 @@ void DescriptorProto_ExtensionRange::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 3, *options_, deterministic, target);
+ 3, this->_internal_options(), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -2993,9 +2844,7 @@ size_t DescriptorProto_ExtensionRange::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -3083,7 +2932,6 @@ void DescriptorProto_ExtensionRange::InternalSwap(DescriptorProto_ExtensionRange
swap(end_, other->end_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata DescriptorProto_ExtensionRange::GetMetadata() const {
@@ -3103,16 +2951,15 @@ const int DescriptorProto_ReservedRange::kEndFieldNumber;
DescriptorProto_ReservedRange::DescriptorProto_ReservedRange()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange();
+ ::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)
@@ -3120,8 +2967,7 @@ DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(::google::protobuf:
DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(const DescriptorProto_ReservedRange& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- _has_bits_(from._has_bits_),
- _cached_size_(0) {
+ _has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&start_, &from.start_,
static_cast<size_t>(reinterpret_cast<char*>(&end_) -
@@ -3130,7 +2976,6 @@ DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(const DescriptorPro
}
void DescriptorProto_ReservedRange::SharedCtor() {
- _cached_size_ = 0;
::memset(&start_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&end_) -
reinterpret_cast<char*>(&start_)) + sizeof(end_));
@@ -3149,12 +2994,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* DescriptorProto_ReservedRange::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -3162,7 +3005,7 @@ const ::google::protobuf::Descriptor* DescriptorProto_ReservedRange::descriptor(
}
const DescriptorProto_ReservedRange& DescriptorProto_ReservedRange::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base);
return *internal_default_instance();
}
@@ -3189,7 +3032,7 @@ bool DescriptorProto_ReservedRange::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto.ReservedRange)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -3317,9 +3160,7 @@ size_t DescriptorProto_ReservedRange::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -3400,7 +3241,6 @@ void DescriptorProto_ReservedRange::InternalSwap(DescriptorProto_ReservedRange*
swap(end_, other->end_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata DescriptorProto_ReservedRange::GetMetadata() const {
@@ -3443,9 +3283,8 @@ const int DescriptorProto::kReservedNameFieldNumber;
DescriptorProto::DescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto)
}
@@ -3460,7 +3299,7 @@ DescriptorProto::DescriptorProto(::google::protobuf::Arena* arena)
oneof_decl_(arena),
reserved_range_(arena),
reserved_name_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto)
@@ -3469,7 +3308,6 @@ DescriptorProto::DescriptorProto(const DescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
field_(from.field_),
nested_type_(from.nested_type_),
enum_type_(from.enum_type_),
@@ -3493,7 +3331,6 @@ DescriptorProto::DescriptorProto(const DescriptorProto& from)
}
void DescriptorProto::SharedCtor() {
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
}
@@ -3513,12 +3350,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* DescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -3526,7 +3361,7 @@ const ::google::protobuf::Descriptor* DescriptorProto::descriptor() {
}
const DescriptorProto& DescriptorProto::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base);
return *internal_default_instance();
}
@@ -3548,8 +3383,7 @@ void DescriptorProto::Clear() {
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 3u) {
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(options_ != NULL);
@@ -3566,7 +3400,7 @@ bool DescriptorProto::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -3784,7 +3618,7 @@ void DescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.MessageOptions options = 7;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 7, *options_, output);
+ 7, this->_internal_options(), output);
}
// repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;
@@ -3885,7 +3719,7 @@ void DescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 7, *options_, deterministic, target);
+ 7, this->_internal_options(), deterministic, target);
}
// repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;
@@ -4033,9 +3867,7 @@ size_t DescriptorProto::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -4136,11 +3968,11 @@ void DescriptorProto::InternalSwap(DescriptorProto* other) {
CastToBase(&oneof_decl_)->InternalSwap(CastToBase(&other->oneof_decl_));
CastToBase(&reserved_range_)->InternalSwap(CastToBase(&other->reserved_range_));
reserved_name_.InternalSwap(CastToBase(&other->reserved_name_));
- name_.Swap(&other->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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata DescriptorProto::GetMetadata() const {
@@ -4159,9 +3991,8 @@ const int ExtensionRangeOptions::kUninterpretedOptionFieldNumber;
ExtensionRangeOptions::ExtensionRangeOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.ExtensionRangeOptions)
}
@@ -4170,7 +4001,7 @@ ExtensionRangeOptions::ExtensionRangeOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.ExtensionRangeOptions)
@@ -4179,7 +4010,6 @@ ExtensionRangeOptions::ExtensionRangeOptions(const ExtensionRangeOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
uninterpreted_option_(from.uninterpreted_option_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
@@ -4187,7 +4017,6 @@ ExtensionRangeOptions::ExtensionRangeOptions(const ExtensionRangeOptions& from)
}
void ExtensionRangeOptions::SharedCtor() {
- _cached_size_ = 0;
}
ExtensionRangeOptions::~ExtensionRangeOptions() {
@@ -4203,12 +4032,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* ExtensionRangeOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -4216,7 +4043,7 @@ const ::google::protobuf::Descriptor* ExtensionRangeOptions::descriptor() {
}
const ExtensionRangeOptions& ExtensionRangeOptions::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base);
return *internal_default_instance();
}
@@ -4239,7 +4066,7 @@ bool ExtensionRangeOptions::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.ExtensionRangeOptions)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -4357,9 +4184,7 @@ size_t ExtensionRangeOptions::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -4436,7 +4261,6 @@ void ExtensionRangeOptions::InternalSwap(ExtensionRangeOptions* other) {
CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
@@ -4480,16 +4304,15 @@ const int FieldDescriptorProto::kOptionsFieldNumber;
FieldDescriptorProto::FieldDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FieldDescriptorProto)
@@ -4497,8 +4320,7 @@ FieldDescriptorProto::FieldDescriptorProto(::google::protobuf::Arena* arena)
FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- _has_bits_(from._has_bits_),
- _cached_size_(0) {
+ _has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name()) {
@@ -4537,7 +4359,6 @@ FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from)
}
void FieldDescriptorProto::SharedCtor() {
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
extendee_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
type_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -4569,12 +4390,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* FieldDescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -4582,7 +4401,7 @@ const ::google::protobuf::Descriptor* FieldDescriptorProto::descriptor() {
}
const FieldDescriptorProto& FieldDescriptorProto::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base);
return *internal_default_instance();
}
@@ -4596,24 +4415,19 @@ void FieldDescriptorProto::Clear() {
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 63u) {
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
- GOOGLE_DCHECK(!extendee_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- extendee_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ extendee_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000004u) {
- GOOGLE_DCHECK(!type_name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- type_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ type_name_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000008u) {
- GOOGLE_DCHECK(!default_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- default_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ default_value_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000010u) {
- GOOGLE_DCHECK(!json_name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- json_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ json_name_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000020u) {
GOOGLE_DCHECK(options_ != NULL);
@@ -4639,7 +4453,7 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.FieldDescriptorProto)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -4693,7 +4507,7 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
- int value;
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -4713,7 +4527,7 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
- int value;
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -4890,7 +4704,7 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.FieldOptions options = 8;
if (cached_has_bits & 0x00000020u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 8, *options_, output);
+ 8, this->_internal_options(), output);
}
// optional int32 oneof_index = 9;
@@ -4988,7 +4802,7 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000020u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 8, *options_, deterministic, target);
+ 8, this->_internal_options(), deterministic, target);
}
// optional int32 oneof_index = 9;
@@ -5097,9 +4911,7 @@ size_t FieldDescriptorProto::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -5206,11 +5018,16 @@ void FieldDescriptorProto::UnsafeArenaSwap(FieldDescriptorProto* other) {
}
void FieldDescriptorProto::InternalSwap(FieldDescriptorProto* other) {
using std::swap;
- name_.Swap(&other->name_);
- extendee_.Swap(&other->extendee_);
- type_name_.Swap(&other->type_name_);
- default_value_.Swap(&other->default_value_);
- json_name_.Swap(&other->json_name_);
+ name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ extendee_.Swap(&other->extendee_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ type_name_.Swap(&other->type_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ default_value_.Swap(&other->default_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ json_name_.Swap(&other->json_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
swap(options_, other->options_);
swap(number_, other->number_);
swap(oneof_index_, other->oneof_index_);
@@ -5218,7 +5035,6 @@ void FieldDescriptorProto::InternalSwap(FieldDescriptorProto* other) {
swap(type_, other->type_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata FieldDescriptorProto::GetMetadata() const {
@@ -5253,16 +5069,15 @@ const int OneofDescriptorProto::kOptionsFieldNumber;
OneofDescriptorProto::OneofDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.OneofDescriptorProto)
@@ -5270,8 +5085,7 @@ OneofDescriptorProto::OneofDescriptorProto(::google::protobuf::Arena* arena)
OneofDescriptorProto::OneofDescriptorProto(const OneofDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- _has_bits_(from._has_bits_),
- _cached_size_(0) {
+ _has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name()) {
@@ -5287,7 +5101,6 @@ OneofDescriptorProto::OneofDescriptorProto(const OneofDescriptorProto& from)
}
void OneofDescriptorProto::SharedCtor() {
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
}
@@ -5307,12 +5120,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* OneofDescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -5320,7 +5131,7 @@ const ::google::protobuf::Descriptor* OneofDescriptorProto::descriptor() {
}
const OneofDescriptorProto& OneofDescriptorProto::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base);
return *internal_default_instance();
}
@@ -5334,8 +5145,7 @@ void OneofDescriptorProto::Clear() {
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 3u) {
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(options_ != NULL);
@@ -5352,7 +5162,7 @@ bool OneofDescriptorProto::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.OneofDescriptorProto)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -5424,7 +5234,7 @@ void OneofDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.OneofOptions options = 2;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, *options_, output);
+ 2, this->_internal_options(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -5457,7 +5267,7 @@ void OneofDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 2, *options_, deterministic, target);
+ 2, this->_internal_options(), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -5494,9 +5304,7 @@ size_t OneofDescriptorProto::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -5575,11 +5383,11 @@ void OneofDescriptorProto::UnsafeArenaSwap(OneofDescriptorProto* other) {
}
void OneofDescriptorProto::InternalSwap(OneofDescriptorProto* other) {
using std::swap;
- name_.Swap(&other->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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata OneofDescriptorProto::GetMetadata() const {
@@ -5599,16 +5407,15 @@ const int EnumDescriptorProto_EnumReservedRange::kEndFieldNumber;
EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange();
+ ::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)
@@ -5616,8 +5423,7 @@ EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(::g
EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(const EnumDescriptorProto_EnumReservedRange& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- _has_bits_(from._has_bits_),
- _cached_size_(0) {
+ _has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&start_, &from.start_,
static_cast<size_t>(reinterpret_cast<char*>(&end_) -
@@ -5626,7 +5432,6 @@ EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(con
}
void EnumDescriptorProto_EnumReservedRange::SharedCtor() {
- _cached_size_ = 0;
::memset(&start_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&end_) -
reinterpret_cast<char*>(&start_)) + sizeof(end_));
@@ -5645,12 +5450,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* EnumDescriptorProto_EnumReservedRange::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -5658,7 +5461,7 @@ const ::google::protobuf::Descriptor* EnumDescriptorProto_EnumReservedRange::des
}
const EnumDescriptorProto_EnumReservedRange& EnumDescriptorProto_EnumReservedRange::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base);
return *internal_default_instance();
}
@@ -5685,7 +5488,7 @@ bool EnumDescriptorProto_EnumReservedRange::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.EnumDescriptorProto.EnumReservedRange)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -5813,9 +5616,7 @@ size_t EnumDescriptorProto_EnumReservedRange::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -5896,7 +5697,6 @@ void EnumDescriptorProto_EnumReservedRange::InternalSwap(EnumDescriptorProto_Enu
swap(end_, other->end_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata EnumDescriptorProto_EnumReservedRange::GetMetadata() const {
@@ -5934,9 +5734,8 @@ const int EnumDescriptorProto::kReservedNameFieldNumber;
EnumDescriptorProto::EnumDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumDescriptorProto)
}
@@ -5946,7 +5745,7 @@ EnumDescriptorProto::EnumDescriptorProto(::google::protobuf::Arena* arena)
value_(arena),
reserved_range_(arena),
reserved_name_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.EnumDescriptorProto)
@@ -5955,7 +5754,6 @@ EnumDescriptorProto::EnumDescriptorProto(const EnumDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
value_(from.value_),
reserved_range_(from.reserved_range_),
reserved_name_(from.reserved_name_) {
@@ -5974,7 +5772,6 @@ EnumDescriptorProto::EnumDescriptorProto(const EnumDescriptorProto& from)
}
void EnumDescriptorProto::SharedCtor() {
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
}
@@ -5994,12 +5791,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* EnumDescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -6007,7 +5802,7 @@ const ::google::protobuf::Descriptor* EnumDescriptorProto::descriptor() {
}
const EnumDescriptorProto& EnumDescriptorProto::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base);
return *internal_default_instance();
}
@@ -6024,8 +5819,7 @@ void EnumDescriptorProto::Clear() {
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 3u) {
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(options_ != NULL);
@@ -6042,7 +5836,7 @@ bool EnumDescriptorProto::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.EnumDescriptorProto)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -6164,7 +5958,7 @@ void EnumDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.EnumOptions options = 3;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, *options_, output);
+ 3, this->_internal_options(), output);
}
// repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;
@@ -6224,7 +6018,7 @@ void EnumDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 3, *options_, deterministic, target);
+ 3, this->_internal_options(), deterministic, target);
}
// repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;
@@ -6309,9 +6103,7 @@ size_t EnumDescriptorProto::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -6397,11 +6189,11 @@ void EnumDescriptorProto::InternalSwap(EnumDescriptorProto* other) {
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_);
+ 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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata EnumDescriptorProto::GetMetadata() const {
@@ -6437,16 +6229,15 @@ const int EnumValueDescriptorProto::kOptionsFieldNumber;
EnumValueDescriptorProto::EnumValueDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValueDescriptorProto)
@@ -6454,8 +6245,7 @@ EnumValueDescriptorProto::EnumValueDescriptorProto(::google::protobuf::Arena* ar
EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- _has_bits_(from._has_bits_),
- _cached_size_(0) {
+ _has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name()) {
@@ -6472,7 +6262,6 @@ EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProt
}
void EnumValueDescriptorProto::SharedCtor() {
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&options_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&number_) -
@@ -6494,12 +6283,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* EnumValueDescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -6507,7 +6294,7 @@ const ::google::protobuf::Descriptor* EnumValueDescriptorProto::descriptor() {
}
const EnumValueDescriptorProto& EnumValueDescriptorProto::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base);
return *internal_default_instance();
}
@@ -6521,8 +6308,7 @@ void EnumValueDescriptorProto::Clear() {
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 3u) {
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(options_ != NULL);
@@ -6540,7 +6326,7 @@ bool EnumValueDescriptorProto::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.EnumValueDescriptorProto)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -6631,7 +6417,7 @@ void EnumValueDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.EnumValueOptions options = 3;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, *options_, output);
+ 3, this->_internal_options(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -6669,7 +6455,7 @@ void EnumValueDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 3, *options_, deterministic, target);
+ 3, this->_internal_options(), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -6713,9 +6499,7 @@ size_t EnumValueDescriptorProto::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -6798,12 +6582,12 @@ void EnumValueDescriptorProto::UnsafeArenaSwap(EnumValueDescriptorProto* other)
}
void EnumValueDescriptorProto::InternalSwap(EnumValueDescriptorProto* other) {
using std::swap;
- name_.Swap(&other->name_);
+ 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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata EnumValueDescriptorProto::GetMetadata() const {
@@ -6839,9 +6623,8 @@ const int ServiceDescriptorProto::kOptionsFieldNumber;
ServiceDescriptorProto::ServiceDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.ServiceDescriptorProto)
}
@@ -6849,7 +6632,7 @@ ServiceDescriptorProto::ServiceDescriptorProto(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
method_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.ServiceDescriptorProto)
@@ -6858,7 +6641,6 @@ ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& fro
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
method_(from.method_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -6875,7 +6657,6 @@ ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& fro
}
void ServiceDescriptorProto::SharedCtor() {
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
}
@@ -6895,12 +6676,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* ServiceDescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -6908,7 +6687,7 @@ const ::google::protobuf::Descriptor* ServiceDescriptorProto::descriptor() {
}
const ServiceDescriptorProto& ServiceDescriptorProto::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base);
return *internal_default_instance();
}
@@ -6923,8 +6702,7 @@ void ServiceDescriptorProto::Clear() {
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 3u) {
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(options_ != NULL);
@@ -6941,7 +6719,7 @@ bool ServiceDescriptorProto::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.ServiceDescriptorProto)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -7034,7 +6812,7 @@ void ServiceDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.ServiceOptions options = 3;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, *options_, output);
+ 3, this->_internal_options(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -7075,7 +6853,7 @@ void ServiceDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 3, *options_, deterministic, target);
+ 3, this->_internal_options(), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -7123,9 +6901,7 @@ size_t ServiceDescriptorProto::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -7207,11 +6983,11 @@ void ServiceDescriptorProto::UnsafeArenaSwap(ServiceDescriptorProto* other) {
void ServiceDescriptorProto::InternalSwap(ServiceDescriptorProto* other) {
using std::swap;
CastToBase(&method_)->InternalSwap(CastToBase(&other->method_));
- name_.Swap(&other->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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata ServiceDescriptorProto::GetMetadata() const {
@@ -7250,16 +7026,15 @@ const int MethodDescriptorProto::kServerStreamingFieldNumber;
MethodDescriptorProto::MethodDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.MethodDescriptorProto)
@@ -7267,8 +7042,7 @@ MethodDescriptorProto::MethodDescriptorProto(::google::protobuf::Arena* arena)
MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- _has_bits_(from._has_bits_),
- _cached_size_(0) {
+ _has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name()) {
@@ -7297,7 +7071,6 @@ MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from)
}
void MethodDescriptorProto::SharedCtor() {
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
input_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
output_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -7323,12 +7096,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* MethodDescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -7336,7 +7107,7 @@ const ::google::protobuf::Descriptor* MethodDescriptorProto::descriptor() {
}
const MethodDescriptorProto& MethodDescriptorProto::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base);
return *internal_default_instance();
}
@@ -7350,16 +7121,13 @@ void MethodDescriptorProto::Clear() {
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 15u) {
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
- GOOGLE_DCHECK(!input_type_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- input_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ input_type_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000004u) {
- GOOGLE_DCHECK(!output_type_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- output_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ output_type_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000008u) {
GOOGLE_DCHECK(options_ != NULL);
@@ -7379,7 +7147,7 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.MethodDescriptorProto)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -7531,7 +7299,7 @@ void MethodDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.MethodOptions options = 4;
if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 4, *options_, output);
+ 4, this->_internal_options(), output);
}
// optional bool client_streaming = 5 [default = false];
@@ -7596,7 +7364,7 @@ void MethodDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 4, *options_, deterministic, target);
+ 4, this->_internal_options(), deterministic, target);
}
// optional bool client_streaming = 5 [default = false];
@@ -7667,9 +7435,7 @@ size_t MethodDescriptorProto::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -7761,15 +7527,17 @@ void MethodDescriptorProto::UnsafeArenaSwap(MethodDescriptorProto* other) {
}
void MethodDescriptorProto::InternalSwap(MethodDescriptorProto* other) {
using std::swap;
- name_.Swap(&other->name_);
- input_type_.Swap(&other->input_type_);
- output_type_.Swap(&other->output_type_);
+ name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ input_type_.Swap(&other->input_type_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ output_type_.Swap(&other->output_type_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata MethodDescriptorProto::GetMetadata() const {
@@ -7801,14 +7569,15 @@ const int FileOptions::kCsharpNamespaceFieldNumber;
const int FileOptions::kSwiftPrefixFieldNumber;
const int FileOptions::kPhpClassPrefixFieldNumber;
const int FileOptions::kPhpNamespaceFieldNumber;
+const int FileOptions::kPhpMetadataNamespaceFieldNumber;
+const int FileOptions::kRubyPackageFieldNumber;
const int FileOptions::kUninterpretedOptionFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
FileOptions::FileOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FileOptions)
}
@@ -7817,7 +7586,7 @@ FileOptions::FileOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FileOptions)
@@ -7826,7 +7595,6 @@ FileOptions::FileOptions(const FileOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
uninterpreted_option_(from.uninterpreted_option_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
@@ -7870,14 +7638,23 @@ FileOptions::FileOptions(const FileOptions& from)
php_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.php_namespace(),
GetArenaNoVirtual());
}
- ::memcpy(&cc_enable_arenas_, &from.cc_enable_arenas_,
+ php_metadata_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ if (from.has_php_metadata_namespace()) {
+ php_metadata_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.php_metadata_namespace(),
+ GetArenaNoVirtual());
+ }
+ ruby_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ if (from.has_ruby_package()) {
+ ruby_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.ruby_package(),
+ GetArenaNoVirtual());
+ }
+ ::memcpy(&java_multiple_files_, &from.java_multiple_files_,
static_cast<size_t>(reinterpret_cast<char*>(&optimize_for_) -
- reinterpret_cast<char*>(&cc_enable_arenas_)) + sizeof(optimize_for_));
+ reinterpret_cast<char*>(&java_multiple_files_)) + sizeof(optimize_for_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.FileOptions)
}
void FileOptions::SharedCtor() {
- _cached_size_ = 0;
java_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
java_outer_classname_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
go_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -7886,9 +7663,11 @@ void FileOptions::SharedCtor() {
swift_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
php_class_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
php_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(&cc_enable_arenas_, 0, static_cast<size_t>(
- reinterpret_cast<char*>(&deprecated_) -
- reinterpret_cast<char*>(&cc_enable_arenas_)) + sizeof(deprecated_));
+ php_metadata_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ ruby_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ ::memset(&java_multiple_files_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&cc_enable_arenas_) -
+ reinterpret_cast<char*>(&java_multiple_files_)) + sizeof(cc_enable_arenas_));
optimize_for_ = 1;
}
@@ -7907,18 +7686,18 @@ void FileOptions::SharedDtor() {
swift_prefix_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
php_class_prefix_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
php_namespace_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ php_metadata_namespace_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ ruby_package_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void FileOptions::ArenaDtor(void* object) {
FileOptions* _this = reinterpret_cast< FileOptions* >(object);
(void)_this;
}
-void FileOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void FileOptions::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void FileOptions::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* FileOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -7926,7 +7705,7 @@ const ::google::protobuf::Descriptor* FileOptions::descriptor() {
}
const FileOptions& FileOptions::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base);
return *internal_default_instance();
}
@@ -7942,45 +7721,47 @@ void FileOptions::Clear() {
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 255u) {
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!java_package_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- java_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ java_package_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
- GOOGLE_DCHECK(!java_outer_classname_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- java_outer_classname_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ java_outer_classname_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000004u) {
- GOOGLE_DCHECK(!go_package_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- go_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ go_package_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000008u) {
- GOOGLE_DCHECK(!objc_class_prefix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- objc_class_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ objc_class_prefix_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000010u) {
- GOOGLE_DCHECK(!csharp_namespace_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- csharp_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ csharp_namespace_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000020u) {
- GOOGLE_DCHECK(!swift_prefix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- swift_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ swift_prefix_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000040u) {
- GOOGLE_DCHECK(!php_class_prefix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- php_class_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ php_class_prefix_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000080u) {
- GOOGLE_DCHECK(!php_namespace_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- php_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ php_namespace_.ClearNonDefaultToEmpty();
}
}
- if (cached_has_bits & 65280u) {
- ::memset(&cc_enable_arenas_, 0, static_cast<size_t>(
- reinterpret_cast<char*>(&php_generic_services_) -
- reinterpret_cast<char*>(&cc_enable_arenas_)) + sizeof(php_generic_services_));
+ if (cached_has_bits & 768u) {
+ if (cached_has_bits & 0x00000100u) {
+ php_metadata_namespace_.ClearNonDefaultToEmpty();
+ }
+ if (cached_has_bits & 0x00000200u) {
+ ruby_package_.ClearNonDefaultToEmpty();
+ }
}
- if (cached_has_bits & 196608u) {
- deprecated_ = false;
+ if (cached_has_bits & 64512u) {
+ ::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) {
+ ::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_));
optimize_for_ = 1;
}
_has_bits_.Clear();
@@ -7993,7 +7774,7 @@ bool FileOptions::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.FileOptions)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -8033,7 +7814,7 @@ bool FileOptions::MergePartialFromCodedStream(
case 9: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(72u /* 72 & 0xFF */)) {
- int value;
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -8271,6 +8052,38 @@ bool FileOptions::MergePartialFromCodedStream(
break;
}
+ // optional string php_metadata_namespace = 44;
+ case 44: {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(98u /* 354 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadString(
+ input, this->mutable_php_metadata_namespace()));
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->php_metadata_namespace().data(), static_cast<int>(this->php_metadata_namespace().length()),
+ ::google::protobuf::internal::WireFormat::PARSE,
+ "google.protobuf.FileOptions.php_metadata_namespace");
+ } else {
+ goto handle_unusual;
+ }
+ break;
+ }
+
+ // optional string ruby_package = 45;
+ case 45: {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(106u /* 362 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadString(
+ input, this->mutable_ruby_package()));
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->ruby_package().data(), static_cast<int>(this->ruby_package().length()),
+ ::google::protobuf::internal::WireFormat::PARSE,
+ "google.protobuf.FileOptions.ruby_package");
+ } else {
+ goto handle_unusual;
+ }
+ break;
+ }
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
@@ -8337,13 +8150,13 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
- if (cached_has_bits & 0x00020000u) {
+ if (cached_has_bits & 0x00080000u) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
9, this->optimize_for(), output);
}
// optional bool java_multiple_files = 10 [default = false];
- if (cached_has_bits & 0x00000200u) {
+ if (cached_has_bits & 0x00000400u) {
::google::protobuf::internal::WireFormatLite::WriteBool(10, this->java_multiple_files(), output);
}
@@ -8358,37 +8171,37 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional bool cc_generic_services = 16 [default = false];
- if (cached_has_bits & 0x00001000u) {
+ if (cached_has_bits & 0x00002000u) {
::google::protobuf::internal::WireFormatLite::WriteBool(16, this->cc_generic_services(), output);
}
// optional bool java_generic_services = 17 [default = false];
- if (cached_has_bits & 0x00002000u) {
+ if (cached_has_bits & 0x00004000u) {
::google::protobuf::internal::WireFormatLite::WriteBool(17, this->java_generic_services(), output);
}
// optional bool py_generic_services = 18 [default = false];
- if (cached_has_bits & 0x00004000u) {
+ if (cached_has_bits & 0x00008000u) {
::google::protobuf::internal::WireFormatLite::WriteBool(18, this->py_generic_services(), output);
}
// optional bool java_generate_equals_and_hash = 20 [deprecated = true];
- if (cached_has_bits & 0x00000400u) {
+ if (cached_has_bits & 0x00000800u) {
::google::protobuf::internal::WireFormatLite::WriteBool(20, this->java_generate_equals_and_hash(), output);
}
// optional bool deprecated = 23 [default = false];
- if (cached_has_bits & 0x00010000u) {
+ if (cached_has_bits & 0x00020000u) {
::google::protobuf::internal::WireFormatLite::WriteBool(23, this->deprecated(), output);
}
// optional bool java_string_check_utf8 = 27 [default = false];
- if (cached_has_bits & 0x00000800u) {
+ if (cached_has_bits & 0x00001000u) {
::google::protobuf::internal::WireFormatLite::WriteBool(27, this->java_string_check_utf8(), output);
}
// optional bool cc_enable_arenas = 31 [default = false];
- if (cached_has_bits & 0x00000100u) {
+ if (cached_has_bits & 0x00040000u) {
::google::protobuf::internal::WireFormatLite::WriteBool(31, this->cc_enable_arenas(), output);
}
@@ -8443,10 +8256,30 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional bool php_generic_services = 42 [default = false];
- if (cached_has_bits & 0x00008000u) {
+ if (cached_has_bits & 0x00010000u) {
::google::protobuf::internal::WireFormatLite::WriteBool(42, this->php_generic_services(), output);
}
+ // optional string php_metadata_namespace = 44;
+ if (cached_has_bits & 0x00000100u) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->php_metadata_namespace().data(), static_cast<int>(this->php_metadata_namespace().length()),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "google.protobuf.FileOptions.php_metadata_namespace");
+ ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
+ 44, this->php_metadata_namespace(), output);
+ }
+
+ // optional string ruby_package = 45;
+ if (cached_has_bits & 0x00000200u) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->ruby_package().data(), static_cast<int>(this->ruby_package().length()),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "google.protobuf.FileOptions.ruby_package");
+ ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
+ 45, this->ruby_package(), output);
+ }
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
@@ -8498,13 +8331,13 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
- if (cached_has_bits & 0x00020000u) {
+ if (cached_has_bits & 0x00080000u) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
9, this->optimize_for(), target);
}
// optional bool java_multiple_files = 10 [default = false];
- if (cached_has_bits & 0x00000200u) {
+ if (cached_has_bits & 0x00000400u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(10, this->java_multiple_files(), target);
}
@@ -8520,37 +8353,37 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional bool cc_generic_services = 16 [default = false];
- if (cached_has_bits & 0x00001000u) {
+ if (cached_has_bits & 0x00002000u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(16, this->cc_generic_services(), target);
}
// optional bool java_generic_services = 17 [default = false];
- if (cached_has_bits & 0x00002000u) {
+ if (cached_has_bits & 0x00004000u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(17, this->java_generic_services(), target);
}
// optional bool py_generic_services = 18 [default = false];
- if (cached_has_bits & 0x00004000u) {
+ if (cached_has_bits & 0x00008000u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(18, this->py_generic_services(), target);
}
// optional bool java_generate_equals_and_hash = 20 [deprecated = true];
- if (cached_has_bits & 0x00000400u) {
+ if (cached_has_bits & 0x00000800u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(20, this->java_generate_equals_and_hash(), target);
}
// optional bool deprecated = 23 [default = false];
- if (cached_has_bits & 0x00010000u) {
+ if (cached_has_bits & 0x00020000u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(23, this->deprecated(), target);
}
// optional bool java_string_check_utf8 = 27 [default = false];
- if (cached_has_bits & 0x00000800u) {
+ if (cached_has_bits & 0x00001000u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(27, this->java_string_check_utf8(), target);
}
// optional bool cc_enable_arenas = 31 [default = false];
- if (cached_has_bits & 0x00000100u) {
+ if (cached_has_bits & 0x00040000u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(31, this->cc_enable_arenas(), target);
}
@@ -8610,10 +8443,32 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional bool php_generic_services = 42 [default = false];
- if (cached_has_bits & 0x00008000u) {
+ if (cached_has_bits & 0x00010000u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(42, this->php_generic_services(), target);
}
+ // optional string php_metadata_namespace = 44;
+ if (cached_has_bits & 0x00000100u) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->php_metadata_namespace().data(), static_cast<int>(this->php_metadata_namespace().length()),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "google.protobuf.FileOptions.php_metadata_namespace");
+ target =
+ ::google::protobuf::internal::WireFormatLite::WriteStringToArray(
+ 44, this->php_metadata_namespace(), target);
+ }
+
+ // optional string ruby_package = 45;
+ if (cached_has_bits & 0x00000200u) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->ruby_package().data(), static_cast<int>(this->ruby_package().length()),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "google.protobuf.FileOptions.ruby_package");
+ target =
+ ::google::protobuf::internal::WireFormatLite::WriteStringToArray(
+ 45, this->ruby_package(), target);
+ }
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
@@ -8715,9 +8570,18 @@ size_t FileOptions::ByteSizeLong() const {
}
if (_has_bits_[8 / 32] & 65280u) {
- // optional bool cc_enable_arenas = 31 [default = false];
- if (has_cc_enable_arenas()) {
- total_size += 2 + 1;
+ // optional string php_metadata_namespace = 44;
+ if (has_php_metadata_namespace()) {
+ total_size += 2 +
+ ::google::protobuf::internal::WireFormatLite::StringSize(
+ this->php_metadata_namespace());
+ }
+
+ // optional string ruby_package = 45;
+ if (has_ruby_package()) {
+ total_size += 2 +
+ ::google::protobuf::internal::WireFormatLite::StringSize(
+ this->ruby_package());
}
// optional bool java_multiple_files = 10 [default = false];
@@ -8750,18 +8614,23 @@ size_t FileOptions::ByteSizeLong() const {
total_size += 2 + 1;
}
+ }
+ if (_has_bits_[16 / 32] & 983040u) {
// optional bool php_generic_services = 42 [default = false];
if (has_php_generic_services()) {
total_size += 2 + 1;
}
- }
- if (_has_bits_[16 / 32] & 196608u) {
// optional bool deprecated = 23 [default = false];
if (has_deprecated()) {
total_size += 2 + 1;
}
+ // optional bool cc_enable_arenas = 31 [default = false];
+ if (has_cc_enable_arenas()) {
+ total_size += 2 + 1;
+ }
+
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
if (has_optimize_for()) {
total_size += 1 +
@@ -8770,9 +8639,7 @@ size_t FileOptions::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -8829,36 +8696,42 @@ void FileOptions::MergeFrom(const FileOptions& from) {
}
if (cached_has_bits & 65280u) {
if (cached_has_bits & 0x00000100u) {
- cc_enable_arenas_ = from.cc_enable_arenas_;
+ set_php_metadata_namespace(from.php_metadata_namespace());
}
if (cached_has_bits & 0x00000200u) {
- java_multiple_files_ = from.java_multiple_files_;
+ set_ruby_package(from.ruby_package());
}
if (cached_has_bits & 0x00000400u) {
- java_generate_equals_and_hash_ = from.java_generate_equals_and_hash_;
+ java_multiple_files_ = from.java_multiple_files_;
}
if (cached_has_bits & 0x00000800u) {
- java_string_check_utf8_ = from.java_string_check_utf8_;
+ java_generate_equals_and_hash_ = from.java_generate_equals_and_hash_;
}
if (cached_has_bits & 0x00001000u) {
- cc_generic_services_ = from.cc_generic_services_;
+ java_string_check_utf8_ = from.java_string_check_utf8_;
}
if (cached_has_bits & 0x00002000u) {
- java_generic_services_ = from.java_generic_services_;
+ cc_generic_services_ = from.cc_generic_services_;
}
if (cached_has_bits & 0x00004000u) {
- py_generic_services_ = from.py_generic_services_;
+ java_generic_services_ = from.java_generic_services_;
}
if (cached_has_bits & 0x00008000u) {
- php_generic_services_ = from.php_generic_services_;
+ py_generic_services_ = from.py_generic_services_;
}
_has_bits_[0] |= cached_has_bits;
}
- if (cached_has_bits & 196608u) {
+ if (cached_has_bits & 983040u) {
if (cached_has_bits & 0x00010000u) {
- deprecated_ = from.deprecated_;
+ php_generic_services_ = from.php_generic_services_;
}
if (cached_has_bits & 0x00020000u) {
+ deprecated_ = from.deprecated_;
+ }
+ if (cached_has_bits & 0x00040000u) {
+ cc_enable_arenas_ = from.cc_enable_arenas_;
+ }
+ if (cached_has_bits & 0x00080000u) {
optimize_for_ = from.optimize_for_;
}
_has_bits_[0] |= cached_has_bits;
@@ -8910,15 +8783,26 @@ void FileOptions::UnsafeArenaSwap(FileOptions* other) {
void FileOptions::InternalSwap(FileOptions* other) {
using std::swap;
CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
- java_package_.Swap(&other->java_package_);
- java_outer_classname_.Swap(&other->java_outer_classname_);
- go_package_.Swap(&other->go_package_);
- objc_class_prefix_.Swap(&other->objc_class_prefix_);
- csharp_namespace_.Swap(&other->csharp_namespace_);
- swift_prefix_.Swap(&other->swift_prefix_);
- php_class_prefix_.Swap(&other->php_class_prefix_);
- php_namespace_.Swap(&other->php_namespace_);
- swap(cc_enable_arenas_, other->cc_enable_arenas_);
+ java_package_.Swap(&other->java_package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ java_outer_classname_.Swap(&other->java_outer_classname_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ go_package_.Swap(&other->go_package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ objc_class_prefix_.Swap(&other->objc_class_prefix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ csharp_namespace_.Swap(&other->csharp_namespace_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ swift_prefix_.Swap(&other->swift_prefix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ php_class_prefix_.Swap(&other->php_class_prefix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ php_namespace_.Swap(&other->php_namespace_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ php_metadata_namespace_.Swap(&other->php_metadata_namespace_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ ruby_package_.Swap(&other->ruby_package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
swap(java_multiple_files_, other->java_multiple_files_);
swap(java_generate_equals_and_hash_, other->java_generate_equals_and_hash_);
swap(java_string_check_utf8_, other->java_string_check_utf8_);
@@ -8927,10 +8811,10 @@ void FileOptions::InternalSwap(FileOptions* other) {
swap(py_generic_services_, other->py_generic_services_);
swap(php_generic_services_, other->php_generic_services_);
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_);
- swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
@@ -8954,9 +8838,8 @@ const int MessageOptions::kUninterpretedOptionFieldNumber;
MessageOptions::MessageOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.MessageOptions)
}
@@ -8965,7 +8848,7 @@ MessageOptions::MessageOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.MessageOptions)
@@ -8974,7 +8857,6 @@ MessageOptions::MessageOptions(const MessageOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
uninterpreted_option_(from.uninterpreted_option_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
@@ -8985,7 +8867,6 @@ MessageOptions::MessageOptions(const MessageOptions& from)
}
void MessageOptions::SharedCtor() {
- _cached_size_ = 0;
::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_));
@@ -9004,12 +8885,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* MessageOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -9017,7 +8896,7 @@ const ::google::protobuf::Descriptor* MessageOptions::descriptor() {
}
const MessageOptions& MessageOptions::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base);
return *internal_default_instance();
}
@@ -9043,7 +8922,7 @@ bool MessageOptions::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.MessageOptions)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -9281,9 +9160,7 @@ size_t MessageOptions::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -9380,7 +9257,6 @@ void MessageOptions::InternalSwap(MessageOptions* other) {
swap(map_entry_, other->map_entry_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
@@ -9406,9 +9282,8 @@ const int FieldOptions::kUninterpretedOptionFieldNumber;
FieldOptions::FieldOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FieldOptions)
}
@@ -9417,7 +9292,7 @@ FieldOptions::FieldOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FieldOptions)
@@ -9426,7 +9301,6 @@ FieldOptions::FieldOptions(const FieldOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
uninterpreted_option_(from.uninterpreted_option_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
@@ -9437,7 +9311,6 @@ FieldOptions::FieldOptions(const FieldOptions& from)
}
void FieldOptions::SharedCtor() {
- _cached_size_ = 0;
::memset(&ctype_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&jstype_) -
reinterpret_cast<char*>(&ctype_)) + sizeof(jstype_));
@@ -9456,12 +9329,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* FieldOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -9469,7 +9340,7 @@ const ::google::protobuf::Descriptor* FieldOptions::descriptor() {
}
const FieldOptions& FieldOptions::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base);
return *internal_default_instance();
}
@@ -9498,7 +9369,7 @@ bool FieldOptions::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.FieldOptions)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -9506,7 +9377,7 @@ bool FieldOptions::MergePartialFromCodedStream(
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
- int value;
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -9568,7 +9439,7 @@ bool FieldOptions::MergePartialFromCodedStream(
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) {
- int value;
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -9812,9 +9683,7 @@ size_t FieldOptions::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -9919,7 +9788,6 @@ void FieldOptions::InternalSwap(FieldOptions* other) {
swap(jstype_, other->jstype_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
@@ -9939,9 +9807,8 @@ const int OneofOptions::kUninterpretedOptionFieldNumber;
OneofOptions::OneofOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.OneofOptions)
}
@@ -9950,7 +9817,7 @@ OneofOptions::OneofOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.OneofOptions)
@@ -9959,7 +9826,6 @@ OneofOptions::OneofOptions(const OneofOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
uninterpreted_option_(from.uninterpreted_option_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
@@ -9967,7 +9833,6 @@ OneofOptions::OneofOptions(const OneofOptions& from)
}
void OneofOptions::SharedCtor() {
- _cached_size_ = 0;
}
OneofOptions::~OneofOptions() {
@@ -9983,12 +9848,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* OneofOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -9996,7 +9859,7 @@ const ::google::protobuf::Descriptor* OneofOptions::descriptor() {
}
const OneofOptions& OneofOptions::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base);
return *internal_default_instance();
}
@@ -10019,7 +9882,7 @@ bool OneofOptions::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.OneofOptions)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -10137,9 +10000,7 @@ size_t OneofOptions::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -10216,7 +10077,6 @@ void OneofOptions::InternalSwap(OneofOptions* other) {
CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
@@ -10238,9 +10098,8 @@ const int EnumOptions::kUninterpretedOptionFieldNumber;
EnumOptions::EnumOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumOptions)
}
@@ -10249,7 +10108,7 @@ EnumOptions::EnumOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.EnumOptions)
@@ -10258,7 +10117,6 @@ EnumOptions::EnumOptions(const EnumOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
uninterpreted_option_(from.uninterpreted_option_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
@@ -10269,7 +10127,6 @@ EnumOptions::EnumOptions(const EnumOptions& from)
}
void EnumOptions::SharedCtor() {
- _cached_size_ = 0;
::memset(&allow_alias_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&deprecated_) -
reinterpret_cast<char*>(&allow_alias_)) + sizeof(deprecated_));
@@ -10288,12 +10145,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* EnumOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -10301,7 +10156,7 @@ const ::google::protobuf::Descriptor* EnumOptions::descriptor() {
}
const EnumOptions& EnumOptions::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base);
return *internal_default_instance();
}
@@ -10327,7 +10182,7 @@ bool EnumOptions::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.EnumOptions)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -10507,9 +10362,7 @@ size_t EnumOptions::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -10598,7 +10451,6 @@ void EnumOptions::InternalSwap(EnumOptions* other) {
swap(deprecated_, other->deprecated_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
@@ -10619,9 +10471,8 @@ const int EnumValueOptions::kUninterpretedOptionFieldNumber;
EnumValueOptions::EnumValueOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumValueOptions)
}
@@ -10630,7 +10481,7 @@ EnumValueOptions::EnumValueOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValueOptions)
@@ -10639,7 +10490,6 @@ EnumValueOptions::EnumValueOptions(const EnumValueOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
uninterpreted_option_(from.uninterpreted_option_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
@@ -10648,7 +10498,6 @@ EnumValueOptions::EnumValueOptions(const EnumValueOptions& from)
}
void EnumValueOptions::SharedCtor() {
- _cached_size_ = 0;
deprecated_ = false;
}
@@ -10665,12 +10514,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* EnumValueOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -10678,7 +10525,7 @@ const ::google::protobuf::Descriptor* EnumValueOptions::descriptor() {
}
const EnumValueOptions& EnumValueOptions::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base);
return *internal_default_instance();
}
@@ -10702,7 +10549,7 @@ bool EnumValueOptions::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.EnumValueOptions)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -10851,9 +10698,7 @@ size_t EnumValueOptions::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -10934,7 +10779,6 @@ void EnumValueOptions::InternalSwap(EnumValueOptions* other) {
swap(deprecated_, other->deprecated_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
@@ -10955,9 +10799,8 @@ const int ServiceOptions::kUninterpretedOptionFieldNumber;
ServiceOptions::ServiceOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.ServiceOptions)
}
@@ -10966,7 +10809,7 @@ ServiceOptions::ServiceOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.ServiceOptions)
@@ -10975,7 +10818,6 @@ ServiceOptions::ServiceOptions(const ServiceOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
uninterpreted_option_(from.uninterpreted_option_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
@@ -10984,7 +10826,6 @@ ServiceOptions::ServiceOptions(const ServiceOptions& from)
}
void ServiceOptions::SharedCtor() {
- _cached_size_ = 0;
deprecated_ = false;
}
@@ -11001,12 +10842,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* ServiceOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -11014,7 +10853,7 @@ const ::google::protobuf::Descriptor* ServiceOptions::descriptor() {
}
const ServiceOptions& ServiceOptions::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base);
return *internal_default_instance();
}
@@ -11038,7 +10877,7 @@ bool ServiceOptions::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.ServiceOptions)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -11187,9 +11026,7 @@ size_t ServiceOptions::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -11270,7 +11107,6 @@ void ServiceOptions::InternalSwap(ServiceOptions* other) {
swap(deprecated_, other->deprecated_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
@@ -11292,9 +11128,8 @@ const int MethodOptions::kUninterpretedOptionFieldNumber;
MethodOptions::MethodOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.MethodOptions)
}
@@ -11303,7 +11138,7 @@ MethodOptions::MethodOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.MethodOptions)
@@ -11312,7 +11147,6 @@ MethodOptions::MethodOptions(const MethodOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
uninterpreted_option_(from.uninterpreted_option_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
@@ -11323,7 +11157,6 @@ MethodOptions::MethodOptions(const MethodOptions& from)
}
void MethodOptions::SharedCtor() {
- _cached_size_ = 0;
::memset(&deprecated_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&idempotency_level_) -
reinterpret_cast<char*>(&deprecated_)) + sizeof(idempotency_level_));
@@ -11342,12 +11175,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* MethodOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -11355,7 +11186,7 @@ const ::google::protobuf::Descriptor* MethodOptions::descriptor() {
}
const MethodOptions& MethodOptions::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base);
return *internal_default_instance();
}
@@ -11384,7 +11215,7 @@ bool MethodOptions::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.MethodOptions)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -11406,7 +11237,7 @@ bool MethodOptions::MergePartialFromCodedStream(
case 34: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 272 & 0xFF */)) {
- int value;
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -11573,9 +11404,7 @@ size_t MethodOptions::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -11664,7 +11493,6 @@ void MethodOptions::InternalSwap(MethodOptions* other) {
swap(idempotency_level_, other->idempotency_level_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
@@ -11685,16 +11513,15 @@ const int UninterpretedOption_NamePart::kIsExtensionFieldNumber;
UninterpretedOption_NamePart::UninterpretedOption_NamePart()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart();
+ ::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)
@@ -11702,8 +11529,7 @@ UninterpretedOption_NamePart::UninterpretedOption_NamePart(::google::protobuf::A
UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOption_NamePart& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- _has_bits_(from._has_bits_),
- _cached_size_(0) {
+ _has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_part_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name_part()) {
@@ -11715,7 +11541,6 @@ UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOp
}
void UninterpretedOption_NamePart::SharedCtor() {
- _cached_size_ = 0;
name_part_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
is_extension_ = false;
}
@@ -11734,12 +11559,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* UninterpretedOption_NamePart::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -11747,7 +11570,7 @@ const ::google::protobuf::Descriptor* UninterpretedOption_NamePart::descriptor()
}
const UninterpretedOption_NamePart& UninterpretedOption_NamePart::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base);
return *internal_default_instance();
}
@@ -11760,8 +11583,7 @@ void UninterpretedOption_NamePart::Clear() {
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!name_part_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- name_part_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_part_.ClearNonDefaultToEmpty();
}
is_extension_ = false;
_has_bits_.Clear();
@@ -11774,7 +11596,7 @@ bool UninterpretedOption_NamePart::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.UninterpretedOption.NamePart)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -11929,9 +11751,7 @@ size_t UninterpretedOption_NamePart::ByteSizeLong() const {
total_size += RequiredFieldsByteSizeFallback();
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -12009,11 +11829,11 @@ void UninterpretedOption_NamePart::UnsafeArenaSwap(UninterpretedOption_NamePart*
}
void UninterpretedOption_NamePart::InternalSwap(UninterpretedOption_NamePart* other) {
using std::swap;
- name_part_.Swap(&other->name_part_);
+ 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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata UninterpretedOption_NamePart::GetMetadata() const {
@@ -12038,9 +11858,8 @@ const int UninterpretedOption::kAggregateValueFieldNumber;
UninterpretedOption::UninterpretedOption()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.UninterpretedOption)
}
@@ -12048,7 +11867,7 @@ UninterpretedOption::UninterpretedOption(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
name_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.UninterpretedOption)
@@ -12057,7 +11876,6 @@ UninterpretedOption::UninterpretedOption(const UninterpretedOption& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
name_(from.name_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
identifier_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -12082,7 +11900,6 @@ UninterpretedOption::UninterpretedOption(const UninterpretedOption& from)
}
void UninterpretedOption::SharedCtor() {
- _cached_size_ = 0;
identifier_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
aggregate_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -12107,12 +11924,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* UninterpretedOption::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -12120,7 +11935,7 @@ const ::google::protobuf::Descriptor* UninterpretedOption::descriptor() {
}
const UninterpretedOption& UninterpretedOption::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base);
return *internal_default_instance();
}
@@ -12135,16 +11950,13 @@ void UninterpretedOption::Clear() {
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 7u) {
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!identifier_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- identifier_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ identifier_value_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
- GOOGLE_DCHECK(!string_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- string_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ string_value_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000004u) {
- GOOGLE_DCHECK(!aggregate_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- aggregate_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ aggregate_value_.ClearNonDefaultToEmpty();
}
}
if (cached_has_bits & 56u) {
@@ -12162,7 +11974,7 @@ bool UninterpretedOption::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.UninterpretedOption)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -12479,9 +12291,7 @@ size_t UninterpretedOption::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -12573,15 +12383,17 @@ void UninterpretedOption::UnsafeArenaSwap(UninterpretedOption* other) {
void UninterpretedOption::InternalSwap(UninterpretedOption* other) {
using std::swap;
CastToBase(&name_)->InternalSwap(CastToBase(&other->name_));
- identifier_value_.Swap(&other->identifier_value_);
- string_value_.Swap(&other->string_value_);
- aggregate_value_.Swap(&other->aggregate_value_);
+ identifier_value_.Swap(&other->identifier_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ string_value_.Swap(&other->string_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ aggregate_value_.Swap(&other->aggregate_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata UninterpretedOption::GetMetadata() const {
@@ -12604,9 +12416,8 @@ const int SourceCodeInfo_Location::kLeadingDetachedCommentsFieldNumber;
SourceCodeInfo_Location::SourceCodeInfo_Location()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo.Location)
}
@@ -12616,7 +12427,7 @@ SourceCodeInfo_Location::SourceCodeInfo_Location(::google::protobuf::Arena* aren
path_(arena),
span_(arena),
leading_detached_comments_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location();
+ ::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)
@@ -12625,7 +12436,6 @@ SourceCodeInfo_Location::SourceCodeInfo_Location(const SourceCodeInfo_Location&
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
path_(from.path_),
span_(from.span_),
leading_detached_comments_(from.leading_detached_comments_) {
@@ -12644,7 +12454,6 @@ SourceCodeInfo_Location::SourceCodeInfo_Location(const SourceCodeInfo_Location&
}
void SourceCodeInfo_Location::SharedCtor() {
- _cached_size_ = 0;
leading_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
trailing_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -12664,12 +12473,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* SourceCodeInfo_Location::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -12677,7 +12484,7 @@ const ::google::protobuf::Descriptor* SourceCodeInfo_Location::descriptor() {
}
const SourceCodeInfo_Location& SourceCodeInfo_Location::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base);
return *internal_default_instance();
}
@@ -12694,12 +12501,10 @@ void SourceCodeInfo_Location::Clear() {
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 3u) {
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!leading_comments_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- leading_comments_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ leading_comments_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
- GOOGLE_DCHECK(!trailing_comments_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- trailing_comments_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ trailing_comments_.ClearNonDefaultToEmpty();
}
}
_has_bits_.Clear();
@@ -12712,7 +12517,7 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.SourceCodeInfo.Location)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -13029,9 +12834,7 @@ size_t SourceCodeInfo_Location::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -13113,11 +12916,12 @@ void SourceCodeInfo_Location::InternalSwap(SourceCodeInfo_Location* other) {
path_.InternalSwap(&other->path_);
span_.InternalSwap(&other->span_);
leading_detached_comments_.InternalSwap(CastToBase(&other->leading_detached_comments_));
- leading_comments_.Swap(&other->leading_comments_);
- trailing_comments_.Swap(&other->trailing_comments_);
+ leading_comments_.Swap(&other->leading_comments_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ 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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata SourceCodeInfo_Location::GetMetadata() const {
@@ -13136,9 +12940,8 @@ const int SourceCodeInfo::kLocationFieldNumber;
SourceCodeInfo::SourceCodeInfo()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo)
}
@@ -13146,7 +12949,7 @@ SourceCodeInfo::SourceCodeInfo(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
location_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.SourceCodeInfo)
@@ -13155,14 +12958,12 @@ SourceCodeInfo::SourceCodeInfo(const SourceCodeInfo& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
location_(from.location_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.SourceCodeInfo)
}
void SourceCodeInfo::SharedCtor() {
- _cached_size_ = 0;
}
SourceCodeInfo::~SourceCodeInfo() {
@@ -13178,12 +12979,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* SourceCodeInfo::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -13191,7 +12990,7 @@ const ::google::protobuf::Descriptor* SourceCodeInfo::descriptor() {
}
const SourceCodeInfo& SourceCodeInfo::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base);
return *internal_default_instance();
}
@@ -13213,7 +13012,7 @@ bool SourceCodeInfo::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.SourceCodeInfo)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -13315,9 +13114,7 @@ size_t SourceCodeInfo::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -13388,7 +13185,6 @@ void SourceCodeInfo::InternalSwap(SourceCodeInfo* other) {
CastToBase(&location_)->InternalSwap(CastToBase(&other->location_));
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata SourceCodeInfo::GetMetadata() const {
@@ -13410,9 +13206,8 @@ const int GeneratedCodeInfo_Annotation::kEndFieldNumber;
GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo.Annotation)
}
@@ -13420,7 +13215,7 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(::google::protobuf::A
: ::google::protobuf::Message(),
_internal_metadata_(arena),
path_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation();
+ ::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)
@@ -13429,7 +13224,6 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(const GeneratedCodeIn
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
path_(from.path_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
source_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -13444,7 +13238,6 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(const GeneratedCodeIn
}
void GeneratedCodeInfo_Annotation::SharedCtor() {
- _cached_size_ = 0;
source_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&begin_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&end_) -
@@ -13465,12 +13258,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* GeneratedCodeInfo_Annotation::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -13478,7 +13269,7 @@ const ::google::protobuf::Descriptor* GeneratedCodeInfo_Annotation::descriptor()
}
const GeneratedCodeInfo_Annotation& GeneratedCodeInfo_Annotation::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base);
return *internal_default_instance();
}
@@ -13492,8 +13283,7 @@ void GeneratedCodeInfo_Annotation::Clear() {
path_.Clear();
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
- GOOGLE_DCHECK(!source_file_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- source_file_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ source_file_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 6u) {
::memset(&begin_, 0, static_cast<size_t>(
@@ -13510,7 +13300,7 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.GeneratedCodeInfo.Annotation)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -13741,9 +13531,7 @@ size_t GeneratedCodeInfo_Annotation::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -13825,12 +13613,12 @@ void GeneratedCodeInfo_Annotation::UnsafeArenaSwap(GeneratedCodeInfo_Annotation*
void GeneratedCodeInfo_Annotation::InternalSwap(GeneratedCodeInfo_Annotation* other) {
using std::swap;
path_.InternalSwap(&other->path_);
- source_file_.Swap(&other->source_file_);
+ 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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata GeneratedCodeInfo_Annotation::GetMetadata() const {
@@ -13849,9 +13637,8 @@ const int GeneratedCodeInfo::kAnnotationFieldNumber;
GeneratedCodeInfo::GeneratedCodeInfo()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo)
}
@@ -13859,7 +13646,7 @@ GeneratedCodeInfo::GeneratedCodeInfo(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
annotation_(arena) {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.GeneratedCodeInfo)
@@ -13868,14 +13655,12 @@ GeneratedCodeInfo::GeneratedCodeInfo(const GeneratedCodeInfo& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
- _cached_size_(0),
annotation_(from.annotation_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.GeneratedCodeInfo)
}
void GeneratedCodeInfo::SharedCtor() {
- _cached_size_ = 0;
}
GeneratedCodeInfo::~GeneratedCodeInfo() {
@@ -13891,12 +13676,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* GeneratedCodeInfo::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -13904,7 +13687,7 @@ const ::google::protobuf::Descriptor* GeneratedCodeInfo::descriptor() {
}
const GeneratedCodeInfo& GeneratedCodeInfo::default_instance() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo.base);
return *internal_default_instance();
}
@@ -13926,7 +13709,7 @@ bool GeneratedCodeInfo::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.GeneratedCodeInfo)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -14028,9 +13811,7 @@ size_t GeneratedCodeInfo::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -14101,7 +13882,6 @@ void GeneratedCodeInfo::InternalSwap(GeneratedCodeInfo* other) {
CastToBase(&annotation_)->InternalSwap(CastToBase(&other->annotation_));
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata GeneratedCodeInfo::GetMetadata() const {
@@ -14115,85 +13895,85 @@ void GeneratedCodeInfo::InternalSwap(GeneratedCodeInfo* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileDescriptorSet* Arena::CreateMessage< ::google::protobuf::FileDescriptorSet >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::FileDescriptorProto >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::DescriptorProto_ExtensionRange >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::DescriptorProto_ReservedRange >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::DescriptorProto >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::ExtensionRangeOptions >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::FieldDescriptorProto >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::OneofDescriptorProto >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::EnumDescriptorProto >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::EnumValueDescriptorProto >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::ServiceDescriptorProto >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::MethodDescriptorProto >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::FileOptions >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::MessageOptions >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::FieldOptions >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::OneofOptions >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::EnumOptions >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::EnumValueOptions >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::ServiceOptions >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::MethodOptions >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::UninterpretedOption_NamePart >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::UninterpretedOption >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::SourceCodeInfo_Location >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::SourceCodeInfo >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::GeneratedCodeInfo_Annotation >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::GeneratedCodeInfo >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::GeneratedCodeInfo >(arena);
}
} // namespace protobuf
diff --git a/src/google/protobuf/descriptor.pb.h b/src/google/protobuf/descriptor.pb.h
index 4ec0a5b4..7a8617a2 100644
--- a/src/google/protobuf/descriptor.pb.h
+++ b/src/google/protobuf/descriptor.pb.h
@@ -1,19 +1,19 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/descriptor.proto
-#ifndef PROTOBUF_google_2fprotobuf_2fdescriptor_2eproto_INCLUDED
-#define PROTOBUF_google_2fprotobuf_2fdescriptor_2eproto_INCLUDED
+#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto
+#define PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3005000
+#if GOOGLE_PROTOBUF_VERSION < 3006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3005001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -24,6 +24,7 @@
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -31,6 +32,7 @@
#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
namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto {
// Internal implementation detail -- do not use these members.
@@ -43,89 +45,6 @@ struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::uint32 offsets[];
};
void LIBPROTOBUF_EXPORT AddDescriptors();
-void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorSetImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorSet();
-void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorProtoImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorProto();
-void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ExtensionRangeImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ExtensionRange();
-void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ReservedRangeImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ReservedRange();
-void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProtoImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto();
-void LIBPROTOBUF_EXPORT InitDefaultsExtensionRangeOptionsImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsExtensionRangeOptions();
-void LIBPROTOBUF_EXPORT InitDefaultsFieldDescriptorProtoImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsFieldDescriptorProto();
-void LIBPROTOBUF_EXPORT InitDefaultsOneofDescriptorProtoImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsOneofDescriptorProto();
-void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProto_EnumReservedRange();
-void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProtoImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProto();
-void LIBPROTOBUF_EXPORT InitDefaultsEnumValueDescriptorProtoImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsEnumValueDescriptorProto();
-void LIBPROTOBUF_EXPORT InitDefaultsServiceDescriptorProtoImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsServiceDescriptorProto();
-void LIBPROTOBUF_EXPORT InitDefaultsMethodDescriptorProtoImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsMethodDescriptorProto();
-void LIBPROTOBUF_EXPORT InitDefaultsFileOptionsImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsFileOptions();
-void LIBPROTOBUF_EXPORT InitDefaultsMessageOptionsImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsMessageOptions();
-void LIBPROTOBUF_EXPORT InitDefaultsFieldOptionsImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsFieldOptions();
-void LIBPROTOBUF_EXPORT InitDefaultsOneofOptionsImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsOneofOptions();
-void LIBPROTOBUF_EXPORT InitDefaultsEnumOptionsImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsEnumOptions();
-void LIBPROTOBUF_EXPORT InitDefaultsEnumValueOptionsImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsEnumValueOptions();
-void LIBPROTOBUF_EXPORT InitDefaultsServiceOptionsImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsServiceOptions();
-void LIBPROTOBUF_EXPORT InitDefaultsMethodOptionsImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsMethodOptions();
-void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOption_NamePartImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOption_NamePart();
-void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOptionImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOption();
-void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfo_LocationImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfo_Location();
-void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfoImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfo();
-void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfo_AnnotationImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfo_Annotation();
-void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfoImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfo();
-inline void LIBPROTOBUF_EXPORT InitDefaults() {
- InitDefaultsFileDescriptorSet();
- InitDefaultsFileDescriptorProto();
- InitDefaultsDescriptorProto_ExtensionRange();
- InitDefaultsDescriptorProto_ReservedRange();
- InitDefaultsDescriptorProto();
- InitDefaultsExtensionRangeOptions();
- InitDefaultsFieldDescriptorProto();
- InitDefaultsOneofDescriptorProto();
- InitDefaultsEnumDescriptorProto_EnumReservedRange();
- InitDefaultsEnumDescriptorProto();
- InitDefaultsEnumValueDescriptorProto();
- InitDefaultsServiceDescriptorProto();
- InitDefaultsMethodDescriptorProto();
- InitDefaultsFileOptions();
- InitDefaultsMessageOptions();
- InitDefaultsFieldOptions();
- InitDefaultsOneofOptions();
- InitDefaultsEnumOptions();
- InitDefaultsEnumValueOptions();
- InitDefaultsServiceOptions();
- InitDefaultsMethodOptions();
- InitDefaultsUninterpretedOption_NamePart();
- InitDefaultsUninterpretedOption();
- InitDefaultsSourceCodeInfo_Location();
- InitDefaultsSourceCodeInfo();
- InitDefaultsGeneratedCodeInfo_Annotation();
- InitDefaultsGeneratedCodeInfo();
-}
} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto
namespace google {
namespace protobuf {
@@ -214,33 +133,33 @@ LIBPROTOBUF_EXPORT extern UninterpretedOption_NamePartDefaultTypeInternal _Unint
} // namespace google
namespace google {
namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto* Arena::CreateMessage< ::google::protobuf::DescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMessage< ::google::protobuf::DescriptorProto_ExtensionRange>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMessage< ::google::protobuf::DescriptorProto_ReservedRange>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto* Arena::CreateMessage< ::google::protobuf::EnumDescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMessage< ::google::protobuf::EnumDescriptorProto_EnumReservedRange>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumOptions* Arena::CreateMessage< ::google::protobuf::EnumOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMessage< ::google::protobuf::EnumValueDescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueOptions* Arena::CreateMessage< ::google::protobuf::EnumValueOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::ExtensionRangeOptions* Arena::CreateMessage< ::google::protobuf::ExtensionRangeOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldDescriptorProto* Arena::CreateMessage< ::google::protobuf::FieldDescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldOptions* Arena::CreateMessage< ::google::protobuf::FieldOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorProto* Arena::CreateMessage< ::google::protobuf::FileDescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorSet* Arena::CreateMessage< ::google::protobuf::FileDescriptorSet>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileOptions* Arena::CreateMessage< ::google::protobuf::FileOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo* Arena::CreateMessage< ::google::protobuf::GeneratedCodeInfo>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMessage< ::google::protobuf::GeneratedCodeInfo_Annotation>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::MessageOptions* Arena::CreateMessage< ::google::protobuf::MessageOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodDescriptorProto* Arena::CreateMessage< ::google::protobuf::MethodDescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodOptions* Arena::CreateMessage< ::google::protobuf::MethodOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofDescriptorProto* Arena::CreateMessage< ::google::protobuf::OneofDescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofOptions* Arena::CreateMessage< ::google::protobuf::OneofOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceDescriptorProto* Arena::CreateMessage< ::google::protobuf::ServiceDescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceOptions* Arena::CreateMessage< ::google::protobuf::ServiceOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo* Arena::CreateMessage< ::google::protobuf::SourceCodeInfo>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMessage< ::google::protobuf::SourceCodeInfo_Location>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption* Arena::CreateMessage< ::google::protobuf::UninterpretedOption>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMessage< ::google::protobuf::UninterpretedOption_NamePart>(Arena*);
+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*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -416,10 +335,10 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -430,7 +349,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
return reinterpret_cast<const FileDescriptorSet*>(
&_FileDescriptorSet_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
0;
void UnsafeArenaSwap(FileDescriptorSet* other);
@@ -441,32 +360,33 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
// implements Message ----------------------------------------------
- inline FileDescriptorSet* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<FileDescriptorSet>(NULL);
+ inline FileDescriptorSet* New() const final {
+ return CreateMaybeMessage<FileDescriptorSet>(NULL);
}
- FileDescriptorSet* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<FileDescriptorSet>(arena);
+ FileDescriptorSet* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<FileDescriptorSet>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const FileDescriptorSet& from);
void MergeFrom(const FileDescriptorSet& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(FileDescriptorSet* other);
protected:
explicit FileDescriptorSet(::google::protobuf::Arena* arena);
@@ -482,7 +402,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -508,10 +428,9 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > file_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSetImpl();
};
// -------------------------------------------------------------------
@@ -548,10 +467,10 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -562,7 +481,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
return reinterpret_cast<const FileDescriptorProto*>(
&_FileDescriptorProto_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
1;
void UnsafeArenaSwap(FileDescriptorProto* other);
@@ -573,32 +492,33 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
// implements Message ----------------------------------------------
- inline FileDescriptorProto* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<FileDescriptorProto>(NULL);
+ inline FileDescriptorProto* New() const final {
+ return CreateMaybeMessage<FileDescriptorProto>(NULL);
}
- FileDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<FileDescriptorProto>(arena);
+ FileDescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<FileDescriptorProto>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const FileDescriptorProto& from);
void MergeFrom(const FileDescriptorProto& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(FileDescriptorProto* other);
protected:
explicit FileDescriptorProto(::google::protobuf::Arena* arena);
@@ -614,7 +534,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -790,6 +710,9 @@ 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();
@@ -802,6 +725,9 @@ 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();
@@ -828,7 +754,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::std::string> dependency_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto > message_type_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto > enum_type_;
@@ -842,7 +768,6 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
::google::protobuf::FileOptions* options_;
::google::protobuf::SourceCodeInfo* source_code_info_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProtoImpl();
};
// -------------------------------------------------------------------
@@ -879,10 +804,10 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -893,7 +818,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
return reinterpret_cast<const DescriptorProto_ExtensionRange*>(
&_DescriptorProto_ExtensionRange_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
2;
void UnsafeArenaSwap(DescriptorProto_ExtensionRange* other);
@@ -904,32 +829,33 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
// implements Message ----------------------------------------------
- inline DescriptorProto_ExtensionRange* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<DescriptorProto_ExtensionRange>(NULL);
+ inline DescriptorProto_ExtensionRange* New() const final {
+ return CreateMaybeMessage<DescriptorProto_ExtensionRange>(NULL);
}
- DescriptorProto_ExtensionRange* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<DescriptorProto_ExtensionRange>(arena);
+ DescriptorProto_ExtensionRange* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<DescriptorProto_ExtensionRange>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const DescriptorProto_ExtensionRange& from);
void MergeFrom(const DescriptorProto_ExtensionRange& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(DescriptorProto_ExtensionRange* other);
protected:
explicit DescriptorProto_ExtensionRange(::google::protobuf::Arena* arena);
@@ -945,7 +871,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -955,6 +881,9 @@ 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();
@@ -991,12 +920,11 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::ExtensionRangeOptions* options_;
::google::protobuf::int32 start_;
::google::protobuf::int32 end_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRangeImpl();
};
// -------------------------------------------------------------------
@@ -1033,10 +961,10 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -1047,7 +975,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
return reinterpret_cast<const DescriptorProto_ReservedRange*>(
&_DescriptorProto_ReservedRange_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
3;
void UnsafeArenaSwap(DescriptorProto_ReservedRange* other);
@@ -1058,32 +986,33 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
// implements Message ----------------------------------------------
- inline DescriptorProto_ReservedRange* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<DescriptorProto_ReservedRange>(NULL);
+ inline DescriptorProto_ReservedRange* New() const final {
+ return CreateMaybeMessage<DescriptorProto_ReservedRange>(NULL);
}
- DescriptorProto_ReservedRange* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<DescriptorProto_ReservedRange>(arena);
+ DescriptorProto_ReservedRange* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<DescriptorProto_ReservedRange>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const DescriptorProto_ReservedRange& from);
void MergeFrom(const DescriptorProto_ReservedRange& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(DescriptorProto_ReservedRange* other);
protected:
explicit DescriptorProto_ReservedRange(::google::protobuf::Arena* arena);
@@ -1099,7 +1028,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -1131,11 +1060,10 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::int32 start_;
::google::protobuf::int32 end_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRangeImpl();
};
// -------------------------------------------------------------------
@@ -1172,10 +1100,10 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -1186,7 +1114,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
return reinterpret_cast<const DescriptorProto*>(
&_DescriptorProto_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
4;
void UnsafeArenaSwap(DescriptorProto* other);
@@ -1197,32 +1125,33 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
// implements Message ----------------------------------------------
- inline DescriptorProto* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<DescriptorProto>(NULL);
+ inline DescriptorProto* New() const final {
+ return CreateMaybeMessage<DescriptorProto>(NULL);
}
- DescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<DescriptorProto>(arena);
+ DescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<DescriptorProto>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const DescriptorProto& from);
void MergeFrom(const DescriptorProto& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(DescriptorProto* other);
protected:
explicit DescriptorProto(::google::protobuf::Arena* arena);
@@ -1238,7 +1167,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -1381,6 +1310,9 @@ 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();
@@ -1401,7 +1333,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > field_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto > nested_type_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto > enum_type_;
@@ -1413,7 +1345,6 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::MessageOptions* options_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProtoImpl();
};
// -------------------------------------------------------------------
@@ -1450,10 +1381,10 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -1464,7 +1395,7 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess
return reinterpret_cast<const ExtensionRangeOptions*>(
&_ExtensionRangeOptions_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
5;
void UnsafeArenaSwap(ExtensionRangeOptions* other);
@@ -1475,32 +1406,33 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess
// implements Message ----------------------------------------------
- inline ExtensionRangeOptions* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<ExtensionRangeOptions>(NULL);
+ inline ExtensionRangeOptions* New() const final {
+ return CreateMaybeMessage<ExtensionRangeOptions>(NULL);
}
- ExtensionRangeOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<ExtensionRangeOptions>(arena);
+ ExtensionRangeOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<ExtensionRangeOptions>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const ExtensionRangeOptions& from);
void MergeFrom(const ExtensionRangeOptions& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(ExtensionRangeOptions* other);
protected:
explicit ExtensionRangeOptions(::google::protobuf::Arena* arena);
@@ -1516,7 +1448,7 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -1545,10 +1477,9 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptionsImpl();
};
// -------------------------------------------------------------------
@@ -1585,10 +1516,10 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -1599,7 +1530,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
return reinterpret_cast<const FieldDescriptorProto*>(
&_FieldDescriptorProto_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
6;
void UnsafeArenaSwap(FieldDescriptorProto* other);
@@ -1610,32 +1541,33 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
// implements Message ----------------------------------------------
- inline FieldDescriptorProto* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<FieldDescriptorProto>(NULL);
+ inline FieldDescriptorProto* New() const final {
+ return CreateMaybeMessage<FieldDescriptorProto>(NULL);
}
- FieldDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<FieldDescriptorProto>(arena);
+ FieldDescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<FieldDescriptorProto>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const FieldDescriptorProto& from);
void MergeFrom(const FieldDescriptorProto& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(FieldDescriptorProto* other);
protected:
explicit FieldDescriptorProto(::google::protobuf::Arena* arena);
@@ -1651,7 +1583,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -1867,6 +1799,9 @@ 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();
@@ -1931,7 +1866,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::internal::ArenaStringPtr extendee_;
::google::protobuf::internal::ArenaStringPtr type_name_;
@@ -1943,7 +1878,6 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
int label_;
int type_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProtoImpl();
};
// -------------------------------------------------------------------
@@ -1980,10 +1914,10 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -1994,7 +1928,7 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
return reinterpret_cast<const OneofDescriptorProto*>(
&_OneofDescriptorProto_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
7;
void UnsafeArenaSwap(OneofDescriptorProto* other);
@@ -2005,32 +1939,33 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
// implements Message ----------------------------------------------
- inline OneofDescriptorProto* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<OneofDescriptorProto>(NULL);
+ inline OneofDescriptorProto* New() const final {
+ return CreateMaybeMessage<OneofDescriptorProto>(NULL);
}
- OneofDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<OneofDescriptorProto>(arena);
+ OneofDescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<OneofDescriptorProto>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const OneofDescriptorProto& from);
void MergeFrom(const OneofDescriptorProto& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(OneofDescriptorProto* other);
protected:
explicit OneofDescriptorProto(::google::protobuf::Arena* arena);
@@ -2046,7 +1981,7 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -2080,6 +2015,9 @@ 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();
@@ -2100,11 +2038,10 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ 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 void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProtoImpl();
};
// -------------------------------------------------------------------
@@ -2141,10 +2078,10 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -2155,7 +2092,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google
return reinterpret_cast<const EnumDescriptorProto_EnumReservedRange*>(
&_EnumDescriptorProto_EnumReservedRange_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
8;
void UnsafeArenaSwap(EnumDescriptorProto_EnumReservedRange* other);
@@ -2166,32 +2103,33 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google
// implements Message ----------------------------------------------
- inline EnumDescriptorProto_EnumReservedRange* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<EnumDescriptorProto_EnumReservedRange>(NULL);
+ inline EnumDescriptorProto_EnumReservedRange* New() const final {
+ return CreateMaybeMessage<EnumDescriptorProto_EnumReservedRange>(NULL);
}
- EnumDescriptorProto_EnumReservedRange* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<EnumDescriptorProto_EnumReservedRange>(arena);
+ EnumDescriptorProto_EnumReservedRange* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<EnumDescriptorProto_EnumReservedRange>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const EnumDescriptorProto_EnumReservedRange& from);
void MergeFrom(const EnumDescriptorProto_EnumReservedRange& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(EnumDescriptorProto_EnumReservedRange* other);
protected:
explicit EnumDescriptorProto_EnumReservedRange(::google::protobuf::Arena* arena);
@@ -2207,7 +2145,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -2239,11 +2177,10 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::int32 start_;
::google::protobuf::int32 end_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl();
};
// -------------------------------------------------------------------
@@ -2280,10 +2217,10 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -2294,7 +2231,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
return reinterpret_cast<const EnumDescriptorProto*>(
&_EnumDescriptorProto_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
9;
void UnsafeArenaSwap(EnumDescriptorProto* other);
@@ -2305,32 +2242,33 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
// implements Message ----------------------------------------------
- inline EnumDescriptorProto* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<EnumDescriptorProto>(NULL);
+ inline EnumDescriptorProto* New() const final {
+ return CreateMaybeMessage<EnumDescriptorProto>(NULL);
}
- EnumDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<EnumDescriptorProto>(arena);
+ EnumDescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<EnumDescriptorProto>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const EnumDescriptorProto& from);
void MergeFrom(const EnumDescriptorProto& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(EnumDescriptorProto* other);
protected:
explicit EnumDescriptorProto(::google::protobuf::Arena* arena);
@@ -2346,7 +2284,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -2428,6 +2366,9 @@ 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();
@@ -2448,14 +2389,13 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ 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::internal::ArenaStringPtr name_;
::google::protobuf::EnumOptions* options_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProtoImpl();
};
// -------------------------------------------------------------------
@@ -2492,10 +2432,10 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -2506,7 +2446,7 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
return reinterpret_cast<const EnumValueDescriptorProto*>(
&_EnumValueDescriptorProto_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
10;
void UnsafeArenaSwap(EnumValueDescriptorProto* other);
@@ -2517,32 +2457,33 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
// implements Message ----------------------------------------------
- inline EnumValueDescriptorProto* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<EnumValueDescriptorProto>(NULL);
+ inline EnumValueDescriptorProto* New() const final {
+ return CreateMaybeMessage<EnumValueDescriptorProto>(NULL);
}
- EnumValueDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<EnumValueDescriptorProto>(arena);
+ EnumValueDescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<EnumValueDescriptorProto>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const EnumValueDescriptorProto& from);
void MergeFrom(const EnumValueDescriptorProto& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(EnumValueDescriptorProto* other);
protected:
explicit EnumValueDescriptorProto(::google::protobuf::Arena* arena);
@@ -2558,7 +2499,7 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -2592,6 +2533,9 @@ 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();
@@ -2621,12 +2565,11 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::EnumValueOptions* options_;
::google::protobuf::int32 number_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProtoImpl();
};
// -------------------------------------------------------------------
@@ -2663,10 +2606,10 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -2677,7 +2620,7 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
return reinterpret_cast<const ServiceDescriptorProto*>(
&_ServiceDescriptorProto_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
11;
void UnsafeArenaSwap(ServiceDescriptorProto* other);
@@ -2688,32 +2631,33 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
// implements Message ----------------------------------------------
- inline ServiceDescriptorProto* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<ServiceDescriptorProto>(NULL);
+ inline ServiceDescriptorProto* New() const final {
+ return CreateMaybeMessage<ServiceDescriptorProto>(NULL);
}
- ServiceDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<ServiceDescriptorProto>(arena);
+ ServiceDescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<ServiceDescriptorProto>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const ServiceDescriptorProto& from);
void MergeFrom(const ServiceDescriptorProto& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(ServiceDescriptorProto* other);
protected:
explicit ServiceDescriptorProto(::google::protobuf::Arena* arena);
@@ -2729,7 +2673,7 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -2775,6 +2719,9 @@ 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();
@@ -2795,12 +2742,11 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::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 void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProtoImpl();
};
// -------------------------------------------------------------------
@@ -2837,10 +2783,10 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -2851,7 +2797,7 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
return reinterpret_cast<const MethodDescriptorProto*>(
&_MethodDescriptorProto_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
12;
void UnsafeArenaSwap(MethodDescriptorProto* other);
@@ -2862,32 +2808,33 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
// implements Message ----------------------------------------------
- inline MethodDescriptorProto* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<MethodDescriptorProto>(NULL);
+ inline MethodDescriptorProto* New() const final {
+ return CreateMaybeMessage<MethodDescriptorProto>(NULL);
}
- MethodDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<MethodDescriptorProto>(arena);
+ MethodDescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<MethodDescriptorProto>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const MethodDescriptorProto& from);
void MergeFrom(const MethodDescriptorProto& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(MethodDescriptorProto* other);
protected:
explicit MethodDescriptorProto(::google::protobuf::Arena* arena);
@@ -2903,7 +2850,7 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -2985,6 +2932,9 @@ 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();
@@ -3027,7 +2977,7 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::internal::ArenaStringPtr input_type_;
::google::protobuf::internal::ArenaStringPtr output_type_;
@@ -3035,7 +2985,6 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
bool client_streaming_;
bool server_streaming_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProtoImpl();
};
// -------------------------------------------------------------------
@@ -3072,10 +3021,10 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -3086,7 +3035,7 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
return reinterpret_cast<const FileOptions*>(
&_FileOptions_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
13;
void UnsafeArenaSwap(FileOptions* other);
@@ -3097,32 +3046,33 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
// implements Message ----------------------------------------------
- inline FileOptions* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<FileOptions>(NULL);
+ inline FileOptions* New() const final {
+ return CreateMaybeMessage<FileOptions>(NULL);
}
- FileOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<FileOptions>(arena);
+ FileOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<FileOptions>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const FileOptions& from);
void MergeFrom(const FileOptions& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(FileOptions* other);
protected:
explicit FileOptions(::google::protobuf::Arena* arena);
@@ -3138,7 +3088,7 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -3376,12 +3326,53 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
void unsafe_arena_set_allocated_php_namespace(
::std::string* php_namespace);
- // optional bool cc_enable_arenas = 31 [default = false];
- bool has_cc_enable_arenas() const;
- void clear_cc_enable_arenas();
- static const int kCcEnableArenasFieldNumber = 31;
- bool cc_enable_arenas() const;
- void set_cc_enable_arenas(bool value);
+ // optional string php_metadata_namespace = 44;
+ bool has_php_metadata_namespace() const;
+ void clear_php_metadata_namespace();
+ static const int kPhpMetadataNamespaceFieldNumber = 44;
+ const ::std::string& php_metadata_namespace() const;
+ void set_php_metadata_namespace(const ::std::string& value);
+ #if LANG_CXX11
+ void set_php_metadata_namespace(::std::string&& value);
+ #endif
+ void set_php_metadata_namespace(const char* value);
+ void set_php_metadata_namespace(const char* value, size_t size);
+ ::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"
+ " 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"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_php_metadata_namespace(
+ ::std::string* php_metadata_namespace);
+
+ // optional string ruby_package = 45;
+ bool has_ruby_package() const;
+ void clear_ruby_package();
+ static const int kRubyPackageFieldNumber = 45;
+ const ::std::string& ruby_package() const;
+ void set_ruby_package(const ::std::string& value);
+ #if LANG_CXX11
+ void set_ruby_package(::std::string&& value);
+ #endif
+ void set_ruby_package(const char* value);
+ void set_ruby_package(const char* value, size_t size);
+ ::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"
+ " 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"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_ruby_package(
+ ::std::string* ruby_package);
// optional bool java_multiple_files = 10 [default = false];
bool has_java_multiple_files() const;
@@ -3439,6 +3430,13 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
bool deprecated() const;
void set_deprecated(bool value);
+ // optional bool cc_enable_arenas = 31 [default = false];
+ bool has_cc_enable_arenas() const;
+ void clear_cc_enable_arenas();
+ static const int kCcEnableArenasFieldNumber = 31;
+ bool cc_enable_arenas() const;
+ void set_cc_enable_arenas(bool value);
+
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
bool has_optimize_for() const;
void clear_optimize_for();
@@ -3485,6 +3483,10 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
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();
::google::protobuf::internal::ExtensionSet _extensions_;
@@ -3493,7 +3495,7 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
::google::protobuf::internal::ArenaStringPtr java_package_;
::google::protobuf::internal::ArenaStringPtr java_outer_classname_;
@@ -3503,7 +3505,8 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
::google::protobuf::internal::ArenaStringPtr swift_prefix_;
::google::protobuf::internal::ArenaStringPtr php_class_prefix_;
::google::protobuf::internal::ArenaStringPtr php_namespace_;
- bool cc_enable_arenas_;
+ ::google::protobuf::internal::ArenaStringPtr php_metadata_namespace_;
+ ::google::protobuf::internal::ArenaStringPtr ruby_package_;
bool java_multiple_files_;
bool java_generate_equals_and_hash_;
bool java_string_check_utf8_;
@@ -3512,9 +3515,9 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
bool py_generic_services_;
bool php_generic_services_;
bool deprecated_;
+ bool cc_enable_arenas_;
int optimize_for_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptionsImpl();
};
// -------------------------------------------------------------------
@@ -3551,10 +3554,10 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -3565,7 +3568,7 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
return reinterpret_cast<const MessageOptions*>(
&_MessageOptions_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
14;
void UnsafeArenaSwap(MessageOptions* other);
@@ -3576,32 +3579,33 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
// implements Message ----------------------------------------------
- inline MessageOptions* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<MessageOptions>(NULL);
+ inline MessageOptions* New() const final {
+ return CreateMaybeMessage<MessageOptions>(NULL);
}
- MessageOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<MessageOptions>(arena);
+ MessageOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<MessageOptions>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const MessageOptions& from);
void MergeFrom(const MessageOptions& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(MessageOptions* other);
protected:
explicit MessageOptions(::google::protobuf::Arena* arena);
@@ -3617,7 +3621,7 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -3682,14 +3686,13 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool message_set_wire_format_;
bool no_standard_descriptor_accessor_;
bool deprecated_;
bool map_entry_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptionsImpl();
};
// -------------------------------------------------------------------
@@ -3726,10 +3729,10 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -3740,7 +3743,7 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
return reinterpret_cast<const FieldOptions*>(
&_FieldOptions_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
15;
void UnsafeArenaSwap(FieldOptions* other);
@@ -3751,32 +3754,33 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
// implements Message ----------------------------------------------
- inline FieldOptions* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<FieldOptions>(NULL);
+ inline FieldOptions* New() const final {
+ return CreateMaybeMessage<FieldOptions>(NULL);
}
- FieldOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<FieldOptions>(arena);
+ FieldOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<FieldOptions>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const FieldOptions& from);
void MergeFrom(const FieldOptions& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(FieldOptions* other);
protected:
explicit FieldOptions(::google::protobuf::Arena* arena);
@@ -3792,7 +3796,7 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -3931,7 +3935,7 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
int ctype_;
bool packed_;
@@ -3940,7 +3944,6 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
bool weak_;
int jstype_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptionsImpl();
};
// -------------------------------------------------------------------
@@ -3977,10 +3980,10 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -3991,7 +3994,7 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
return reinterpret_cast<const OneofOptions*>(
&_OneofOptions_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
16;
void UnsafeArenaSwap(OneofOptions* other);
@@ -4002,32 +4005,33 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
// implements Message ----------------------------------------------
- inline OneofOptions* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<OneofOptions>(NULL);
+ inline OneofOptions* New() const final {
+ return CreateMaybeMessage<OneofOptions>(NULL);
}
- OneofOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<OneofOptions>(arena);
+ OneofOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<OneofOptions>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const OneofOptions& from);
void MergeFrom(const OneofOptions& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(OneofOptions* other);
protected:
explicit OneofOptions(::google::protobuf::Arena* arena);
@@ -4043,7 +4047,7 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -4072,10 +4076,9 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptionsImpl();
};
// -------------------------------------------------------------------
@@ -4112,10 +4115,10 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -4126,7 +4129,7 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
return reinterpret_cast<const EnumOptions*>(
&_EnumOptions_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
17;
void UnsafeArenaSwap(EnumOptions* other);
@@ -4137,32 +4140,33 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
// implements Message ----------------------------------------------
- inline EnumOptions* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<EnumOptions>(NULL);
+ inline EnumOptions* New() const final {
+ return CreateMaybeMessage<EnumOptions>(NULL);
}
- EnumOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<EnumOptions>(arena);
+ EnumOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<EnumOptions>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const EnumOptions& from);
void MergeFrom(const EnumOptions& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(EnumOptions* other);
protected:
explicit EnumOptions(::google::protobuf::Arena* arena);
@@ -4178,7 +4182,7 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -4225,12 +4229,11 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool allow_alias_;
bool deprecated_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptionsImpl();
};
// -------------------------------------------------------------------
@@ -4267,10 +4270,10 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -4281,7 +4284,7 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
return reinterpret_cast<const EnumValueOptions*>(
&_EnumValueOptions_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
18;
void UnsafeArenaSwap(EnumValueOptions* other);
@@ -4292,32 +4295,33 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
// implements Message ----------------------------------------------
- inline EnumValueOptions* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<EnumValueOptions>(NULL);
+ inline EnumValueOptions* New() const final {
+ return CreateMaybeMessage<EnumValueOptions>(NULL);
}
- EnumValueOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<EnumValueOptions>(arena);
+ EnumValueOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<EnumValueOptions>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const EnumValueOptions& from);
void MergeFrom(const EnumValueOptions& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(EnumValueOptions* other);
protected:
explicit EnumValueOptions(::google::protobuf::Arena* arena);
@@ -4333,7 +4337,7 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -4371,11 +4375,10 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ 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 void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptionsImpl();
};
// -------------------------------------------------------------------
@@ -4412,10 +4415,10 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -4426,7 +4429,7 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
return reinterpret_cast<const ServiceOptions*>(
&_ServiceOptions_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
19;
void UnsafeArenaSwap(ServiceOptions* other);
@@ -4437,32 +4440,33 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
// implements Message ----------------------------------------------
- inline ServiceOptions* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<ServiceOptions>(NULL);
+ inline ServiceOptions* New() const final {
+ return CreateMaybeMessage<ServiceOptions>(NULL);
}
- ServiceOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<ServiceOptions>(arena);
+ ServiceOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<ServiceOptions>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const ServiceOptions& from);
void MergeFrom(const ServiceOptions& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(ServiceOptions* other);
protected:
explicit ServiceOptions(::google::protobuf::Arena* arena);
@@ -4478,7 +4482,7 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -4516,11 +4520,10 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ 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 void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptionsImpl();
};
// -------------------------------------------------------------------
@@ -4557,10 +4560,10 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -4571,7 +4574,7 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
return reinterpret_cast<const MethodOptions*>(
&_MethodOptions_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
20;
void UnsafeArenaSwap(MethodOptions* other);
@@ -4582,32 +4585,33 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
// implements Message ----------------------------------------------
- inline MethodOptions* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<MethodOptions>(NULL);
+ inline MethodOptions* New() const final {
+ return CreateMaybeMessage<MethodOptions>(NULL);
}
- MethodOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<MethodOptions>(arena);
+ MethodOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<MethodOptions>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const MethodOptions& from);
void MergeFrom(const MethodOptions& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(MethodOptions* other);
protected:
explicit MethodOptions(::google::protobuf::Arena* arena);
@@ -4623,7 +4627,7 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -4698,12 +4702,11 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool deprecated_;
int idempotency_level_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptionsImpl();
};
// -------------------------------------------------------------------
@@ -4740,10 +4743,10 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -4754,7 +4757,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
return reinterpret_cast<const UninterpretedOption_NamePart*>(
&_UninterpretedOption_NamePart_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
21;
void UnsafeArenaSwap(UninterpretedOption_NamePart* other);
@@ -4765,32 +4768,33 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
// implements Message ----------------------------------------------
- inline UninterpretedOption_NamePart* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<UninterpretedOption_NamePart>(NULL);
+ inline UninterpretedOption_NamePart* New() const final {
+ return CreateMaybeMessage<UninterpretedOption_NamePart>(NULL);
}
- UninterpretedOption_NamePart* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<UninterpretedOption_NamePart>(arena);
+ UninterpretedOption_NamePart* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<UninterpretedOption_NamePart>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const UninterpretedOption_NamePart& from);
void MergeFrom(const UninterpretedOption_NamePart& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(UninterpretedOption_NamePart* other);
protected:
explicit UninterpretedOption_NamePart(::google::protobuf::Arena* arena);
@@ -4806,7 +4810,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -4858,11 +4862,10 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ 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 void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePartImpl();
};
// -------------------------------------------------------------------
@@ -4899,10 +4902,10 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -4913,7 +4916,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
return reinterpret_cast<const UninterpretedOption*>(
&_UninterpretedOption_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
22;
void UnsafeArenaSwap(UninterpretedOption* other);
@@ -4924,32 +4927,33 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
// implements Message ----------------------------------------------
- inline UninterpretedOption* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<UninterpretedOption>(NULL);
+ inline UninterpretedOption* New() const final {
+ return CreateMaybeMessage<UninterpretedOption>(NULL);
}
- UninterpretedOption* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<UninterpretedOption>(arena);
+ UninterpretedOption* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<UninterpretedOption>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const UninterpretedOption& from);
void MergeFrom(const UninterpretedOption& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(UninterpretedOption* other);
protected:
explicit UninterpretedOption(::google::protobuf::Arena* arena);
@@ -4965,7 +4969,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -5098,7 +5102,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart > name_;
::google::protobuf::internal::ArenaStringPtr identifier_value_;
::google::protobuf::internal::ArenaStringPtr string_value_;
@@ -5107,7 +5111,6 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
::google::protobuf::int64 negative_int_value_;
double double_value_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOptionImpl();
};
// -------------------------------------------------------------------
@@ -5144,10 +5147,10 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -5158,7 +5161,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
return reinterpret_cast<const SourceCodeInfo_Location*>(
&_SourceCodeInfo_Location_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
23;
void UnsafeArenaSwap(SourceCodeInfo_Location* other);
@@ -5169,32 +5172,33 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
// implements Message ----------------------------------------------
- inline SourceCodeInfo_Location* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<SourceCodeInfo_Location>(NULL);
+ inline SourceCodeInfo_Location* New() const final {
+ return CreateMaybeMessage<SourceCodeInfo_Location>(NULL);
}
- SourceCodeInfo_Location* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<SourceCodeInfo_Location>(arena);
+ SourceCodeInfo_Location* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<SourceCodeInfo_Location>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const SourceCodeInfo_Location& from);
void MergeFrom(const SourceCodeInfo_Location& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(SourceCodeInfo_Location* other);
protected:
explicit SourceCodeInfo_Location(::google::protobuf::Arena* arena);
@@ -5210,7 +5214,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -5322,7 +5326,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedField< ::google::protobuf::int32 > path_;
mutable int _path_cached_byte_size_;
::google::protobuf::RepeatedField< ::google::protobuf::int32 > span_;
@@ -5331,7 +5335,6 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
::google::protobuf::internal::ArenaStringPtr leading_comments_;
::google::protobuf::internal::ArenaStringPtr trailing_comments_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_LocationImpl();
};
// -------------------------------------------------------------------
@@ -5368,10 +5371,10 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -5382,7 +5385,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
return reinterpret_cast<const SourceCodeInfo*>(
&_SourceCodeInfo_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
24;
void UnsafeArenaSwap(SourceCodeInfo* other);
@@ -5393,32 +5396,33 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
// implements Message ----------------------------------------------
- inline SourceCodeInfo* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<SourceCodeInfo>(NULL);
+ inline SourceCodeInfo* New() const final {
+ return CreateMaybeMessage<SourceCodeInfo>(NULL);
}
- SourceCodeInfo* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<SourceCodeInfo>(arena);
+ SourceCodeInfo* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<SourceCodeInfo>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const SourceCodeInfo& from);
void MergeFrom(const SourceCodeInfo& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(SourceCodeInfo* other);
protected:
explicit SourceCodeInfo(::google::protobuf::Arena* arena);
@@ -5434,7 +5438,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -5462,10 +5466,9 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location > location_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfoImpl();
};
// -------------------------------------------------------------------
@@ -5502,10 +5505,10 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -5516,7 +5519,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
return reinterpret_cast<const GeneratedCodeInfo_Annotation*>(
&_GeneratedCodeInfo_Annotation_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
25;
void UnsafeArenaSwap(GeneratedCodeInfo_Annotation* other);
@@ -5527,32 +5530,33 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
// implements Message ----------------------------------------------
- inline GeneratedCodeInfo_Annotation* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<GeneratedCodeInfo_Annotation>(NULL);
+ inline GeneratedCodeInfo_Annotation* New() const final {
+ return CreateMaybeMessage<GeneratedCodeInfo_Annotation>(NULL);
}
- GeneratedCodeInfo_Annotation* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<GeneratedCodeInfo_Annotation>(arena);
+ GeneratedCodeInfo_Annotation* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<GeneratedCodeInfo_Annotation>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const GeneratedCodeInfo_Annotation& from);
void MergeFrom(const GeneratedCodeInfo_Annotation& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(GeneratedCodeInfo_Annotation* other);
protected:
explicit GeneratedCodeInfo_Annotation(::google::protobuf::Arena* arena);
@@ -5568,7 +5572,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -5638,14 +5642,13 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedField< ::google::protobuf::int32 > path_;
mutable 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 void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_AnnotationImpl();
};
// -------------------------------------------------------------------
@@ -5682,10 +5685,10 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
return _internal_metadata_.mutable_unknown_fields();
}
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -5696,7 +5699,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
return reinterpret_cast<const GeneratedCodeInfo*>(
&_GeneratedCodeInfo_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
26;
void UnsafeArenaSwap(GeneratedCodeInfo* other);
@@ -5707,32 +5710,33 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
// implements Message ----------------------------------------------
- inline GeneratedCodeInfo* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<GeneratedCodeInfo>(NULL);
+ inline GeneratedCodeInfo* New() const final {
+ return CreateMaybeMessage<GeneratedCodeInfo>(NULL);
}
- GeneratedCodeInfo* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<GeneratedCodeInfo>(arena);
+ GeneratedCodeInfo* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<GeneratedCodeInfo>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const GeneratedCodeInfo& from);
void MergeFrom(const GeneratedCodeInfo& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(GeneratedCodeInfo* other);
protected:
explicit GeneratedCodeInfo(::google::protobuf::Arena* arena);
@@ -5748,7 +5752,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -5776,10 +5780,9 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation > annotation_;
friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfoImpl();
};
// ===================================================================
@@ -5878,8 +5881,11 @@ inline ::std::string* FileDescriptorProto::mutable_name() {
}
inline ::std::string* FileDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.name)
+ if (!has_name()) {
+ return NULL;
+ }
clear_has_name();
- return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -5963,8 +5969,11 @@ inline ::std::string* FileDescriptorProto::mutable_package() {
}
inline ::std::string* FileDescriptorProto::release_package() {
// @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.package)
+ if (!has_package()) {
+ return NULL;
+ }
clear_has_package();
- return package_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileDescriptorProto::set_allocated_package(::std::string* package) {
if (package != NULL) {
@@ -6259,6 +6268,9 @@ inline void FileDescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
clear_has_options();
}
+inline const ::google::protobuf::FileOptions& FileDescriptorProto::_internal_options() const {
+ return *options_;
+}
inline const ::google::protobuf::FileOptions& FileDescriptorProto::options() const {
const ::google::protobuf::FileOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.options)
@@ -6270,7 +6282,7 @@ inline ::google::protobuf::FileOptions* FileDescriptorProto::release_options() {
clear_has_options();
::google::protobuf::FileOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
- temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
options_ = NULL;
return temp;
@@ -6285,8 +6297,8 @@ inline ::google::protobuf::FileOptions* FileDescriptorProto::unsafe_arena_releas
inline ::google::protobuf::FileOptions* FileDescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::FileOptions >(
- GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<::google::protobuf::FileOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.options)
return options_;
@@ -6325,6 +6337,9 @@ 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_;
+}
inline const ::google::protobuf::SourceCodeInfo& FileDescriptorProto::source_code_info() const {
const ::google::protobuf::SourceCodeInfo* p = source_code_info_;
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.source_code_info)
@@ -6336,7 +6351,7 @@ inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::release_source_c
clear_has_source_code_info();
::google::protobuf::SourceCodeInfo* temp = source_code_info_;
if (GetArenaNoVirtual() != NULL) {
- temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
source_code_info_ = NULL;
return temp;
@@ -6351,8 +6366,8 @@ inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::unsafe_arena_rel
inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::mutable_source_code_info() {
set_has_source_code_info();
if (source_code_info_ == NULL) {
- source_code_info_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::SourceCodeInfo >(
- GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<::google::protobuf::SourceCodeInfo>(GetArenaNoVirtual());
+ source_code_info_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.source_code_info)
return source_code_info_;
@@ -6429,8 +6444,11 @@ inline ::std::string* FileDescriptorProto::mutable_syntax() {
}
inline ::std::string* FileDescriptorProto::release_syntax() {
// @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.syntax)
+ if (!has_syntax()) {
+ return NULL;
+ }
clear_has_syntax();
- return syntax_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return syntax_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileDescriptorProto::set_allocated_syntax(::std::string* syntax) {
if (syntax != NULL) {
@@ -6528,6 +6546,9 @@ 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_;
+}
inline const ::google::protobuf::ExtensionRangeOptions& DescriptorProto_ExtensionRange::options() const {
const ::google::protobuf::ExtensionRangeOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.options)
@@ -6539,7 +6560,7 @@ inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange
clear_has_options();
::google::protobuf::ExtensionRangeOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
- temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
options_ = NULL;
return temp;
@@ -6554,8 +6575,8 @@ inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange
inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange::mutable_options() {
set_has_options();
if (options_ == NULL) {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ExtensionRangeOptions >(
- GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<::google::protobuf::ExtensionRangeOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.ExtensionRange.options)
return options_;
@@ -6688,8 +6709,11 @@ inline ::std::string* DescriptorProto::mutable_name() {
}
inline ::std::string* DescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.name)
+ if (!has_name()) {
+ return NULL;
+ }
clear_has_name();
- return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void DescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -6915,6 +6939,9 @@ inline void DescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
clear_has_options();
}
+inline const ::google::protobuf::MessageOptions& DescriptorProto::_internal_options() const {
+ return *options_;
+}
inline const ::google::protobuf::MessageOptions& DescriptorProto::options() const {
const ::google::protobuf::MessageOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.options)
@@ -6926,7 +6953,7 @@ inline ::google::protobuf::MessageOptions* DescriptorProto::release_options() {
clear_has_options();
::google::protobuf::MessageOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
- temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
options_ = NULL;
return temp;
@@ -6941,8 +6968,8 @@ inline ::google::protobuf::MessageOptions* DescriptorProto::unsafe_arena_release
inline ::google::protobuf::MessageOptions* DescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::MessageOptions >(
- GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<::google::protobuf::MessageOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.options)
return options_;
@@ -7156,8 +7183,11 @@ inline ::std::string* FieldDescriptorProto::mutable_name() {
}
inline ::std::string* FieldDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.name)
+ if (!has_name()) {
+ return NULL;
+ }
clear_has_name();
- return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FieldDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -7315,8 +7345,11 @@ inline ::std::string* FieldDescriptorProto::mutable_type_name() {
}
inline ::std::string* FieldDescriptorProto::release_type_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.type_name)
+ if (!has_type_name()) {
+ return NULL;
+ }
clear_has_type_name();
- return type_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return type_name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FieldDescriptorProto::set_allocated_type_name(::std::string* type_name) {
if (type_name != NULL) {
@@ -7400,8 +7433,11 @@ inline ::std::string* FieldDescriptorProto::mutable_extendee() {
}
inline ::std::string* FieldDescriptorProto::release_extendee() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.extendee)
+ if (!has_extendee()) {
+ return NULL;
+ }
clear_has_extendee();
- return extendee_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return extendee_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FieldDescriptorProto::set_allocated_extendee(::std::string* extendee) {
if (extendee != NULL) {
@@ -7485,8 +7521,11 @@ inline ::std::string* FieldDescriptorProto::mutable_default_value() {
}
inline ::std::string* FieldDescriptorProto::release_default_value() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.default_value)
+ if (!has_default_value()) {
+ return NULL;
+ }
clear_has_default_value();
- return default_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return default_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FieldDescriptorProto::set_allocated_default_value(::std::string* default_value) {
if (default_value != NULL) {
@@ -7594,8 +7633,11 @@ inline ::std::string* FieldDescriptorProto::mutable_json_name() {
}
inline ::std::string* FieldDescriptorProto::release_json_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.json_name)
+ if (!has_json_name()) {
+ return NULL;
+ }
clear_has_json_name();
- return json_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return json_name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FieldDescriptorProto::set_allocated_json_name(::std::string* json_name) {
if (json_name != NULL) {
@@ -7641,6 +7683,9 @@ inline void FieldDescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
clear_has_options();
}
+inline const ::google::protobuf::FieldOptions& FieldDescriptorProto::_internal_options() const {
+ return *options_;
+}
inline const ::google::protobuf::FieldOptions& FieldDescriptorProto::options() const {
const ::google::protobuf::FieldOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.options)
@@ -7652,7 +7697,7 @@ inline ::google::protobuf::FieldOptions* FieldDescriptorProto::release_options()
clear_has_options();
::google::protobuf::FieldOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
- temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
options_ = NULL;
return temp;
@@ -7667,8 +7712,8 @@ inline ::google::protobuf::FieldOptions* FieldDescriptorProto::unsafe_arena_rele
inline ::google::protobuf::FieldOptions* FieldDescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::FieldOptions >(
- GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<::google::protobuf::FieldOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.options)
return options_;
@@ -7749,8 +7794,11 @@ inline ::std::string* OneofDescriptorProto::mutable_name() {
}
inline ::std::string* OneofDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.OneofDescriptorProto.name)
+ if (!has_name()) {
+ return NULL;
+ }
clear_has_name();
- return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void OneofDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -7796,6 +7844,9 @@ inline void OneofDescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
clear_has_options();
}
+inline const ::google::protobuf::OneofOptions& OneofDescriptorProto::_internal_options() const {
+ return *options_;
+}
inline const ::google::protobuf::OneofOptions& OneofDescriptorProto::options() const {
const ::google::protobuf::OneofOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.OneofDescriptorProto.options)
@@ -7807,7 +7858,7 @@ inline ::google::protobuf::OneofOptions* OneofDescriptorProto::release_options()
clear_has_options();
::google::protobuf::OneofOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
- temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
options_ = NULL;
return temp;
@@ -7822,8 +7873,8 @@ inline ::google::protobuf::OneofOptions* OneofDescriptorProto::unsafe_arena_rele
inline ::google::protobuf::OneofOptions* OneofDescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::OneofOptions >(
- GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<::google::protobuf::OneofOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.OneofDescriptorProto.options)
return options_;
@@ -7956,8 +8007,11 @@ inline ::std::string* EnumDescriptorProto::mutable_name() {
}
inline ::std::string* EnumDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.EnumDescriptorProto.name)
+ if (!has_name()) {
+ return NULL;
+ }
clear_has_name();
- return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void EnumDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -8033,6 +8087,9 @@ inline void EnumDescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
clear_has_options();
}
+inline const ::google::protobuf::EnumOptions& EnumDescriptorProto::_internal_options() const {
+ return *options_;
+}
inline const ::google::protobuf::EnumOptions& EnumDescriptorProto::options() const {
const ::google::protobuf::EnumOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.options)
@@ -8044,7 +8101,7 @@ inline ::google::protobuf::EnumOptions* EnumDescriptorProto::release_options() {
clear_has_options();
::google::protobuf::EnumOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
- temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
options_ = NULL;
return temp;
@@ -8059,8 +8116,8 @@ inline ::google::protobuf::EnumOptions* EnumDescriptorProto::unsafe_arena_releas
inline ::google::protobuf::EnumOptions* EnumDescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::EnumOptions >(
- GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<::google::protobuf::EnumOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.options)
return options_;
@@ -8240,8 +8297,11 @@ inline ::std::string* EnumValueDescriptorProto::mutable_name() {
}
inline ::std::string* EnumValueDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.EnumValueDescriptorProto.name)
+ if (!has_name()) {
+ return NULL;
+ }
clear_has_name();
- return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void EnumValueDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -8311,6 +8371,9 @@ inline void EnumValueDescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
clear_has_options();
}
+inline const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::_internal_options() const {
+ return *options_;
+}
inline const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::options() const {
const ::google::protobuf::EnumValueOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.options)
@@ -8322,7 +8385,7 @@ inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::release_o
clear_has_options();
::google::protobuf::EnumValueOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
- temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
options_ = NULL;
return temp;
@@ -8337,8 +8400,8 @@ inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::unsafe_ar
inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::EnumValueOptions >(
- GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<::google::protobuf::EnumValueOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueDescriptorProto.options)
return options_;
@@ -8419,8 +8482,11 @@ inline ::std::string* ServiceDescriptorProto::mutable_name() {
}
inline ::std::string* ServiceDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.ServiceDescriptorProto.name)
+ if (!has_name()) {
+ return NULL;
+ }
clear_has_name();
- return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void ServiceDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -8496,6 +8562,9 @@ inline void ServiceDescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
clear_has_options();
}
+inline const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::_internal_options() const {
+ return *options_;
+}
inline const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::options() const {
const ::google::protobuf::ServiceOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.options)
@@ -8507,7 +8576,7 @@ inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::release_optio
clear_has_options();
::google::protobuf::ServiceOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
- temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
options_ = NULL;
return temp;
@@ -8522,8 +8591,8 @@ inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::unsafe_arena_
inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ServiceOptions >(
- GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<::google::protobuf::ServiceOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.options)
return options_;
@@ -8604,8 +8673,11 @@ inline ::std::string* MethodDescriptorProto::mutable_name() {
}
inline ::std::string* MethodDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.name)
+ if (!has_name()) {
+ return NULL;
+ }
clear_has_name();
- return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void MethodDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -8689,8 +8761,11 @@ inline ::std::string* MethodDescriptorProto::mutable_input_type() {
}
inline ::std::string* MethodDescriptorProto::release_input_type() {
// @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.input_type)
+ if (!has_input_type()) {
+ return NULL;
+ }
clear_has_input_type();
- return input_type_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return input_type_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void MethodDescriptorProto::set_allocated_input_type(::std::string* input_type) {
if (input_type != NULL) {
@@ -8774,8 +8849,11 @@ inline ::std::string* MethodDescriptorProto::mutable_output_type() {
}
inline ::std::string* MethodDescriptorProto::release_output_type() {
// @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.output_type)
+ if (!has_output_type()) {
+ return NULL;
+ }
clear_has_output_type();
- return output_type_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return output_type_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void MethodDescriptorProto::set_allocated_output_type(::std::string* output_type) {
if (output_type != NULL) {
@@ -8821,6 +8899,9 @@ inline void MethodDescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
clear_has_options();
}
+inline const ::google::protobuf::MethodOptions& MethodDescriptorProto::_internal_options() const {
+ return *options_;
+}
inline const ::google::protobuf::MethodOptions& MethodDescriptorProto::options() const {
const ::google::protobuf::MethodOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.options)
@@ -8832,7 +8913,7 @@ inline ::google::protobuf::MethodOptions* MethodDescriptorProto::release_options
clear_has_options();
::google::protobuf::MethodOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
- temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
options_ = NULL;
return temp;
@@ -8847,8 +8928,8 @@ inline ::google::protobuf::MethodOptions* MethodDescriptorProto::unsafe_arena_re
inline ::google::protobuf::MethodOptions* MethodDescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::MethodOptions >(
- GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<::google::protobuf::MethodOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.options)
return options_;
@@ -8977,8 +9058,11 @@ inline ::std::string* FileOptions::mutable_java_package() {
}
inline ::std::string* FileOptions::release_java_package() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_package)
+ if (!has_java_package()) {
+ return NULL;
+ }
clear_has_java_package();
- return java_package_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return java_package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_java_package(::std::string* java_package) {
if (java_package != NULL) {
@@ -9062,8 +9146,11 @@ inline ::std::string* FileOptions::mutable_java_outer_classname() {
}
inline ::std::string* FileOptions::release_java_outer_classname() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_outer_classname)
+ if (!has_java_outer_classname()) {
+ return NULL;
+ }
clear_has_java_outer_classname();
- return java_outer_classname_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ 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) {
@@ -9097,13 +9184,13 @@ inline void FileOptions::unsafe_arena_set_allocated_java_outer_classname(
// optional bool java_multiple_files = 10 [default = false];
inline bool FileOptions::has_java_multiple_files() const {
- return (_has_bits_[0] & 0x00000200u) != 0;
+ return (_has_bits_[0] & 0x00000400u) != 0;
}
inline void FileOptions::set_has_java_multiple_files() {
- _has_bits_[0] |= 0x00000200u;
+ _has_bits_[0] |= 0x00000400u;
}
inline void FileOptions::clear_has_java_multiple_files() {
- _has_bits_[0] &= ~0x00000200u;
+ _has_bits_[0] &= ~0x00000400u;
}
inline void FileOptions::clear_java_multiple_files() {
java_multiple_files_ = false;
@@ -9121,13 +9208,13 @@ inline void FileOptions::set_java_multiple_files(bool value) {
// optional bool java_generate_equals_and_hash = 20 [deprecated = true];
inline bool FileOptions::has_java_generate_equals_and_hash() const {
- return (_has_bits_[0] & 0x00000400u) != 0;
+ return (_has_bits_[0] & 0x00000800u) != 0;
}
inline void FileOptions::set_has_java_generate_equals_and_hash() {
- _has_bits_[0] |= 0x00000400u;
+ _has_bits_[0] |= 0x00000800u;
}
inline void FileOptions::clear_has_java_generate_equals_and_hash() {
- _has_bits_[0] &= ~0x00000400u;
+ _has_bits_[0] &= ~0x00000800u;
}
inline void FileOptions::clear_java_generate_equals_and_hash() {
java_generate_equals_and_hash_ = false;
@@ -9145,13 +9232,13 @@ inline void FileOptions::set_java_generate_equals_and_hash(bool value) {
// optional bool java_string_check_utf8 = 27 [default = false];
inline bool FileOptions::has_java_string_check_utf8() const {
- return (_has_bits_[0] & 0x00000800u) != 0;
+ return (_has_bits_[0] & 0x00001000u) != 0;
}
inline void FileOptions::set_has_java_string_check_utf8() {
- _has_bits_[0] |= 0x00000800u;
+ _has_bits_[0] |= 0x00001000u;
}
inline void FileOptions::clear_has_java_string_check_utf8() {
- _has_bits_[0] &= ~0x00000800u;
+ _has_bits_[0] &= ~0x00001000u;
}
inline void FileOptions::clear_java_string_check_utf8() {
java_string_check_utf8_ = false;
@@ -9169,13 +9256,13 @@ inline void FileOptions::set_java_string_check_utf8(bool value) {
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
inline bool FileOptions::has_optimize_for() const {
- return (_has_bits_[0] & 0x00020000u) != 0;
+ return (_has_bits_[0] & 0x00080000u) != 0;
}
inline void FileOptions::set_has_optimize_for() {
- _has_bits_[0] |= 0x00020000u;
+ _has_bits_[0] |= 0x00080000u;
}
inline void FileOptions::clear_has_optimize_for() {
- _has_bits_[0] &= ~0x00020000u;
+ _has_bits_[0] &= ~0x00080000u;
}
inline void FileOptions::clear_optimize_for() {
optimize_for_ = 1;
@@ -9244,8 +9331,11 @@ inline ::std::string* FileOptions::mutable_go_package() {
}
inline ::std::string* FileOptions::release_go_package() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.go_package)
+ if (!has_go_package()) {
+ return NULL;
+ }
clear_has_go_package();
- return go_package_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return go_package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_go_package(::std::string* go_package) {
if (go_package != NULL) {
@@ -9279,13 +9369,13 @@ inline void FileOptions::unsafe_arena_set_allocated_go_package(
// optional bool cc_generic_services = 16 [default = false];
inline bool FileOptions::has_cc_generic_services() const {
- return (_has_bits_[0] & 0x00001000u) != 0;
+ return (_has_bits_[0] & 0x00002000u) != 0;
}
inline void FileOptions::set_has_cc_generic_services() {
- _has_bits_[0] |= 0x00001000u;
+ _has_bits_[0] |= 0x00002000u;
}
inline void FileOptions::clear_has_cc_generic_services() {
- _has_bits_[0] &= ~0x00001000u;
+ _has_bits_[0] &= ~0x00002000u;
}
inline void FileOptions::clear_cc_generic_services() {
cc_generic_services_ = false;
@@ -9303,13 +9393,13 @@ inline void FileOptions::set_cc_generic_services(bool value) {
// optional bool java_generic_services = 17 [default = false];
inline bool FileOptions::has_java_generic_services() const {
- return (_has_bits_[0] & 0x00002000u) != 0;
+ return (_has_bits_[0] & 0x00004000u) != 0;
}
inline void FileOptions::set_has_java_generic_services() {
- _has_bits_[0] |= 0x00002000u;
+ _has_bits_[0] |= 0x00004000u;
}
inline void FileOptions::clear_has_java_generic_services() {
- _has_bits_[0] &= ~0x00002000u;
+ _has_bits_[0] &= ~0x00004000u;
}
inline void FileOptions::clear_java_generic_services() {
java_generic_services_ = false;
@@ -9327,13 +9417,13 @@ inline void FileOptions::set_java_generic_services(bool value) {
// optional bool py_generic_services = 18 [default = false];
inline bool FileOptions::has_py_generic_services() const {
- return (_has_bits_[0] & 0x00004000u) != 0;
+ return (_has_bits_[0] & 0x00008000u) != 0;
}
inline void FileOptions::set_has_py_generic_services() {
- _has_bits_[0] |= 0x00004000u;
+ _has_bits_[0] |= 0x00008000u;
}
inline void FileOptions::clear_has_py_generic_services() {
- _has_bits_[0] &= ~0x00004000u;
+ _has_bits_[0] &= ~0x00008000u;
}
inline void FileOptions::clear_py_generic_services() {
py_generic_services_ = false;
@@ -9351,13 +9441,13 @@ inline void FileOptions::set_py_generic_services(bool value) {
// optional bool php_generic_services = 42 [default = false];
inline bool FileOptions::has_php_generic_services() const {
- return (_has_bits_[0] & 0x00008000u) != 0;
+ return (_has_bits_[0] & 0x00010000u) != 0;
}
inline void FileOptions::set_has_php_generic_services() {
- _has_bits_[0] |= 0x00008000u;
+ _has_bits_[0] |= 0x00010000u;
}
inline void FileOptions::clear_has_php_generic_services() {
- _has_bits_[0] &= ~0x00008000u;
+ _has_bits_[0] &= ~0x00010000u;
}
inline void FileOptions::clear_php_generic_services() {
php_generic_services_ = false;
@@ -9375,13 +9465,13 @@ inline void FileOptions::set_php_generic_services(bool value) {
// optional bool deprecated = 23 [default = false];
inline bool FileOptions::has_deprecated() const {
- return (_has_bits_[0] & 0x00010000u) != 0;
+ return (_has_bits_[0] & 0x00020000u) != 0;
}
inline void FileOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00010000u;
+ _has_bits_[0] |= 0x00020000u;
}
inline void FileOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00010000u;
+ _has_bits_[0] &= ~0x00020000u;
}
inline void FileOptions::clear_deprecated() {
deprecated_ = false;
@@ -9399,13 +9489,13 @@ inline void FileOptions::set_deprecated(bool value) {
// optional bool cc_enable_arenas = 31 [default = false];
inline bool FileOptions::has_cc_enable_arenas() const {
- return (_has_bits_[0] & 0x00000100u) != 0;
+ return (_has_bits_[0] & 0x00040000u) != 0;
}
inline void FileOptions::set_has_cc_enable_arenas() {
- _has_bits_[0] |= 0x00000100u;
+ _has_bits_[0] |= 0x00040000u;
}
inline void FileOptions::clear_has_cc_enable_arenas() {
- _has_bits_[0] &= ~0x00000100u;
+ _has_bits_[0] &= ~0x00040000u;
}
inline void FileOptions::clear_cc_enable_arenas() {
cc_enable_arenas_ = false;
@@ -9473,8 +9563,11 @@ inline ::std::string* FileOptions::mutable_objc_class_prefix() {
}
inline ::std::string* FileOptions::release_objc_class_prefix() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.objc_class_prefix)
+ if (!has_objc_class_prefix()) {
+ return NULL;
+ }
clear_has_objc_class_prefix();
- return objc_class_prefix_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ 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) {
@@ -9558,8 +9651,11 @@ inline ::std::string* FileOptions::mutable_csharp_namespace() {
}
inline ::std::string* FileOptions::release_csharp_namespace() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.csharp_namespace)
+ if (!has_csharp_namespace()) {
+ return NULL;
+ }
clear_has_csharp_namespace();
- return csharp_namespace_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return csharp_namespace_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_csharp_namespace(::std::string* csharp_namespace) {
if (csharp_namespace != NULL) {
@@ -9643,8 +9739,11 @@ inline ::std::string* FileOptions::mutable_swift_prefix() {
}
inline ::std::string* FileOptions::release_swift_prefix() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.swift_prefix)
+ if (!has_swift_prefix()) {
+ return NULL;
+ }
clear_has_swift_prefix();
- return swift_prefix_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return swift_prefix_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_swift_prefix(::std::string* swift_prefix) {
if (swift_prefix != NULL) {
@@ -9728,8 +9827,11 @@ inline ::std::string* FileOptions::mutable_php_class_prefix() {
}
inline ::std::string* FileOptions::release_php_class_prefix() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_class_prefix)
+ if (!has_php_class_prefix()) {
+ return NULL;
+ }
clear_has_php_class_prefix();
- return php_class_prefix_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ 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) {
@@ -9813,8 +9915,11 @@ inline ::std::string* FileOptions::mutable_php_namespace() {
}
inline ::std::string* FileOptions::release_php_namespace() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_namespace)
+ if (!has_php_namespace()) {
+ return NULL;
+ }
clear_has_php_namespace();
- return php_namespace_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return php_namespace_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_php_namespace(::std::string* php_namespace) {
if (php_namespace != NULL) {
@@ -9846,6 +9951,182 @@ inline void FileOptions::unsafe_arena_set_allocated_php_namespace(
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.php_namespace)
}
+// optional string php_metadata_namespace = 44;
+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();
+}
+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();
+ 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();
+ php_metadata_namespace_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.php_metadata_namespace)
+}
+#endif
+inline void FileOptions::set_php_metadata_namespace(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
+ set_has_php_metadata_namespace();
+ 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();
+ 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();
+ // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.php_metadata_namespace)
+ return php_metadata_namespace_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+inline ::std::string* FileOptions::release_php_metadata_namespace() {
+ // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_metadata_namespace)
+ if (!has_php_metadata_namespace()) {
+ return NULL;
+ }
+ clear_has_php_metadata_namespace();
+ 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();
+ } else {
+ clear_has_php_metadata_namespace();
+ }
+ php_metadata_namespace_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), php_metadata_namespace,
+ GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.php_metadata_namespace)
+}
+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();
+ return php_metadata_namespace_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+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();
+ } else {
+ clear_has_php_metadata_namespace();
+ }
+ php_metadata_namespace_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ php_metadata_namespace, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.php_metadata_namespace)
+}
+
+// optional string ruby_package = 45;
+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();
+}
+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();
+ 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();
+ ruby_package_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.ruby_package)
+}
+#endif
+inline void FileOptions::set_ruby_package(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
+ set_has_ruby_package();
+ 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();
+ 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();
+ // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.ruby_package)
+ return ruby_package_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+inline ::std::string* FileOptions::release_ruby_package() {
+ // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.ruby_package)
+ if (!has_ruby_package()) {
+ return NULL;
+ }
+ clear_has_ruby_package();
+ 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();
+ } else {
+ clear_has_ruby_package();
+ }
+ ruby_package_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ruby_package,
+ GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.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();
+ return ruby_package_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+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();
+ } else {
+ clear_has_ruby_package();
+ }
+ ruby_package_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ ruby_package, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.ruby_package)
+}
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
inline int FileOptions::uninterpreted_option_size() const {
return uninterpreted_option_.size();
@@ -10557,8 +10838,11 @@ inline ::std::string* UninterpretedOption_NamePart::mutable_name_part() {
}
inline ::std::string* UninterpretedOption_NamePart::release_name_part() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.NamePart.name_part)
+ if (!has_name_part()) {
+ return NULL;
+ }
clear_has_name_part();
- return name_part_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ 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) {
@@ -10700,8 +10984,11 @@ inline ::std::string* UninterpretedOption::mutable_identifier_value() {
}
inline ::std::string* UninterpretedOption::release_identifier_value() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.identifier_value)
+ if (!has_identifier_value()) {
+ return NULL;
+ }
clear_has_identifier_value();
- return identifier_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return identifier_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void UninterpretedOption::set_allocated_identifier_value(::std::string* identifier_value) {
if (identifier_value != NULL) {
@@ -10857,8 +11144,11 @@ inline ::std::string* UninterpretedOption::mutable_string_value() {
}
inline ::std::string* UninterpretedOption::release_string_value() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.string_value)
+ if (!has_string_value()) {
+ return NULL;
+ }
clear_has_string_value();
- return string_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return string_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void UninterpretedOption::set_allocated_string_value(::std::string* string_value) {
if (string_value != NULL) {
@@ -10942,8 +11232,11 @@ inline ::std::string* UninterpretedOption::mutable_aggregate_value() {
}
inline ::std::string* UninterpretedOption::release_aggregate_value() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.aggregate_value)
+ if (!has_aggregate_value()) {
+ return NULL;
+ }
clear_has_aggregate_value();
- return aggregate_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return aggregate_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void UninterpretedOption::set_allocated_aggregate_value(::std::string* aggregate_value) {
if (aggregate_value != NULL) {
@@ -11091,8 +11384,11 @@ inline ::std::string* SourceCodeInfo_Location::mutable_leading_comments() {
}
inline ::std::string* SourceCodeInfo_Location::release_leading_comments() {
// @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.leading_comments)
+ if (!has_leading_comments()) {
+ return NULL;
+ }
clear_has_leading_comments();
- return leading_comments_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ 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) {
@@ -11176,8 +11472,11 @@ inline ::std::string* SourceCodeInfo_Location::mutable_trailing_comments() {
}
inline ::std::string* SourceCodeInfo_Location::release_trailing_comments() {
// @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.trailing_comments)
+ if (!has_trailing_comments()) {
+ return NULL;
+ }
clear_has_trailing_comments();
- return trailing_comments_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ 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) {
@@ -11398,8 +11697,11 @@ inline ::std::string* GeneratedCodeInfo_Annotation::mutable_source_file() {
}
inline ::std::string* GeneratedCodeInfo_Annotation::release_source_file() {
// @@protoc_insertion_point(field_release:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
+ if (!has_source_file()) {
+ return NULL;
+ }
clear_has_source_file();
- return source_file_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ 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) {
@@ -11577,32 +11879,32 @@ GeneratedCodeInfo::annotation() const {
namespace google {
namespace protobuf {
-template <> struct is_proto_enum< ::google::protobuf::FieldDescriptorProto_Type> : ::google::protobuf::internal::true_type {};
+template <> struct is_proto_enum< ::google::protobuf::FieldDescriptorProto_Type> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldDescriptorProto_Type>() {
return ::google::protobuf::FieldDescriptorProto_Type_descriptor();
}
-template <> struct is_proto_enum< ::google::protobuf::FieldDescriptorProto_Label> : ::google::protobuf::internal::true_type {};
+template <> struct is_proto_enum< ::google::protobuf::FieldDescriptorProto_Label> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldDescriptorProto_Label>() {
return ::google::protobuf::FieldDescriptorProto_Label_descriptor();
}
-template <> struct is_proto_enum< ::google::protobuf::FileOptions_OptimizeMode> : ::google::protobuf::internal::true_type {};
+template <> struct is_proto_enum< ::google::protobuf::FileOptions_OptimizeMode> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FileOptions_OptimizeMode>() {
return ::google::protobuf::FileOptions_OptimizeMode_descriptor();
}
-template <> struct is_proto_enum< ::google::protobuf::FieldOptions_CType> : ::google::protobuf::internal::true_type {};
+template <> struct is_proto_enum< ::google::protobuf::FieldOptions_CType> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldOptions_CType>() {
return ::google::protobuf::FieldOptions_CType_descriptor();
}
-template <> struct is_proto_enum< ::google::protobuf::FieldOptions_JSType> : ::google::protobuf::internal::true_type {};
+template <> struct is_proto_enum< ::google::protobuf::FieldOptions_JSType> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldOptions_JSType>() {
return ::google::protobuf::FieldOptions_JSType_descriptor();
}
-template <> struct is_proto_enum< ::google::protobuf::MethodOptions_IdempotencyLevel> : ::google::protobuf::internal::true_type {};
+template <> struct is_proto_enum< ::google::protobuf::MethodOptions_IdempotencyLevel> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::MethodOptions_IdempotencyLevel>() {
return ::google::protobuf::MethodOptions_IdempotencyLevel_descriptor();
@@ -11613,4 +11915,4 @@ inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::MethodOption
// @@protoc_insertion_point(global_scope)
-#endif // PROTOBUF_google_2fprotobuf_2fdescriptor_2eproto_INCLUDED
+#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto
diff --git a/src/google/protobuf/descriptor.proto b/src/google/protobuf/descriptor.proto
index 8697a50d..ed08fcbc 100644
--- a/src/google/protobuf/descriptor.proto
+++ b/src/google/protobuf/descriptor.proto
@@ -417,6 +417,17 @@ message FileOptions {
// determining the namespace.
optional string php_namespace = 41;
+
+ // Use this option to change the namespace of php generated metadata classes.
+ // Default is empty. When this option is empty, the proto file name will be used
+ // for determining the namespace.
+ optional string php_metadata_namespace = 44;
+
+ // Use this option to change the package of ruby generated classes. Default
+ // is empty. When this option is not set, the package name will be used for
+ // determining the ruby package.
+ optional string ruby_package = 45;
+
// The parser stores options it doesn't recognize here.
// See the documentation for the "Options" section above.
repeated UninterpretedOption uninterpreted_option = 999;
diff --git a/src/google/protobuf/descriptor_database.h b/src/google/protobuf/descriptor_database.h
index 28f8af7a..07523660 100644
--- a/src/google/protobuf/descriptor_database.h
+++ b/src/google/protobuf/descriptor_database.h
@@ -142,7 +142,7 @@ class LIBPROTOBUF_EXPORT DescriptorDatabase {
class LIBPROTOBUF_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
@@ -155,14 +155,14 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase {
// implements DescriptorDatabase -----------------------------------
bool FindFileByName(const string& filename,
- FileDescriptorProto* output);
+ FileDescriptorProto* output) override;
bool FindFileContainingSymbol(const string& symbol_name,
- FileDescriptorProto* output);
+ FileDescriptorProto* output) override;
bool FindFileContainingExtension(const string& containing_type,
int field_number,
- FileDescriptorProto* output);
+ FileDescriptorProto* output) override;
bool FindAllExtensionNumbers(const string& extendee_type,
- std::vector<int>* output);
+ std::vector<int>* output) override;
private:
// So that it can use DescriptorIndex.
@@ -214,7 +214,7 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase {
// will find it. Proof:
// 1) Define the "search key" to be the key we are looking for, the "found
// key" to be the key found in step (1), and the "match key" to be the
- // key which actually matches the serach key (i.e. the key we're trying
+ // key which actually matches the search key (i.e. the key we're trying
// to find).
// 2) The found key must be less than or equal to the search key by
// definition.
@@ -280,7 +280,7 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase {
class LIBPROTOBUF_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
@@ -300,14 +300,14 @@ class LIBPROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase {
// implements DescriptorDatabase -----------------------------------
bool FindFileByName(const string& filename,
- FileDescriptorProto* output);
+ FileDescriptorProto* output) override;
bool FindFileContainingSymbol(const string& symbol_name,
- FileDescriptorProto* output);
+ FileDescriptorProto* output) override;
bool FindFileContainingExtension(const string& containing_type,
int field_number,
- FileDescriptorProto* output);
+ FileDescriptorProto* output) override;
bool FindAllExtensionNumbers(const string& extendee_type,
- std::vector<int>* output);
+ std::vector<int>* output) override;
private:
SimpleDescriptorDatabase::DescriptorIndex<std::pair<const void*, int> >
@@ -326,18 +326,18 @@ class LIBPROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase {
class LIBPROTOBUF_EXPORT DescriptorPoolDatabase : public DescriptorDatabase {
public:
explicit DescriptorPoolDatabase(const DescriptorPool& pool);
- ~DescriptorPoolDatabase();
+ ~DescriptorPoolDatabase() override;
// implements DescriptorDatabase -----------------------------------
bool FindFileByName(const string& filename,
- FileDescriptorProto* output);
+ FileDescriptorProto* output) override;
bool FindFileContainingSymbol(const string& symbol_name,
- FileDescriptorProto* output);
+ FileDescriptorProto* output) override;
bool FindFileContainingExtension(const string& containing_type,
int field_number,
- FileDescriptorProto* output);
+ FileDescriptorProto* output) override;
bool FindAllExtensionNumbers(const string& extendee_type,
- std::vector<int>* output);
+ std::vector<int>* output) override;
private:
const DescriptorPool& pool_;
@@ -356,20 +356,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);
+ FileDescriptorProto* output) override;
bool FindFileContainingSymbol(const string& symbol_name,
- FileDescriptorProto* output);
+ FileDescriptorProto* output) override;
bool FindFileContainingExtension(const 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);
+ std::vector<int>* output) override;
private:
diff --git a/src/google/protobuf/descriptor_database_unittest.cc b/src/google/protobuf/descriptor_database_unittest.cc
index 9d710886..083ef8f2 100644
--- a/src/google/protobuf/descriptor_database_unittest.cc
+++ b/src/google/protobuf/descriptor_database_unittest.cc
@@ -36,13 +36,10 @@
#include <algorithm>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
-#include <google/protobuf/descriptor_database.h>
-#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/descriptor_database.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/stubs/logging.h>
@@ -179,7 +176,7 @@ class DescriptorDatabaseTest
EXPECT_FALSE(test_case_->AddToDatabase(file_proto));
}
- google::protobuf::scoped_ptr<DescriptorDatabaseTestCase> test_case_;
+ std::unique_ptr<DescriptorDatabaseTestCase> test_case_;
DescriptorDatabase* database_;
};
diff --git a/src/google/protobuf/descriptor_unittest.cc b/src/google/protobuf/descriptor_unittest.cc
index b0337035..54da095a 100644
--- a/src/google/protobuf/descriptor_unittest.cc
+++ b/src/google/protobuf/descriptor_unittest.cc
@@ -36,9 +36,6 @@
#include <limits>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
#include <google/protobuf/compiler/importer.h>
@@ -2252,7 +2249,7 @@ class MiscTest : public testing::Test {
return field != NULL ? field->enum_type() : NULL;
}
- google::protobuf::scoped_ptr<DescriptorPool> pool_;
+ std::unique_ptr<DescriptorPool> pool_;
};
TEST_F(MiscTest, TypeNames) {
@@ -2682,7 +2679,7 @@ class AllowUnknownDependenciesTest
const FieldDescriptor* qux_field_;
SimpleDescriptorDatabase db_; // used if in FALLBACK_DATABASE mode.
- google::protobuf::scoped_ptr<DescriptorPool> pool_;
+ std::unique_ptr<DescriptorPool> pool_;
};
TEST_P(AllowUnknownDependenciesTest, PlaceholderFile) {
@@ -3952,8 +3949,22 @@ TEST_F(ValidationErrorTest, EnumReservedRangeOverlap) {
" reserved_range { start: 5 end: 15 }"
"}",
- "foo.proto: Foo: NUMBER: Reserved range 5 to 14"
- " overlaps with already-defined range 10 to 19.\n");
+ "foo.proto: Foo: NUMBER: Reserved range 5 to 15"
+ " overlaps with already-defined range 10 to 20.\n");
+}
+
+TEST_F(ValidationErrorTest, EnumReservedRangeOverlapByOne) {
+ BuildFileWithErrors(
+ "name: \"foo.proto\" "
+ "enum_type {"
+ " name: \"Foo\""
+ " value { name:\"BAR\" number:0 }"
+ " reserved_range { start: 10 end: 20 }"
+ " reserved_range { start: 5 end: 10 }"
+ "}",
+
+ "foo.proto: Foo: NUMBER: Reserved range 5 to 10"
+ " overlaps with already-defined range 10 to 20.\n");
}
TEST_F(ValidationErrorTest, EnumNegativeReservedRangeOverlap) {
@@ -3966,8 +3977,8 @@ TEST_F(ValidationErrorTest, EnumNegativeReservedRangeOverlap) {
" reserved_range { start: -15 end: -5 }"
"}",
- "foo.proto: Foo: NUMBER: Reserved range -15 to -6"
- " overlaps with already-defined range -20 to -11.\n");
+ "foo.proto: Foo: NUMBER: Reserved range -15 to -5"
+ " overlaps with already-defined range -20 to -10.\n");
}
TEST_F(ValidationErrorTest, EnumMixedReservedRangeOverlap) {
@@ -3980,8 +3991,22 @@ TEST_F(ValidationErrorTest, EnumMixedReservedRangeOverlap) {
" reserved_range { start: -15 end: 5 }"
"}",
- "foo.proto: Foo: NUMBER: Reserved range -15 to 4"
- " overlaps with already-defined range -20 to 9.\n");
+ "foo.proto: Foo: NUMBER: Reserved range -15 to 5"
+ " overlaps with already-defined range -20 to 10.\n");
+}
+
+TEST_F(ValidationErrorTest, EnumMixedReservedRangeOverlap2) {
+ BuildFileWithErrors(
+ "name: \"foo.proto\" "
+ "enum_type {"
+ " name: \"Foo\""
+ " value { name:\"BAR\" number:20 }"
+ " reserved_range { start: -20 end: 10 }"
+ " reserved_range { start: 10 end: 10 }"
+ "}",
+
+ "foo.proto: Foo: NUMBER: Reserved range 10 to 10"
+ " overlaps with already-defined range -20 to 10.\n");
}
TEST_F(ValidationErrorTest, EnumReservedRangeStartGreaterThanEnd) {
@@ -6893,40 +6918,95 @@ class SingletonSourceTree : public compiler::SourceTree {
const char *const kSourceLocationTestInput =
"syntax = \"proto2\";\n"
+ "option java_package = \"com.foo.bar\";\n"
+ "option (test_file_opt) = \"foobar\";\n"
"message A {\n"
- " optional int32 a = 1;\n"
+ " option (test_msg_opt) = \"foobar\";\n"
+ " optional int32 a = 1 [deprecated = true];\n"
" message B {\n"
- " required double b = 1;\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"
- " YES = 1;\n"
- " NO = 2;\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 max;\n"
+ " extensions 1000 to 2000, 2001 to max [(test_ext_opt) = \"foobar\"];\n"
"}\n"
"extend MessageWithExtensions {\n"
- " optional int32 int32_extension = 1001;\n"
+ " repeated int32 int32_extension = 1001 [packed=true];\n"
"}\n"
"message C {\n"
" extend MessageWithExtensions {\n"
" optional C message_extension = 1002;\n"
" }\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:
SourceLocationTest()
: source_tree_("/test/test.proto", kSourceLocationTestInput),
- db_(&source_tree_),
- pool_(&db_, &collector_) {}
+ simple_db_(),
+ source_tree_db_(&source_tree_),
+ merged_db_(&simple_db_, &source_tree_db_),
+ pool_(&merged_db_, &collector_) {
+ // we need descriptor.proto to be accessible by the pool
+ // since our test file imports it
+ FileDescriptorProto::descriptor()->file()->CopyTo(&file_proto_);
+ simple_db_.Add(file_proto_);
+ }
static string PrintSourceLocation(const SourceLocation &loc) {
return strings::Substitute("$0:$1-$2:$3",
@@ -6937,12 +7017,20 @@ class SourceLocationTest : public testing::Test {
}
private:
+ FileDescriptorProto file_proto_;
AbortingErrorCollector collector_;
SingletonSourceTree source_tree_;
- compiler::SourceTreeDescriptorDatabase db_;
+ SimpleDescriptorDatabase simple_db_; // contains descriptor.proto
+ compiler::SourceTreeDescriptorDatabase source_tree_db_; // loads test.proto
+ MergedDescriptorDatabase merged_db_; // combines above two dbs
protected:
DescriptorPool pool_;
+
+ // 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;
};
// TODO(adonovan): implement support for option fields and for
@@ -6956,27 +7044,27 @@ TEST_F(SourceLocationTest, GetSourceLocation) {
const Descriptor *a_desc = file_desc->FindMessageTypeByName("A");
EXPECT_TRUE(a_desc->GetSourceLocation(&loc));
- EXPECT_EQ("2:1-7:2", PrintSourceLocation(loc));
+ EXPECT_EQ("4:1-16:2", PrintSourceLocation(loc));
const Descriptor *a_b_desc = a_desc->FindNestedTypeByName("B");
EXPECT_TRUE(a_b_desc->GetSourceLocation(&loc));
- EXPECT_EQ("4:3-6:4", PrintSourceLocation(loc));
+ EXPECT_EQ("7:3-9:4", PrintSourceLocation(loc));
const EnumDescriptor *e_desc = file_desc->FindEnumTypeByName("Indecision");
EXPECT_TRUE(e_desc->GetSourceLocation(&loc));
- EXPECT_EQ("8:1-12:2", PrintSourceLocation(loc));
+ EXPECT_EQ("17:1-24:2", PrintSourceLocation(loc));
const EnumValueDescriptor *yes_desc = e_desc->FindValueByName("YES");
EXPECT_TRUE(yes_desc->GetSourceLocation(&loc));
- EXPECT_EQ("9:3-9:13", PrintSourceLocation(loc));
+ EXPECT_EQ("21:3-21:42", PrintSourceLocation(loc));
const ServiceDescriptor *s_desc = file_desc->FindServiceByName("S");
EXPECT_TRUE(s_desc->GetSourceLocation(&loc));
- EXPECT_EQ("13:1-16:2", PrintSourceLocation(loc));
+ EXPECT_EQ("25:1-35:2", PrintSourceLocation(loc));
const MethodDescriptor *m_desc = s_desc->FindMethodByName("Method");
EXPECT_TRUE(m_desc->GetSourceLocation(&loc));
- EXPECT_EQ("14:3-14:31", PrintSourceLocation(loc));
+ EXPECT_EQ("29:3-29:31", PrintSourceLocation(loc));
}
@@ -6989,16 +7077,426 @@ TEST_F(SourceLocationTest, ExtensionSourceLocation) {
const FieldDescriptor *int32_extension_desc =
file_desc->FindExtensionByName("int32_extension");
EXPECT_TRUE(int32_extension_desc->GetSourceLocation(&loc));
- EXPECT_EQ("21:3-21:41", PrintSourceLocation(loc));
+ EXPECT_EQ("40:3-40:55", PrintSourceLocation(loc));
const Descriptor *c_desc = file_desc->FindMessageTypeByName("C");
EXPECT_TRUE(c_desc->GetSourceLocation(&loc));
- EXPECT_EQ("23:1-27:2", PrintSourceLocation(loc));
+ EXPECT_EQ("42:1-46:2", PrintSourceLocation(loc));
const FieldDescriptor *message_extension_desc =
c_desc->FindExtensionByName("message_extension");
EXPECT_TRUE(message_extension_desc->GetSourceLocation(&loc));
- EXPECT_EQ("25:5-25:41", PrintSourceLocation(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.
+
+ // We are verifying that the file's source info contains correct
+ // info for interpreted options and that it does *not* contain
+ // any info for corresponding uninterpreted option path.
+
+ SourceLocation loc;
+
+ const FileDescriptor *file_desc =
+ GOOGLE_CHECK_NOTNULL(pool_.FindFileByName("/test/test.proto"));
+
+ // File options
+ {
+ int path[] = {FileDescriptorProto::kOptionsFieldNumber,
+ FileOptions::kJavaPackageFieldNumber};
+ int unint[] = {FileDescriptorProto::kOptionsFieldNumber,
+ FileOptions::kUninterpretedOptionFieldNumber,
+ 0};
+
+ std::vector<int> vpath(path, path + 2);
+ EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
+ EXPECT_EQ("2:1-2:37", PrintSourceLocation(loc));
+
+ std::vector<int> vunint(unint, unint + 3);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+ {
+ int path[] = {FileDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber};
+ int unint[] = {FileDescriptorProto::kOptionsFieldNumber,
+ 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));
+
+ std::vector<int> vunint(unint, unint + 3);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+
+ // Message option
+ {
+ int path[] = {FileDescriptorProto::kMessageTypeFieldNumber,
+ 0,
+ DescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber};
+ int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber,
+ 0,
+ DescriptorProto::kOptionsFieldNumber,
+ 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));
+
+ std::vector<int> vunint(unint, unint + 5);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+
+ // Field option
+ {
+ int path[] = {FileDescriptorProto::kMessageTypeFieldNumber,
+ 0,
+ DescriptorProto::kFieldFieldNumber,
+ 0,
+ FieldDescriptorProto::kOptionsFieldNumber,
+ FieldOptions::kDeprecatedFieldNumber};
+ int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber,
+ 0,
+ DescriptorProto::kFieldFieldNumber,
+ 0,
+ FieldDescriptorProto::kOptionsFieldNumber,
+ FieldOptions::kUninterpretedOptionFieldNumber,
+ 0};
+ std::vector<int> vpath(path, path + 6);
+ EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
+ EXPECT_EQ("6:25-6:42", PrintSourceLocation(loc));
+
+ std::vector<int> vunint(unint, unint + 7);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+
+ // Nested message option
+ {
+ int path[] = {FileDescriptorProto::kMessageTypeFieldNumber,
+ 0,
+ DescriptorProto::kNestedTypeFieldNumber,
+ 0,
+ DescriptorProto::kFieldFieldNumber,
+ 0,
+ FieldDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber};
+ int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber,
+ 0,
+ DescriptorProto::kNestedTypeFieldNumber,
+ 0,
+ DescriptorProto::kFieldFieldNumber,
+ 0,
+ FieldDescriptorProto::kOptionsFieldNumber,
+ FieldOptions::kUninterpretedOptionFieldNumber,
+ 0};
+ std::vector<int> vpath(path, path + 8);
+ EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
+ EXPECT_EQ("8:28-8:55", PrintSourceLocation(loc));
+
+ std::vector<int> vunint(unint, unint + 9);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+
+ // One-of option
+ {
+ int path[] = {FileDescriptorProto::kMessageTypeFieldNumber,
+ 0,
+ DescriptorProto::kOneofDeclFieldNumber,
+ 0,
+ OneofDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber};
+ int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber,
+ 0,
+ DescriptorProto::kOneofDeclFieldNumber,
+ 0,
+ OneofDescriptorProto::kOptionsFieldNumber,
+ OneofOptions::kUninterpretedOptionFieldNumber,
+ 0};
+ std::vector<int> vpath(path, path + 6);
+ EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
+ EXPECT_EQ("11:5-11:40", PrintSourceLocation(loc));
+
+ std::vector<int> vunint(unint, unint + 7);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+
+ // Enum option, repeated options
+ {
+ int path[] = {FileDescriptorProto::kEnumTypeFieldNumber,
+ 0,
+ EnumDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber,
+ 0};
+ int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber,
+ 0,
+ EnumDescriptorProto::kOptionsFieldNumber,
+ 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));
+
+ std::vector<int> vunint(unint, unint + 5);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+ {
+ int path[] = {FileDescriptorProto::kEnumTypeFieldNumber,
+ 0,
+ EnumDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber,
+ 1};
+ int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber,
+ 0,
+ EnumDescriptorProto::kOptionsFieldNumber,
+ 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));
+
+ std::vector<int> vunint(unint, unint + 5);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+ {
+ int path[] = {FileDescriptorProto::kEnumTypeFieldNumber,
+ 0,
+ EnumDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber,
+ 2};
+ int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber,
+ 0,
+ EnumDescriptorProto::kOptionsFieldNumber,
+ 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));
+
+ std::vector<int> vunint(unint, unint + 5);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+
+ // 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 unint[] = {FileDescriptorProto::kEnumTypeFieldNumber,
+ 0,
+ EnumDescriptorProto::kValueFieldNumber,
+ 0,
+ EnumValueDescriptorProto::kOptionsFieldNumber,
+ EnumValueOptions::kUninterpretedOptionFieldNumber,
+ 0};
+ std::vector<int> vpath(path, path + 7);
+ EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
+ EXPECT_EQ("21:14-21:40", PrintSourceLocation(loc));
+
+ std::vector<int> vunint(unint, unint + 7);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+ {
+ int path[] = {FileDescriptorProto::kEnumTypeFieldNumber,
+ 0,
+ EnumDescriptorProto::kValueFieldNumber,
+ 1,
+ EnumValueDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber};
+ int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber,
+ 0,
+ EnumDescriptorProto::kValueFieldNumber,
+ 1,
+ EnumValueDescriptorProto::kOptionsFieldNumber,
+ EnumValueOptions::kUninterpretedOptionFieldNumber,
+ 0};
+ std::vector<int> vpath(path, path + 6);
+ EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
+ EXPECT_EQ("22:14-22:42", PrintSourceLocation(loc));
+
+ std::vector<int> vunint(unint, unint + 7);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+
+ // Service option, repeated options
+ {
+ int path[] = {FileDescriptorProto::kServiceFieldNumber,
+ 0,
+ ServiceDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber,
+ 0};
+ int unint[] = {FileDescriptorProto::kServiceFieldNumber,
+ 0,
+ ServiceDescriptorProto::kOptionsFieldNumber,
+ 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));
+
+ std::vector<int> vunint(unint, unint + 5);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+ {
+ int path[] = {FileDescriptorProto::kServiceFieldNumber,
+ 0,
+ ServiceDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber,
+ 1};
+ int unint[] = {FileDescriptorProto::kServiceFieldNumber,
+ 0,
+ ServiceDescriptorProto::kOptionsFieldNumber,
+ 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));
+
+ std::vector<int> vunint(unint, unint + 5);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+ {
+ int path[] = {FileDescriptorProto::kServiceFieldNumber,
+ 0,
+ ServiceDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber,
+ 2};
+ int unint[] = {FileDescriptorProto::kServiceFieldNumber,
+ 0,
+ ServiceDescriptorProto::kOptionsFieldNumber,
+ 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));
+
+ std::vector<int> vunint(unint, unint + 5);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+
+ // Method options
+ {
+ int path[] = {FileDescriptorProto::kServiceFieldNumber,
+ 0,
+ ServiceDescriptorProto::kMethodFieldNumber,
+ 1,
+ MethodDescriptorProto::kOptionsFieldNumber,
+ MethodOptions::kDeprecatedFieldNumber};
+ int unint[] = {FileDescriptorProto::kServiceFieldNumber,
+ 0,
+ ServiceDescriptorProto::kMethodFieldNumber,
+ 1,
+ MethodDescriptorProto::kOptionsFieldNumber,
+ MethodOptions::kUninterpretedOptionFieldNumber,
+ 0};
+ std::vector<int> vpath(path, path + 6);
+ EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
+ EXPECT_EQ("32:5-32:30", PrintSourceLocation(loc));
+
+ std::vector<int> vunint(unint, unint + 7);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+ {
+ int path[] = {FileDescriptorProto::kServiceFieldNumber,
+ 0,
+ ServiceDescriptorProto::kMethodFieldNumber,
+ 1,
+ MethodDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber};
+ int unint[] = {FileDescriptorProto::kServiceFieldNumber,
+ 0,
+ ServiceDescriptorProto::kMethodFieldNumber,
+ 1,
+ MethodDescriptorProto::kOptionsFieldNumber,
+ MethodOptions::kUninterpretedOptionFieldNumber,
+ 1};
+ std::vector<int> vpath(path, path + 6);
+ EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
+ EXPECT_EQ("33:5-33:41", PrintSourceLocation(loc));
+
+ std::vector<int> vunint(unint, unint + 7);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+
+ // Extension range options
+ {
+ 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 unint[] = {FileDescriptorProto::kMessageTypeFieldNumber,
+ 1,
+ DescriptorProto::kExtensionRangeFieldNumber,
+ 0,
+ DescriptorProto_ExtensionRange::kOptionsFieldNumber,
+ ExtensionRangeOptions::kUninterpretedOptionFieldNumber,
+ 0};
+ std::vector<int> vpath(path, path + 6);
+ EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
+ EXPECT_EQ("37:41-37:66", PrintSourceLocation(loc));
+
+ std::vector<int> vunint(unint, unint + 7);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+ {
+ int path[] = {FileDescriptorProto::kMessageTypeFieldNumber,
+ 1,
+ DescriptorProto::kExtensionRangeFieldNumber,
+ 1,
+ DescriptorProto_ExtensionRange::kOptionsFieldNumber,
+ kCustomOptionFieldNumber};
+ int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber,
+ 1,
+ DescriptorProto::kExtensionRangeFieldNumber,
+ 1,
+ DescriptorProto_ExtensionRange::kOptionsFieldNumber,
+ ExtensionRangeOptions::kUninterpretedOptionFieldNumber,
+ 0};
+ std::vector<int> vpath(path, path + 6);
+ EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
+ EXPECT_EQ("37:41-37:66", PrintSourceLocation(loc));
+
+ std::vector<int> vunint(unint, unint + 7);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
+
+ // Field option on extension
+ {
+ int path[] = {FileDescriptorProto::kExtensionFieldNumber,
+ 0,
+ FieldDescriptorProto::kOptionsFieldNumber,
+ FieldOptions::kPackedFieldNumber};
+ int unint[] = {FileDescriptorProto::kExtensionFieldNumber,
+ 0,
+ FieldDescriptorProto::kOptionsFieldNumber,
+ 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));
+
+ std::vector<int> vunint(unint, unint + 5);
+ EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
+ }
}
// Missing SourceCodeInfo doesn't cause crash:
diff --git a/src/google/protobuf/drop_unknown_fields_test.cc b/src/google/protobuf/drop_unknown_fields_test.cc
index f2f2f749..437a04e7 100644
--- a/src/google/protobuf/drop_unknown_fields_test.cc
+++ b/src/google/protobuf/drop_unknown_fields_test.cc
@@ -29,9 +29,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/unittest_drop_unknown_fields.pb.h>
#include <google/protobuf/dynamic_message.h>
@@ -94,7 +91,7 @@ TEST(DropUnknownFieldsTest, DynamicMessageDefaultDrop) {
foo_with_extra_fields.set_extra_int32_value(2);
google::protobuf::DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<google::protobuf::Message> foo(
+ 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());
@@ -114,7 +111,7 @@ TEST(DropUnknownFieldsTest, DynamicMessageDefaultPreserve) {
foo_with_extra_fields.set_extra_int32_value(2);
google::protobuf::DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<google::protobuf::Message> foo(
+ std::unique_ptr<google::protobuf::Message> foo(
factory.GetPrototype(Foo::descriptor())->New());
ASSERT_TRUE(foo->ParseFromString(foo_with_extra_fields.SerializeAsString()));
EXPECT_FALSE(foo->GetReflection()->GetUnknownFields(*foo).empty());
diff --git a/src/google/protobuf/duration.pb.cc b/src/google/protobuf/duration.pb.cc
index b4d5eb5f..e8417a78 100644
--- a/src/google/protobuf/duration.pb.cc
+++ b/src/google/protobuf/duration.pb.cc
@@ -7,7 +7,6 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
@@ -19,6 +18,7 @@
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
+
namespace google {
namespace protobuf {
class DurationDefaultTypeInternal {
@@ -29,14 +29,9 @@ class DurationDefaultTypeInternal {
} // namespace protobuf
} // namespace google
namespace protobuf_google_2fprotobuf_2fduration_2eproto {
-void InitDefaultsDurationImpl() {
+static void InitDefaultsDuration() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_Duration_default_instance_;
new (ptr) ::google::protobuf::Duration();
@@ -45,9 +40,11 @@ void InitDefaultsDurationImpl() {
::google::protobuf::Duration::InitAsDefaultInstance();
}
-void InitDefaultsDuration() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDurationImpl);
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Duration =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDuration}, {}};
+
+void InitDefaults() {
+ ::google::protobuf::internal::InitSCC(&scc_info_Duration.base);
}
::google::protobuf::Metadata file_level_metadata[1];
@@ -69,17 +66,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Duration_default_instance_),
};
-void protobuf_AssignDescriptors() {
+static void protobuf_AssignDescriptors() {
AddDescriptors();
- ::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/duration.proto", schemas, file_default_instances, TableStruct::offsets, factory,
+ "google/protobuf/duration.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
-void protobuf_AssignDescriptorsOnce() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
+static 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;
@@ -88,7 +84,7 @@ void protobuf_RegisterTypes(const ::std::string&) {
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
-void AddDescriptorsImpl() {
+static void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\036google/protobuf/duration.proto\022\017google"
@@ -105,8 +101,8 @@ void AddDescriptorsImpl() {
}
void AddDescriptors() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
+ 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 {
@@ -129,24 +125,22 @@ const int Duration::kNanosFieldNumber;
Duration::Duration()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDuration();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDuration();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fduration_2eproto::scc_info_Duration.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Duration)
}
Duration::Duration(const Duration& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&seconds_, &from.seconds_,
static_cast<size_t>(reinterpret_cast<char*>(&nanos_) -
@@ -158,7 +152,6 @@ void Duration::SharedCtor() {
::memset(&seconds_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&nanos_) -
reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_));
- _cached_size_ = 0;
}
Duration::~Duration() {
@@ -174,12 +167,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Duration::descriptor() {
::protobuf_google_2fprotobuf_2fduration_2eproto::protobuf_AssignDescriptorsOnce();
@@ -187,7 +178,7 @@ const ::google::protobuf::Descriptor* Duration::descriptor() {
}
const Duration& Duration::default_instance() {
- ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDuration();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fduration_2eproto::scc_info_Duration.base);
return *internal_default_instance();
}
@@ -210,7 +201,7 @@ bool Duration::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Duration)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -334,9 +325,7 @@ size_t Duration::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -412,7 +401,6 @@ void Duration::InternalSwap(Duration* other) {
swap(seconds_, other->seconds_);
swap(nanos_, other->nanos_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Duration::GetMetadata() const {
@@ -426,7 +414,7 @@ void Duration::InternalSwap(Duration* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Duration* Arena::CreateMessage< ::google::protobuf::Duration >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Duration* Arena::CreateMaybeMessage< ::google::protobuf::Duration >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Duration >(arena);
}
} // namespace protobuf
diff --git a/src/google/protobuf/duration.pb.h b/src/google/protobuf/duration.pb.h
index 7fe0748d..751edbef 100644
--- a/src/google/protobuf/duration.pb.h
+++ b/src/google/protobuf/duration.pb.h
@@ -1,19 +1,19 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/duration.proto
-#ifndef PROTOBUF_google_2fprotobuf_2fduration_2eproto_INCLUDED
-#define PROTOBUF_google_2fprotobuf_2fduration_2eproto_INCLUDED
+#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto
+#define PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3005000
+#if GOOGLE_PROTOBUF_VERSION < 3006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3005001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -24,12 +24,14 @@
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
+#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fduration_2eproto LIBPROTOBUF_EXPORT
namespace protobuf_google_2fprotobuf_2fduration_2eproto {
// Internal implementation detail -- do not use these members.
@@ -42,11 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::uint32 offsets[];
};
void LIBPROTOBUF_EXPORT AddDescriptors();
-void LIBPROTOBUF_EXPORT InitDefaultsDurationImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsDuration();
-inline void LIBPROTOBUF_EXPORT InitDefaults() {
- InitDefaultsDuration();
-}
} // namespace protobuf_google_2fprotobuf_2fduration_2eproto
namespace google {
namespace protobuf {
@@ -57,7 +54,7 @@ LIBPROTOBUF_EXPORT extern DurationDefaultTypeInternal _Duration_default_instance
} // namespace google
namespace google {
namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Duration* Arena::CreateMessage< ::google::protobuf::Duration>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Duration* Arena::CreateMaybeMessage<::google::protobuf::Duration>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -91,10 +88,10 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -105,7 +102,7 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
return reinterpret_cast<const Duration*>(
&_Duration_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
0;
void UnsafeArenaSwap(Duration* other);
@@ -116,32 +113,33 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
// implements Message ----------------------------------------------
- inline Duration* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Duration>(NULL);
+ inline Duration* New() const final {
+ return CreateMaybeMessage<Duration>(NULL);
}
- Duration* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Duration>(arena);
+ Duration* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Duration>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Duration& from);
void MergeFrom(const Duration& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Duration* other);
protected:
explicit Duration(::google::protobuf::Arena* arena);
@@ -157,7 +155,7 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -184,9 +182,8 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
typedef void DestructorSkippable_;
::google::protobuf::int64 seconds_;
::google::protobuf::int32 nanos_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fduration_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDurationImpl();
};
// ===================================================================
@@ -238,4 +235,4 @@ inline void Duration::set_nanos(::google::protobuf::int32 value) {
// @@protoc_insertion_point(global_scope)
-#endif // PROTOBUF_google_2fprotobuf_2fduration_2eproto_INCLUDED
+#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto
diff --git a/src/google/protobuf/dynamic_message.cc b/src/google/protobuf/dynamic_message.cc
index 48d6aad8..8ad112ce 100644
--- a/src/google/protobuf/dynamic_message.cc
+++ b/src/google/protobuf/dynamic_message.cc
@@ -65,9 +65,6 @@
#include <algorithm>
#include <google/protobuf/stubs/hash.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/stubs/common.h>
@@ -232,13 +229,13 @@ class DynamicMessage : public Message {
// Warning: The order in which the following pointers are defined is
// important (the prototype must be deleted *before* the offsets).
- google::protobuf::scoped_array<uint32> offsets;
- google::protobuf::scoped_array<uint32> has_bits_indices;
- google::protobuf::scoped_ptr<const GeneratedMessageReflection> reflection;
- // Don't use a scoped_ptr to hold the prototype: the destructor for
+ std::unique_ptr<uint32[]> offsets;
+ std::unique_ptr<uint32[]> has_bits_indices;
+ std::unique_ptr<const GeneratedMessageReflection> reflection;
+ // Don't use a unique_ptr to hold the prototype: the destructor for
// DynamicMessage needs to know whether it is the prototype, and does so by
// looking back at this field. This would assume details about the
- // implementation of scoped_ptr.
+ // implementation of unique_ptr.
const DynamicMessage* prototype;
int weak_field_map_offset; // The offset for the weak_field_map;
@@ -261,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(::google::protobuf::Arena* arena) const override;
+ ::google::protobuf::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
diff --git a/src/google/protobuf/dynamic_message.h b/src/google/protobuf/dynamic_message.h
index e29b148d..940d5e15 100644
--- a/src/google/protobuf/dynamic_message.h
+++ b/src/google/protobuf/dynamic_message.h
@@ -40,9 +40,6 @@
#include <algorithm>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
#include <google/protobuf/message.h>
@@ -118,7 +115,7 @@ 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_;
@@ -130,7 +127,7 @@ class LIBPROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory {
// public header (for good reason), but dynamic_message.h is, and public
// headers may only #include other public headers.
struct PrototypeMap;
- google::protobuf::scoped_ptr<PrototypeMap> prototypes_;
+ std::unique_ptr<PrototypeMap> prototypes_;
mutable Mutex prototypes_mutex_;
friend class DynamicMessage;
diff --git a/src/google/protobuf/dynamic_message_unittest.cc b/src/google/protobuf/dynamic_message_unittest.cc
index 34f3641b..94446b08 100644
--- a/src/google/protobuf/dynamic_message_unittest.cc
+++ b/src/google/protobuf/dynamic_message_unittest.cc
@@ -41,16 +41,13 @@
// DynamicMessage.
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
-#include <google/protobuf/dynamic_message.h>
-#include <google/protobuf/descriptor.h>
-#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/test_util.h>
#include <google/protobuf/unittest.pb.h>
#include <google/protobuf/unittest_no_field_presence.pb.h>
+#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
diff --git a/src/google/protobuf/empty.pb.cc b/src/google/protobuf/empty.pb.cc
index ffff80b9..163a4f6a 100644
--- a/src/google/protobuf/empty.pb.cc
+++ b/src/google/protobuf/empty.pb.cc
@@ -7,7 +7,6 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
@@ -19,6 +18,7 @@
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
+
namespace google {
namespace protobuf {
class EmptyDefaultTypeInternal {
@@ -29,14 +29,9 @@ class EmptyDefaultTypeInternal {
} // namespace protobuf
} // namespace google
namespace protobuf_google_2fprotobuf_2fempty_2eproto {
-void InitDefaultsEmptyImpl() {
+static void InitDefaultsEmpty() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_Empty_default_instance_;
new (ptr) ::google::protobuf::Empty();
@@ -45,9 +40,11 @@ void InitDefaultsEmptyImpl() {
::google::protobuf::Empty::InitAsDefaultInstance();
}
-void InitDefaultsEmpty() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEmptyImpl);
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Empty =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEmpty}, {}};
+
+void InitDefaults() {
+ ::google::protobuf::internal::InitSCC(&scc_info_Empty.base);
}
::google::protobuf::Metadata file_level_metadata[1];
@@ -67,17 +64,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Empty_default_instance_),
};
-void protobuf_AssignDescriptors() {
+static void protobuf_AssignDescriptors() {
AddDescriptors();
- ::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/empty.proto", schemas, file_default_instances, TableStruct::offsets, factory,
+ "google/protobuf/empty.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
-void protobuf_AssignDescriptorsOnce() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
+static 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;
@@ -86,7 +82,7 @@ void protobuf_RegisterTypes(const ::std::string&) {
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
-void AddDescriptorsImpl() {
+static void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\033google/protobuf/empty.proto\022\017google.pr"
@@ -102,8 +98,8 @@ void AddDescriptorsImpl() {
}
void AddDescriptors() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
+ 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 {
@@ -124,30 +120,27 @@ void Empty::InitAsDefaultInstance() {
Empty::Empty()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmpty();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmpty();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fempty_2eproto::scc_info_Empty.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Empty)
}
Empty::Empty(const Empty& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Empty)
}
void Empty::SharedCtor() {
- _cached_size_ = 0;
}
Empty::~Empty() {
@@ -163,12 +156,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Empty::descriptor() {
::protobuf_google_2fprotobuf_2fempty_2eproto::protobuf_AssignDescriptorsOnce();
@@ -176,7 +167,7 @@ const ::google::protobuf::Descriptor* Empty::descriptor() {
}
const Empty& Empty::default_instance() {
- ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmpty();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fempty_2eproto::scc_info_Empty.base);
return *internal_default_instance();
}
@@ -196,7 +187,7 @@ bool Empty::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Empty)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
handle_unusual:
@@ -253,9 +244,7 @@ size_t Empty::ByteSizeLong() const {
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -323,7 +312,6 @@ void Empty::UnsafeArenaSwap(Empty* other) {
void Empty::InternalSwap(Empty* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Empty::GetMetadata() const {
@@ -337,7 +325,7 @@ void Empty::InternalSwap(Empty* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Empty* Arena::CreateMessage< ::google::protobuf::Empty >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Empty* Arena::CreateMaybeMessage< ::google::protobuf::Empty >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Empty >(arena);
}
} // namespace protobuf
diff --git a/src/google/protobuf/empty.pb.h b/src/google/protobuf/empty.pb.h
index 2fef9a43..c3da4fa8 100644
--- a/src/google/protobuf/empty.pb.h
+++ b/src/google/protobuf/empty.pb.h
@@ -1,19 +1,19 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/empty.proto
-#ifndef PROTOBUF_google_2fprotobuf_2fempty_2eproto_INCLUDED
-#define PROTOBUF_google_2fprotobuf_2fempty_2eproto_INCLUDED
+#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto
+#define PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3005000
+#if GOOGLE_PROTOBUF_VERSION < 3006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3005001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -24,12 +24,14 @@
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
+#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fempty_2eproto LIBPROTOBUF_EXPORT
namespace protobuf_google_2fprotobuf_2fempty_2eproto {
// Internal implementation detail -- do not use these members.
@@ -42,11 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::uint32 offsets[];
};
void LIBPROTOBUF_EXPORT AddDescriptors();
-void LIBPROTOBUF_EXPORT InitDefaultsEmptyImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsEmpty();
-inline void LIBPROTOBUF_EXPORT InitDefaults() {
- InitDefaultsEmpty();
-}
} // namespace protobuf_google_2fprotobuf_2fempty_2eproto
namespace google {
namespace protobuf {
@@ -57,7 +54,7 @@ LIBPROTOBUF_EXPORT extern EmptyDefaultTypeInternal _Empty_default_instance_;
} // namespace google
namespace google {
namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Empty* Arena::CreateMessage< ::google::protobuf::Empty>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Empty* Arena::CreateMaybeMessage<::google::protobuf::Empty>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -91,10 +88,10 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -105,7 +102,7 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
return reinterpret_cast<const Empty*>(
&_Empty_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
0;
void UnsafeArenaSwap(Empty* other);
@@ -116,32 +113,33 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
// implements Message ----------------------------------------------
- inline Empty* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Empty>(NULL);
+ inline Empty* New() const final {
+ return CreateMaybeMessage<Empty>(NULL);
}
- Empty* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Empty>(arena);
+ Empty* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Empty>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Empty& from);
void MergeFrom(const Empty& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Empty* other);
protected:
explicit Empty(::google::protobuf::Arena* arena);
@@ -157,7 +155,7 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -170,9 +168,8 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fempty_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmptyImpl();
};
// ===================================================================
@@ -196,4 +193,4 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
// @@protoc_insertion_point(global_scope)
-#endif // PROTOBUF_google_2fprotobuf_2fempty_2eproto_INCLUDED
+#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto
diff --git a/src/google/protobuf/extension_set.cc b/src/google/protobuf/extension_set.cc
index 8f104800..b587b38f 100644
--- a/src/google/protobuf/extension_set.cc
+++ b/src/google/protobuf/extension_set.cc
@@ -33,6 +33,7 @@
// Sanjay Ghemawat, Jeff Dean, and others.
#include <google/protobuf/stubs/hash.h>
+#include <tuple>
#include <utility>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/once.h>
@@ -179,20 +180,29 @@ void ExtensionSet::RegisterMessageExtension(const MessageLite* containing_type,
// Constructors and basic methods.
ExtensionSet::ExtensionSet(::google::protobuf::Arena* arena)
- : arena_(arena) {
- if (arena_ != NULL) {
- arena_->OwnDestructor(&extensions_);
- }
-}
-
-ExtensionSet::ExtensionSet() : arena_(NULL) {}
+ : arena_(arena),
+ flat_capacity_(0),
+ flat_size_(0),
+ map_{flat_capacity_ == 0 ? NULL
+ : ::google::protobuf::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_)} {}
ExtensionSet::~ExtensionSet() {
// Deletes all allocated extensions.
if (arena_ == NULL) {
- for (ExtensionMap::iterator iter = extensions_.begin();
- iter != extensions_.end(); ++iter) {
- iter->second.Free();
+ ForEach([](int /* number */, Extension& ext) { ext.Free(); });
+ if (GOOGLE_PREDICT_FALSE(is_large())) {
+ delete map_.large;
+ } else {
+ delete[] map_.flat;
}
}
}
@@ -203,45 +213,43 @@ ExtensionSet::~ExtensionSet() {
// vector<const FieldDescriptor*>* output) const
bool ExtensionSet::Has(int number) const {
- ExtensionMap::const_iterator iter = extensions_.find(number);
- if (iter == extensions_.end()) return false;
- GOOGLE_DCHECK(!iter->second.is_repeated);
- return !iter->second.is_cleared;
+ const Extension* ext = FindOrNull(number);
+ if (ext == NULL) return false;
+ GOOGLE_DCHECK(!ext->is_repeated);
+ return !ext->is_cleared;
}
int ExtensionSet::NumExtensions() const {
int result = 0;
- for (ExtensionMap::const_iterator iter = extensions_.begin();
- iter != extensions_.end(); ++iter) {
- if (!iter->second.is_cleared) {
+ ForEach([&result](int /* number */, const Extension& ext) {
+ if (!ext.is_cleared) {
++result;
}
- }
+ });
return result;
}
int ExtensionSet::ExtensionSize(int number) const {
- ExtensionMap::const_iterator iter = extensions_.find(number);
- if (iter == extensions_.end()) return 0;
- return iter->second.GetSize();
+ const Extension* ext = FindOrNull(number);
+ return ext == NULL ? 0 : ext->GetSize();
}
FieldType ExtensionSet::ExtensionType(int number) const {
- ExtensionMap::const_iterator iter = extensions_.find(number);
- if (iter == extensions_.end()) {
+ const Extension* ext = FindOrNull(number);
+ if (ext == NULL) {
GOOGLE_LOG(DFATAL) << "Don't lookup extension types if they aren't present (1). ";
return 0;
}
- if (iter->second.is_cleared) {
+ if (ext->is_cleared) {
GOOGLE_LOG(DFATAL) << "Don't lookup extension types if they aren't present (2). ";
}
- return iter->second.type;
+ return ext->type;
}
void ExtensionSet::ClearExtension(int number) {
- ExtensionMap::iterator iter = extensions_.find(number);
- if (iter == extensions_.end()) return;
- iter->second.Clear();
+ Extension* ext = FindOrNull(number);
+ if (ext == NULL) return;
+ ext->Clear();
}
// ===================================================================
@@ -267,12 +275,12 @@ enum Cardinality {
\
LOWERCASE ExtensionSet::Get##CAMELCASE(int number, \
LOWERCASE default_value) const { \
- ExtensionMap::const_iterator iter = extensions_.find(number); \
- if (iter == extensions_.end() || iter->second.is_cleared) { \
+ const Extension* extension = FindOrNull(number); \
+ if (extension == NULL || extension->is_cleared) { \
return default_value; \
} else { \
- GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, UPPERCASE); \
- return iter->second.LOWERCASE##_value; \
+ GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, UPPERCASE); \
+ return extension->LOWERCASE##_value; \
} \
} \
\
@@ -292,18 +300,18 @@ void ExtensionSet::Set##CAMELCASE(int number, FieldType type, \
} \
\
LOWERCASE ExtensionSet::GetRepeated##CAMELCASE(int number, int index) const { \
- ExtensionMap::const_iterator iter = extensions_.find(number); \
- GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; \
- GOOGLE_DCHECK_TYPE(iter->second, REPEATED, UPPERCASE); \
- return iter->second.repeated_##LOWERCASE##_value->Get(index); \
+ const Extension* extension = FindOrNull(number); \
+ GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; \
+ GOOGLE_DCHECK_TYPE(*extension, REPEATED, UPPERCASE); \
+ return extension->repeated_##LOWERCASE##_value->Get(index); \
} \
\
void ExtensionSet::SetRepeated##CAMELCASE( \
int number, int index, LOWERCASE value) { \
- ExtensionMap::iterator iter = extensions_.find(number); \
- GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; \
- GOOGLE_DCHECK_TYPE(iter->second, REPEATED, UPPERCASE); \
- iter->second.repeated_##LOWERCASE##_value->Set(index, value); \
+ Extension* extension = FindOrNull(number); \
+ GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; \
+ GOOGLE_DCHECK_TYPE(*extension, REPEATED, UPPERCASE); \
+ extension->repeated_##LOWERCASE##_value->Set(index, value); \
} \
\
void ExtensionSet::Add##CAMELCASE(int number, FieldType type, \
@@ -336,13 +344,13 @@ PRIMITIVE_ACCESSORS( BOOL, bool, Bool)
const void* ExtensionSet::GetRawRepeatedField(int number,
const void* default_value) const {
- ExtensionMap::const_iterator iter = extensions_.find(number);
- if (iter == extensions_.end()) {
+ const Extension* extension = FindOrNull(number);
+ if (extension == NULL) {
return default_value;
}
// We assume that all the RepeatedField<>* pointers have the same
// size and alignment within the anonymous union in Extension.
- return iter->second.repeated_int32_value;
+ return extension->repeated_int32_value;
}
void* ExtensionSet::MutableRawRepeatedField(int number, FieldType field_type,
@@ -393,7 +401,7 @@ void* ExtensionSet::MutableRawRepeatedField(int number, FieldType field_type,
break;
case WireFormatLite::CPPTYPE_STRING:
extension->repeated_string_value =
- Arena::CreateMessage<RepeatedPtrField< ::std::string> >(arena_);
+ Arena::CreateMessage<RepeatedPtrField<::std::string> >(arena_);
break;
case WireFormatLite::CPPTYPE_MESSAGE:
extension->repeated_message_value =
@@ -410,11 +418,11 @@ void* ExtensionSet::MutableRawRepeatedField(int number, FieldType field_type,
// Compatible version using old call signature. Does not create extensions when
// the don't already exist; instead, just GOOGLE_CHECK-fails.
void* ExtensionSet::MutableRawRepeatedField(int number) {
- ExtensionMap::iterator iter = extensions_.find(number);
- GOOGLE_CHECK(iter == extensions_.end()) << "Extension not found.";
+ Extension* extension = FindOrNull(number);
+ GOOGLE_CHECK(extension != NULL) << "Extension not found.";
// We assume that all the RepeatedField<>* pointers have the same
// size and alignment within the anonymous union in Extension.
- return iter->second.repeated_int32_value;
+ return extension->repeated_int32_value;
}
@@ -422,13 +430,13 @@ void* ExtensionSet::MutableRawRepeatedField(int number) {
// Enums
int ExtensionSet::GetEnum(int number, int default_value) const {
- ExtensionMap::const_iterator iter = extensions_.find(number);
- if (iter == extensions_.end() || iter->second.is_cleared) {
+ const Extension* extension = FindOrNull(number);
+ if (extension == NULL || extension->is_cleared) {
// Not present. Return the default value.
return default_value;
} else {
- GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, ENUM);
- return iter->second.enum_value;
+ GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, ENUM);
+ return extension->enum_value;
}
}
@@ -447,17 +455,17 @@ void ExtensionSet::SetEnum(int number, FieldType type, int value,
}
int ExtensionSet::GetRepeatedEnum(int number, int index) const {
- ExtensionMap::const_iterator iter = extensions_.find(number);
- GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty).";
- GOOGLE_DCHECK_TYPE(iter->second, REPEATED, ENUM);
- return iter->second.repeated_enum_value->Get(index);
+ const Extension* extension = FindOrNull(number);
+ GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty).";
+ GOOGLE_DCHECK_TYPE(*extension, REPEATED, ENUM);
+ return extension->repeated_enum_value->Get(index);
}
void ExtensionSet::SetRepeatedEnum(int number, int index, int value) {
- ExtensionMap::iterator iter = extensions_.find(number);
- GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty).";
- GOOGLE_DCHECK_TYPE(iter->second, REPEATED, ENUM);
- iter->second.repeated_enum_value->Set(index, value);
+ Extension* extension = FindOrNull(number);
+ GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty).";
+ GOOGLE_DCHECK_TYPE(*extension, REPEATED, ENUM);
+ extension->repeated_enum_value->Set(index, value);
}
void ExtensionSet::AddEnum(int number, FieldType type,
@@ -483,13 +491,13 @@ void ExtensionSet::AddEnum(int number, FieldType type,
const string& ExtensionSet::GetString(int number,
const string& default_value) const {
- ExtensionMap::const_iterator iter = extensions_.find(number);
- if (iter == extensions_.end() || iter->second.is_cleared) {
+ const Extension* extension = FindOrNull(number);
+ if (extension == NULL || extension->is_cleared) {
// Not present. Return the default value.
return default_value;
} else {
- GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, STRING);
- return *iter->second.string_value;
+ GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, STRING);
+ return *extension->string_value;
}
}
@@ -509,17 +517,17 @@ string* ExtensionSet::MutableString(int number, FieldType type,
}
const string& ExtensionSet::GetRepeatedString(int number, int index) const {
- ExtensionMap::const_iterator iter = extensions_.find(number);
- GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty).";
- GOOGLE_DCHECK_TYPE(iter->second, REPEATED, STRING);
- return iter->second.repeated_string_value->Get(index);
+ const Extension* extension = FindOrNull(number);
+ GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty).";
+ GOOGLE_DCHECK_TYPE(*extension, REPEATED, STRING);
+ return extension->repeated_string_value->Get(index);
}
string* ExtensionSet::MutableRepeatedString(int number, int index) {
- ExtensionMap::iterator iter = extensions_.find(number);
- GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty).";
- GOOGLE_DCHECK_TYPE(iter->second, REPEATED, STRING);
- return iter->second.repeated_string_value->Mutable(index);
+ Extension* extension = FindOrNull(number);
+ GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty).";
+ GOOGLE_DCHECK_TYPE(*extension, REPEATED, STRING);
+ return extension->repeated_string_value->Mutable(index);
}
string* ExtensionSet::AddString(int number, FieldType type,
@@ -543,16 +551,16 @@ string* ExtensionSet::AddString(int number, FieldType type,
const MessageLite& ExtensionSet::GetMessage(
int number, const MessageLite& default_value) const {
- ExtensionMap::const_iterator iter = extensions_.find(number);
- if (iter == extensions_.end()) {
+ const Extension* extension = FindOrNull(number);
+ if (extension == NULL) {
// Not present. Return the default value.
return default_value;
} else {
- GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE);
- if (iter->second.is_lazy) {
- return iter->second.lazymessage_value->GetMessage(default_value);
+ GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE);
+ if (extension->is_lazy) {
+ return extension->lazymessage_value->GetMessage(default_value);
} else {
- return *iter->second.message_value;
+ return *extension->message_value;
}
}
}
@@ -663,55 +671,53 @@ void ExtensionSet::UnsafeArenaSetAllocatedMessage(
extension->is_cleared = false;
}
-
MessageLite* ExtensionSet::ReleaseMessage(int number,
const MessageLite& prototype) {
- ExtensionMap::iterator iter = extensions_.find(number);
- if (iter == extensions_.end()) {
+ Extension* extension = FindOrNull(number);
+ if (extension == NULL) {
// Not present. Return NULL.
return NULL;
} else {
- GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE);
+ GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE);
MessageLite* ret = NULL;
- if (iter->second.is_lazy) {
- ret = iter->second.lazymessage_value->ReleaseMessage(prototype);
+ if (extension->is_lazy) {
+ ret = extension->lazymessage_value->ReleaseMessage(prototype);
if (arena_ == NULL) {
- delete iter->second.lazymessage_value;
+ delete extension->lazymessage_value;
}
} else {
if (arena_ == NULL) {
- ret = iter->second.message_value;
+ ret = extension->message_value;
} else {
// ReleaseMessage() always returns a heap-allocated message, and we are
// on an arena, so we need to make a copy of this message to return.
- ret = (iter->second.message_value)->New();
- ret->CheckTypeAndMergeFrom(*iter->second.message_value);
+ ret = extension->message_value->New();
+ ret->CheckTypeAndMergeFrom(*extension->message_value);
}
}
- extensions_.erase(number);
+ Erase(number);
return ret;
}
}
MessageLite* ExtensionSet::UnsafeArenaReleaseMessage(
int number, const MessageLite& prototype) {
- ExtensionMap::iterator iter = extensions_.find(number);
- if (iter == extensions_.end()) {
+ Extension* extension = FindOrNull(number);
+ if (extension == NULL) {
// Not present. Return NULL.
return NULL;
} else {
- GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE);
+ GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE);
MessageLite* ret = NULL;
- if (iter->second.is_lazy) {
- ret =
- iter->second.lazymessage_value->UnsafeArenaReleaseMessage(prototype);
+ if (extension->is_lazy) {
+ ret = extension->lazymessage_value->UnsafeArenaReleaseMessage(prototype);
if (arena_ == NULL) {
- delete iter->second.lazymessage_value;
+ delete extension->lazymessage_value;
}
} else {
- ret = iter->second.message_value;
+ ret = extension->message_value;
}
- extensions_.erase(number);
+ Erase(number);
return ret;
}
}
@@ -722,17 +728,17 @@ MessageLite* ExtensionSet::UnsafeArenaReleaseMessage(
const MessageLite& ExtensionSet::GetRepeatedMessage(
int number, int index) const {
- ExtensionMap::const_iterator iter = extensions_.find(number);
- GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty).";
- GOOGLE_DCHECK_TYPE(iter->second, REPEATED, MESSAGE);
- return iter->second.repeated_message_value->Get(index);
+ const Extension* extension = FindOrNull(number);
+ GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty).";
+ GOOGLE_DCHECK_TYPE(*extension, REPEATED, MESSAGE);
+ return extension->repeated_message_value->Get(index);
}
MessageLite* ExtensionSet::MutableRepeatedMessage(int number, int index) {
- ExtensionMap::iterator iter = extensions_.find(number);
- GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty).";
- GOOGLE_DCHECK_TYPE(iter->second, REPEATED, MESSAGE);
- return iter->second.repeated_message_value->Mutable(index);
+ Extension* extension = FindOrNull(number);
+ GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty).";
+ GOOGLE_DCHECK_TYPE(*extension, REPEATED, MESSAGE);
+ return extension->repeated_message_value->Mutable(index);
}
MessageLite* ExtensionSet::AddMessage(int number, FieldType type,
@@ -752,7 +758,7 @@ 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*>(
+ reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
extension->repeated_message_value)
->AddFromCleared<GenericTypeHandler<MessageLite> >();
if (result == NULL) {
@@ -770,10 +776,8 @@ MessageLite* ExtensionSet::AddMessage(int number, FieldType type,
#undef GOOGLE_DCHECK_TYPE
void ExtensionSet::RemoveLast(int number) {
- ExtensionMap::iterator iter = extensions_.find(number);
- GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty).";
-
- Extension* extension = &iter->second;
+ Extension* extension = FindOrNull(number);
+ GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty).";
GOOGLE_DCHECK(extension->is_repeated);
switch(cpp_type(extension->type)) {
@@ -811,20 +815,16 @@ void ExtensionSet::RemoveLast(int number) {
}
MessageLite* ExtensionSet::ReleaseLast(int number) {
- ExtensionMap::iterator iter = extensions_.find(number);
- GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty).";
-
- Extension* extension = &iter->second;
+ Extension* extension = FindOrNull(number);
+ GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty).";
GOOGLE_DCHECK(extension->is_repeated);
GOOGLE_DCHECK(cpp_type(extension->type) == WireFormatLite::CPPTYPE_MESSAGE);
return extension->repeated_message_value->ReleaseLast();
}
void ExtensionSet::SwapElements(int number, int index1, int index2) {
- ExtensionMap::iterator iter = extensions_.find(number);
- GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty).";
-
- Extension* extension = &iter->second;
+ Extension* extension = FindOrNull(number);
+ GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty).";
GOOGLE_DCHECK(extension->is_repeated);
switch(cpp_type(extension->type)) {
@@ -864,18 +864,45 @@ void ExtensionSet::SwapElements(int number, int index1, int index2) {
// ===================================================================
void ExtensionSet::Clear() {
- for (ExtensionMap::iterator iter = extensions_.begin();
- iter != extensions_.end(); ++iter) {
- iter->second.Clear();
+ ForEach([](int /* number */, Extension& ext) { ext.Clear(); });
+}
+
+namespace {
+// Computes the size of a std::set_union without constructing the union.
+template <typename ItX, typename ItY>
+size_t SizeOfUnion(ItX it_xs, ItX end_xs, ItY it_ys, ItY end_ys) {
+ size_t result = 0;
+ while (it_xs != end_xs && it_ys != end_ys) {
+ ++result;
+ if (it_xs->first < it_ys->first) {
+ ++it_xs;
+ } else if (it_xs->first == it_ys->first) {
+ ++it_xs;
+ ++it_ys;
+ } else {
+ ++it_ys;
+ }
}
+ result += std::distance(it_xs, end_xs);
+ result += std::distance(it_ys, end_ys);
+ return result;
}
+} // namespace
void ExtensionSet::MergeFrom(const ExtensionSet& other) {
- for (ExtensionMap::const_iterator iter = other.extensions_.begin();
- iter != other.extensions_.end(); ++iter) {
- const Extension& other_extension = iter->second;
- InternalExtensionMergeFrom(iter->first, other_extension);
+ if (GOOGLE_PREDICT_TRUE(!is_large())) {
+ if (GOOGLE_PREDICT_TRUE(!other.is_large())) {
+ GrowCapacity(SizeOfUnion(flat_begin(), flat_end(), other.flat_begin(),
+ other.flat_end()));
+ } else {
+ GrowCapacity(SizeOfUnion(flat_begin(), flat_end(),
+ other.map_.large->begin(),
+ other.map_.large->end()));
+ }
}
+ other.ForEach([this](int number, const Extension& ext) {
+ this->InternalExtensionMergeFrom(number, ext);
+ });
}
void ExtensionSet::InternalExtensionMergeFrom(
@@ -929,7 +956,7 @@ 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<::google::protobuf::internal::RepeatedPtrFieldBase*>(
extension->repeated_message_value)
->AddFromCleared<GenericTypeHandler<MessageLite> >();
if (target == NULL) {
@@ -1020,7 +1047,10 @@ void ExtensionSet::InternalExtensionMergeFrom(
void ExtensionSet::Swap(ExtensionSet* x) {
if (GetArenaNoVirtual() == x->GetArenaNoVirtual()) {
- extensions_.swap(x->extensions_);
+ using std::swap;
+ swap(flat_capacity_, x->flat_capacity_);
+ swap(flat_size_, x->flat_size_);
+ swap(map_, x->map_);
} else {
// TODO(cfallin, rohananil): We maybe able to optimize a case where we are
// swapping from heap to arena-allocated extension set, by just Own()'ing
@@ -1037,19 +1067,17 @@ void ExtensionSet::Swap(ExtensionSet* x) {
void ExtensionSet::SwapExtension(ExtensionSet* other,
int number) {
if (this == other) return;
- ExtensionMap::iterator this_iter = extensions_.find(number);
- ExtensionMap::iterator other_iter = other->extensions_.find(number);
+ Extension* this_ext = FindOrNull(number);
+ Extension* other_ext = other->FindOrNull(number);
- if (this_iter == extensions_.end() &&
- other_iter == other->extensions_.end()) {
+ if (this_ext == NULL && other_ext == NULL) {
return;
}
- if (this_iter != extensions_.end() &&
- other_iter != other->extensions_.end()) {
+ if (this_ext != NULL && other_ext != NULL) {
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
using std::swap;
- swap(this_iter->second, other_iter->second);
+ swap(*this_ext, *other_ext);
} else {
// TODO(cfallin, rohananil): We could further optimize these cases,
// especially avoid creation of ExtensionSet, and move MergeFrom logic
@@ -1057,33 +1085,33 @@ void ExtensionSet::SwapExtension(ExtensionSet* other,
// We do it this way to reuse the copy-across-arenas logic already
// implemented in ExtensionSet's MergeFrom.
ExtensionSet temp;
- temp.InternalExtensionMergeFrom(number, other_iter->second);
- ExtensionMap::iterator temp_iter = temp.extensions_.find(number);
- other_iter->second.Clear();
- other->InternalExtensionMergeFrom(number, this_iter->second);
- this_iter->second.Clear();
- InternalExtensionMergeFrom(number, temp_iter->second);
+ temp.InternalExtensionMergeFrom(number, *other_ext);
+ Extension* temp_ext = temp.FindOrNull(number);
+ other_ext->Clear();
+ other->InternalExtensionMergeFrom(number, *this_ext);
+ this_ext->Clear();
+ InternalExtensionMergeFrom(number, *temp_ext);
}
return;
}
- if (this_iter == extensions_.end()) {
+ if (this_ext == NULL) {
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
- extensions_.insert(std::make_pair(number, other_iter->second));
+ *Insert(number).first = *other_ext;
} else {
- InternalExtensionMergeFrom(number, other_iter->second);
+ InternalExtensionMergeFrom(number, *other_ext);
}
- other->extensions_.erase(number);
+ other->Erase(number);
return;
}
- if (other_iter == other->extensions_.end()) {
+ if (other_ext == NULL) {
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
- other->extensions_.insert(std::make_pair(number, this_iter->second));
+ *other->Insert(number).first = *this_ext;
} else {
- other->InternalExtensionMergeFrom(number, this_iter->second);
+ other->InternalExtensionMergeFrom(number, *this_ext);
}
- extensions_.erase(number);
+ Erase(number);
return;
}
}
@@ -1091,28 +1119,15 @@ void ExtensionSet::SwapExtension(ExtensionSet* other,
bool ExtensionSet::IsInitialized() const {
// Extensions are never required. However, we need to check that all
// embedded messages are initialized.
- for (ExtensionMap::const_iterator iter = extensions_.begin();
- iter != extensions_.end(); ++iter) {
- const Extension& extension = iter->second;
- if (cpp_type(extension.type) == WireFormatLite::CPPTYPE_MESSAGE) {
- if (extension.is_repeated) {
- for (int i = 0; i < extension.repeated_message_value->size(); i++) {
- if (!extension.repeated_message_value->Get(i).IsInitialized()) {
- return false;
- }
- }
- } else {
- if (!extension.is_cleared) {
- if (extension.is_lazy) {
- if (!extension.lazymessage_value->IsInitialized()) return false;
- } else {
- if (!extension.message_value->IsInitialized()) return false;
- }
- }
- }
+ if (GOOGLE_PREDICT_FALSE(is_large())) {
+ for (const auto& kv : *map_.large) {
+ if (!kv.second.IsInitialized()) return false;
}
+ return true;
+ }
+ for (const KeyValue* it = flat_begin(); it != flat_end(); ++it) {
+ if (!it->second.IsInitialized()) return false;
}
-
return true;
}
@@ -1351,22 +1366,27 @@ bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input,
void ExtensionSet::SerializeWithCachedSizes(
int start_field_number, int end_field_number,
io::CodedOutputStream* output) const {
- ExtensionMap::const_iterator iter;
- for (iter = extensions_.lower_bound(start_field_number);
- iter != extensions_.end() && iter->first < end_field_number;
- ++iter) {
- iter->second.SerializeFieldWithCachedSizes(iter->first, output);
+ if (GOOGLE_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) {
+ it->second.SerializeFieldWithCachedSizes(it->first, output);
+ }
+ return;
+ }
+ const KeyValue* end = flat_end();
+ for (const KeyValue* it = std::lower_bound(
+ flat_begin(), end, start_field_number, KeyValue::FirstComparator());
+ it != end && it->first < end_field_number; ++it) {
+ it->second.SerializeFieldWithCachedSizes(it->first, output);
}
}
size_t ExtensionSet::ByteSize() const {
size_t total_size = 0;
-
- for (ExtensionMap::const_iterator iter = extensions_.begin();
- iter != extensions_.end(); ++iter) {
- total_size += iter->second.ByteSize(iter->first);
- }
-
+ ForEach([&total_size](int number, const Extension& ext) {
+ total_size += ext.ByteSize(number);
+ });
return total_size;
}
@@ -1376,11 +1396,10 @@ size_t ExtensionSet::ByteSize() const {
bool ExtensionSet::MaybeNewExtension(int number,
const FieldDescriptor* descriptor,
Extension** result) {
- std::pair<ExtensionMap::iterator, bool> insert_result =
- extensions_.insert(std::make_pair(number, Extension()));
- *result = &insert_result.first->second;
+ bool extension_is_new = false;
+ std::tie(*result, extension_is_new) = Insert(number);
(*result)->descriptor = descriptor;
- return insert_result.second;
+ return extension_is_new;
}
// ===================================================================
@@ -1752,9 +1771,143 @@ void ExtensionSet::Extension::Free() {
// Defined in extension_set_heavy.cc.
// int ExtensionSet::Extension::SpaceUsedExcludingSelf() const
+bool ExtensionSet::Extension::IsInitialized() const {
+ if (cpp_type(type) == WireFormatLite::CPPTYPE_MESSAGE) {
+ if (is_repeated) {
+ for (int i = 0; i < repeated_message_value->size(); i++) {
+ if (!repeated_message_value->Get(i).IsInitialized()) {
+ return false;
+ }
+ }
+ } else {
+ if (!is_cleared) {
+ if (is_lazy) {
+ if (!lazymessage_value->IsInitialized()) return false;
+ } else {
+ if (!message_value->IsInitialized()) return false;
+ }
+ }
+ }
+ }
+ return true;
+}
+
// Dummy key method to avoid weak vtable.
void ExtensionSet::LazyMessageExtension::UnusedKeyMethod() {}
+const ExtensionSet::Extension* ExtensionSet::FindOrNull(int key) const {
+ if (GOOGLE_PREDICT_FALSE(is_large())) {
+ return FindOrNullInLargeMap(key);
+ }
+ const KeyValue* end = flat_end();
+ const KeyValue* it =
+ std::lower_bound(flat_begin(), end, key, KeyValue::FirstComparator());
+ if (it != end && it->first == key) {
+ return &it->second;
+ }
+ return NULL;
+}
+
+const ExtensionSet::Extension* ExtensionSet::FindOrNullInLargeMap(
+ int key) const {
+ assert(is_large());
+ LargeMap::const_iterator it = map_.large->find(key);
+ if (it != map_.large->end()) {
+ return &it->second;
+ }
+ return NULL;
+}
+
+ExtensionSet::Extension* ExtensionSet::FindOrNull(int key) {
+ if (GOOGLE_PREDICT_FALSE(is_large())) {
+ return FindOrNullInLargeMap(key);
+ }
+ KeyValue* end = flat_end();
+ KeyValue* it =
+ std::lower_bound(flat_begin(), end, key, KeyValue::FirstComparator());
+ if (it != end && it->first == key) {
+ return &it->second;
+ }
+ return NULL;
+}
+
+ExtensionSet::Extension* ExtensionSet::FindOrNullInLargeMap(int key) {
+ assert(is_large());
+ LargeMap::iterator it = map_.large->find(key);
+ if (it != map_.large->end()) {
+ return &it->second;
+ }
+ return NULL;
+}
+
+std::pair<ExtensionSet::Extension*, bool> ExtensionSet::Insert(int key) {
+ if (GOOGLE_PREDICT_FALSE(is_large())) {
+ auto maybe = map_.large->insert({key, Extension()});
+ return {&maybe.first->second, maybe.second};
+ }
+ KeyValue* end = flat_end();
+ KeyValue* it =
+ std::lower_bound(flat_begin(), end, key, KeyValue::FirstComparator());
+ if (it != end && it->first == key) {
+ return {&it->second, false};
+ }
+ if (flat_size_ < flat_capacity_) {
+ std::copy_backward(it, end, end + 1);
+ ++flat_size_;
+ it->first = key;
+ it->second = Extension();
+ return {&it->second, true};
+ }
+ GrowCapacity(flat_size_ + 1);
+ return Insert(key);
+}
+
+void ExtensionSet::GrowCapacity(size_t minimum_new_capacity) {
+ if (GOOGLE_PREDICT_FALSE(is_large())) {
+ return; // LargeMap does not have a "reserve" method.
+ }
+ if (flat_capacity_ >= minimum_new_capacity) {
+ return;
+ }
+
+ do {
+ flat_capacity_ = flat_capacity_ == 0 ? 1 : flat_capacity_ * 4;
+ } while (flat_capacity_ < minimum_new_capacity);
+
+ const KeyValue* begin = flat_begin();
+ const KeyValue* end = flat_end();
+ if (flat_capacity_ > kMaximumFlatCapacity) {
+ // Switch to LargeMap
+ map_.large = ::google::protobuf::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_);
+ std::copy(begin, end, map_.flat);
+ }
+ if (arena_ == NULL) delete[] begin;
+}
+
+// static
+constexpr uint16 ExtensionSet::kMaximumFlatCapacity;
+
+void ExtensionSet::Erase(int key) {
+ if (GOOGLE_PREDICT_FALSE(is_large())) {
+ map_.large->erase(key);
+ return;
+ }
+ KeyValue* end = flat_end();
+ KeyValue* it =
+ std::lower_bound(flat_begin(), end, key, KeyValue::FirstComparator());
+ if (it != end && it->first == key) {
+ std::copy(it + 1, end, it);
+ --flat_size_;
+ }
+}
+
// ==================================================================
// Default repeated field instances for iterator-compatible accessors
diff --git a/src/google/protobuf/extension_set.h b/src/google/protobuf/extension_set.h
index b0f3b8dd..e94e0b9c 100644
--- a/src/google/protobuf/extension_set.h
+++ b/src/google/protobuf/extension_set.h
@@ -38,16 +38,16 @@
#ifndef GOOGLE_PROTOBUF_EXTENSION_SET_H__
#define GOOGLE_PROTOBUF_EXTENSION_SET_H__
-#include <vector>
+#include <algorithm>
+#include <cassert>
#include <map>
-#include <utility>
#include <string>
-
+#include <utility>
+#include <vector>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/once.h>
-
#include <google/protobuf/repeated_field.h>
namespace google {
@@ -134,7 +134,7 @@ class LIBPROTOBUF_EXPORT GeneratedExtensionFinder : public ExtensionFinder {
virtual ~GeneratedExtensionFinder() {}
// Returns true and fills in *output if found, otherwise returns false.
- virtual bool Find(int number, ExtensionInfo* output);
+ virtual bool Find(int number, ExtensionInfo* output) override;
private:
const MessageLite* containing_type_;
@@ -464,7 +464,12 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
const MessageLite& prototype) = 0;
virtual bool IsInitialized() const = 0;
- virtual int ByteSize() const = 0;
+
+ PROTOBUF_RUNTIME_DEPRECATED("Please use ByteSizeLong() instead")
+ virtual int ByteSize() const {
+ return internal::ToIntSize(ByteSizeLong());
+ }
+ virtual size_t ByteSizeLong() const = 0;
virtual size_t SpaceUsedLong() const = 0;
virtual void MergeFrom(const LazyMessageExtension& other) = 0;
@@ -567,9 +572,89 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
int GetSize() const;
void Free();
size_t SpaceUsedExcludingSelfLong() const;
+ bool IsInitialized() const;
};
- typedef std::map<int, Extension> ExtensionMap;
+ // The Extension struct is small enough to be passed by value, so we use it
+ // directly as the value type in mappings rather than use pointers. We use
+ // sorted maps rather than hash-maps because we expect most ExtensionSets will
+ // only contain a small number of extension. Also, we want AppendToList and
+ // deterministic serialization to order fields by field number.
+
+ struct KeyValue {
+ int first;
+ Extension second;
+
+ struct FirstComparator {
+ bool operator()(const KeyValue& lhs, const KeyValue& rhs) const {
+ return lhs.first < rhs.first;
+ }
+ bool operator()(const KeyValue& lhs, int key) const {
+ return lhs.first < key;
+ }
+ bool operator()(int key, const KeyValue& rhs) const {
+ return key < rhs.first;
+ }
+ };
+ };
+
+ typedef std::map<int, Extension> LargeMap;
+
+ // Wrapper API that switches between flat-map and LargeMap.
+
+ // Finds a key (if present) in the ExtensionSet.
+ const Extension* FindOrNull(int key) const;
+ Extension* FindOrNull(int key);
+
+ // Helper-functions that only inspect the LargeMap.
+ const Extension* FindOrNullInLargeMap(int key) const;
+ Extension* FindOrNullInLargeMap(int key);
+
+ // Inserts a new (key, Extension) into the ExtensionSet (and returns true), or
+ // finds the already-existing Extension for that key (returns false).
+ // The Extension* will point to the new-or-found Extension.
+ std::pair<Extension*, bool> Insert(int key);
+
+ // Grows the flat_capacity_.
+ // If flat_capacity_ > kMaximumFlatCapacity, converts to LargeMap.
+ void GrowCapacity(size_t minimum_new_capacity);
+ static constexpr uint16 kMaximumFlatCapacity = 256;
+ bool is_large() const { return flat_capacity_ > kMaximumFlatCapacity; }
+
+ // Removes a key from the ExtensionSet.
+ void Erase(int key);
+
+ size_t Size() const {
+ return GOOGLE_PREDICT_FALSE(is_large()) ? map_.large->size() : flat_size_;
+ }
+
+ // Similar to std::for_each.
+ // Each Iterator is decomposed into ->first and ->second fields, so
+ // that the KeyValueFunctor can be agnostic vis-a-vis KeyValue-vs-std::pair.
+ template <typename Iterator, typename KeyValueFunctor>
+ static KeyValueFunctor ForEach(Iterator begin, Iterator end,
+ KeyValueFunctor func) {
+ for (Iterator it = begin; it != end; ++it) func(it->first, it->second);
+ return std::move(func);
+ }
+
+ // Applies a functor to the <int, Extension&> pairs in sorted order.
+ template <typename KeyValueFunctor>
+ KeyValueFunctor ForEach(KeyValueFunctor func) {
+ if (GOOGLE_PREDICT_FALSE(is_large())) {
+ return ForEach(map_.large->begin(), map_.large->end(), std::move(func));
+ }
+ return ForEach(flat_begin(), flat_end(), std::move(func));
+ }
+
+ // 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())) {
+ return ForEach(map_.large->begin(), map_.large->end(), std::move(func));
+ }
+ return ForEach(flat_begin(), flat_end(), std::move(func));
+ }
// Merges existing Extension from other_extension
void InternalExtensionMergeFrom(int number, const Extension& other_extension);
@@ -633,14 +718,38 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
static inline size_t RepeatedMessage_SpaceUsedExcludingSelfLong(
RepeatedPtrFieldBase* field);
- // The Extension struct is small enough to be passed by value, so we use it
- // directly as the value type in the map rather than use pointers. We use
- // a map rather than hash_map here because we expect most ExtensionSets will
- // only contain a small number of extensions whereas hash_map is optimized
- // for 100 elements or more. Also, we want AppendToList() to order fields
- // by field number.
- ExtensionMap extensions_;
+ KeyValue* flat_begin() {
+ assert(!is_large());
+ return map_.flat;
+ }
+ const KeyValue* flat_begin() const {
+ assert(!is_large());
+ return map_.flat;
+ }
+ KeyValue* flat_end() {
+ assert(!is_large());
+ return map_.flat + flat_size_;
+ }
+ const KeyValue* flat_end() const {
+ assert(!is_large());
+ return map_.flat + flat_size_;
+ }
+
::google::protobuf::Arena* arena_;
+
+ // Manual memory-management:
+ // map_.flat is an allocated array of flat_capacity_ elements.
+ // [map_.flat, map_.flat + flat_size_) is the currently-in-use prefix.
+ uint16 flat_capacity_;
+ uint16 flat_size_;
+ union AllocatedData {
+ KeyValue* flat;
+
+ // If flat_capacity_ > kMaximumFlatCapacity, switch to LargeMap,
+ // which guarantees O(n lg n) CPU but larger constant factors.
+ LargeMap* large;
+ } map_;
+
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionSet);
};
@@ -1127,7 +1236,7 @@ LIBPROTOBUF_EXPORT extern ProtobufOnceType repeated_message_generic_type_traits_
// message-type repeated field extensions.
class LIBPROTOBUF_EXPORT RepeatedMessageGenericTypeTraits {
public:
- typedef RepeatedPtrField< ::google::protobuf::MessageLite*> RepeatedFieldType;
+ typedef RepeatedPtrField<::google::protobuf::MessageLite*> RepeatedFieldType;
private:
template<typename Type> friend class RepeatedMessageTypeTraits;
static void InitializeDefaultRepeatedFields();
diff --git a/src/google/protobuf/extension_set_heavy.cc b/src/google/protobuf/extension_set_heavy.cc
index 432c0fd7..372aea57 100644
--- a/src/google/protobuf/extension_set_heavy.cc
+++ b/src/google/protobuf/extension_set_heavy.cc
@@ -35,9 +35,10 @@
// Contains methods defined in extension_set.h which cannot be part of the
// lite library because they use descriptors or reflection.
+#include <google/protobuf/stubs/casts.h>
+#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
-#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/message.h>
@@ -84,9 +85,9 @@ class DescriptorPoolExtensionFinder : public ExtensionFinder {
MessageFactory* factory,
const Descriptor* containing_type)
: pool_(pool), factory_(factory), containing_type_(containing_type) {}
- virtual ~DescriptorPoolExtensionFinder() {}
+ virtual ~DescriptorPoolExtensionFinder() override {}
- virtual bool Find(int number, ExtensionInfo* output);
+ virtual bool Find(int number, ExtensionInfo* output) override;
private:
const DescriptorPool* pool_;
@@ -95,16 +96,14 @@ class DescriptorPoolExtensionFinder : public ExtensionFinder {
};
void ExtensionSet::AppendToList(
- const Descriptor* containing_type,
- const DescriptorPool* pool,
+ const Descriptor* containing_type, const DescriptorPool* pool,
std::vector<const FieldDescriptor*>* output) const {
- for (ExtensionMap::const_iterator iter = extensions_.begin();
- iter != extensions_.end(); ++iter) {
+ ForEach([containing_type, pool, &output](int number, const Extension& ext) {
bool has = false;
- if (iter->second.is_repeated) {
- has = iter->second.GetSize() > 0;
+ if (ext.is_repeated) {
+ has = ext.GetSize() > 0;
} else {
- has = !iter->second.is_cleared;
+ has = !ext.is_cleared;
}
if (has) {
@@ -113,14 +112,13 @@ void ExtensionSet::AppendToList(
// initialized, so they might not even be constructed until
// AppendToList() is called.
- if (iter->second.descriptor == NULL) {
- output->push_back(pool->FindExtensionByNumber(
- containing_type, iter->first));
+ if (ext.descriptor == NULL) {
+ output->push_back(pool->FindExtensionByNumber(containing_type, number));
} else {
- output->push_back(iter->second.descriptor);
+ output->push_back(ext.descriptor);
}
}
- }
+ });
}
inline FieldDescriptor::Type real_type(FieldType type) {
@@ -147,17 +145,17 @@ inline WireFormatLite::FieldType field_type(FieldType type) {
const MessageLite& ExtensionSet::GetMessage(int number,
const Descriptor* message_type,
MessageFactory* factory) const {
- ExtensionMap::const_iterator iter = extensions_.find(number);
- if (iter == extensions_.end() || iter->second.is_cleared) {
+ const Extension* extension = FindOrNull(number);
+ if (extension == NULL || extension->is_cleared) {
// Not present. Return the default value.
return *factory->GetPrototype(message_type);
} else {
- GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE);
- if (iter->second.is_lazy) {
- return iter->second.lazymessage_value->GetMessage(
+ GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE);
+ if (extension->is_lazy) {
+ return extension->lazymessage_value->GetMessage(
*factory->GetPrototype(message_type));
} else {
- return *iter->second.message_value;
+ return *extension->message_value;
}
}
}
@@ -190,51 +188,51 @@ MessageLite* ExtensionSet::MutableMessage(const FieldDescriptor* descriptor,
MessageLite* ExtensionSet::ReleaseMessage(const FieldDescriptor* descriptor,
MessageFactory* factory) {
- ExtensionMap::iterator iter = extensions_.find(descriptor->number());
- if (iter == extensions_.end()) {
+ Extension* extension = FindOrNull(descriptor->number());
+ if (extension == NULL) {
// Not present. Return NULL.
return NULL;
} else {
- GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE);
+ GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE);
MessageLite* ret = NULL;
- if (iter->second.is_lazy) {
- ret = iter->second.lazymessage_value->ReleaseMessage(
+ if (extension->is_lazy) {
+ ret = extension->lazymessage_value->ReleaseMessage(
*factory->GetPrototype(descriptor->message_type()));
if (arena_ == NULL) {
- delete iter->second.lazymessage_value;
+ delete extension->lazymessage_value;
}
} else {
if (arena_ != NULL) {
- ret = (iter->second.message_value)->New();
- ret->CheckTypeAndMergeFrom(*(iter->second.message_value));
+ ret = extension->message_value->New();
+ ret->CheckTypeAndMergeFrom(*extension->message_value);
} else {
- ret = iter->second.message_value;
+ ret = extension->message_value;
}
}
- extensions_.erase(descriptor->number());
+ Erase(descriptor->number());
return ret;
}
}
MessageLite* ExtensionSet::UnsafeArenaReleaseMessage(
const FieldDescriptor* descriptor, MessageFactory* factory) {
- ExtensionMap::iterator iter = extensions_.find(descriptor->number());
- if (iter == extensions_.end()) {
+ Extension* extension = FindOrNull(descriptor->number());
+ if (extension == NULL) {
// Not present. Return NULL.
return NULL;
} else {
- GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE);
+ GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE);
MessageLite* ret = NULL;
- if (iter->second.is_lazy) {
- ret = iter->second.lazymessage_value->UnsafeArenaReleaseMessage(
+ if (extension->is_lazy) {
+ ret = extension->lazymessage_value->UnsafeArenaReleaseMessage(
*factory->GetPrototype(descriptor->message_type()));
if (arena_ == NULL) {
- delete iter->second.lazymessage_value;
+ delete extension->lazymessage_value;
}
} else {
- ret = iter->second.message_value;
+ ret = extension->message_value;
}
- extensions_.erase(descriptor->number());
+ Erase(descriptor->number());
return ret;
}
}
@@ -260,7 +258,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<::google::protobuf::internal::RepeatedPtrFieldBase*>(
extension->repeated_message_value)
->AddFromCleared<GenericTypeHandler<MessageLite> >();
if (result == NULL) {
@@ -349,14 +347,10 @@ int ExtensionSet::SpaceUsedExcludingSelf() const {
}
size_t ExtensionSet::SpaceUsedExcludingSelfLong() const {
- size_t total_size =
- extensions_.size() * sizeof(ExtensionMap::value_type);
- for (ExtensionMap::const_iterator iter = extensions_.begin(),
- end = extensions_.end();
- iter != end;
- ++iter) {
- total_size += iter->second.SpaceUsedExcludingSelfLong();
- }
+ size_t total_size = Size() * sizeof(KeyValue);
+ ForEach([&total_size](int /* number */, const Extension& ext) {
+ total_size += ext.SpaceUsedExcludingSelfLong();
+ });
return total_size;
}
@@ -394,7 +388,7 @@ size_t ExtensionSet::Extension::SpaceUsedExcludingSelfLong() const {
total_size +=
sizeof(*repeated_message_value) +
RepeatedMessage_SpaceUsedExcludingSelfLong(
- reinterpret_cast< ::google::protobuf::internal::RepeatedPtrFieldBase*>(
+ reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
repeated_message_value));
break;
}
@@ -438,25 +432,33 @@ uint8* ExtensionSet::SerializeMessageSetWithCachedSizesToArray(
}
uint8* ExtensionSet::InternalSerializeWithCachedSizesToArray(
- int start_field_number, int end_field_number,
- bool deterministic, uint8* target) const {
- ExtensionMap::const_iterator iter;
- for (iter = extensions_.lower_bound(start_field_number);
- iter != extensions_.end() && iter->first < end_field_number;
- ++iter) {
- target = iter->second.InternalSerializeFieldWithCachedSizesToArray(
- iter->first, deterministic, target);
+ int start_field_number, int end_field_number, bool deterministic,
+ uint8* target) const {
+ if (GOOGLE_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) {
+ target = it->second.InternalSerializeFieldWithCachedSizesToArray(
+ it->first, deterministic, target);
+ }
+ return target;
+ }
+ const KeyValue* end = flat_end();
+ for (const KeyValue* it = std::lower_bound(
+ flat_begin(), end, start_field_number, KeyValue::FirstComparator());
+ it != end && it->first < end_field_number; ++it) {
+ target = it->second.InternalSerializeFieldWithCachedSizesToArray(
+ it->first, deterministic, target);
}
return target;
}
uint8* ExtensionSet::InternalSerializeMessageSetWithCachedSizesToArray(
bool deterministic, uint8* target) const {
- ExtensionMap::const_iterator iter;
- for (iter = extensions_.begin(); iter != extensions_.end(); ++iter) {
- target = iter->second.InternalSerializeMessageSetItemWithCachedSizesToArray(
- iter->first, deterministic, target);
- }
+ ForEach([deterministic, &target](int number, const Extension& ext) {
+ target = ext.InternalSerializeMessageSetItemWithCachedSizesToArray(
+ number, deterministic, target);
+ });
return target;
}
@@ -783,9 +785,9 @@ size_t ExtensionSet::Extension::MessageSetItemByteSize(int number) const {
// message
size_t message_size = 0;
if (is_lazy) {
- message_size = lazymessage_value->ByteSize();
+ message_size = lazymessage_value->ByteSizeLong();
} else {
- message_size = message_value->ByteSize();
+ message_size = message_value->ByteSizeLong();
}
our_size += io::CodedOutputStream::VarintSize32(message_size);
@@ -796,20 +798,16 @@ size_t ExtensionSet::Extension::MessageSetItemByteSize(int number) const {
void ExtensionSet::SerializeMessageSetWithCachedSizes(
io::CodedOutputStream* output) const {
- for (ExtensionMap::const_iterator iter = extensions_.begin();
- iter != extensions_.end(); ++iter) {
- iter->second.SerializeMessageSetItemWithCachedSizes(iter->first, output);
- }
+ ForEach([output](int number, const Extension& ext) {
+ ext.SerializeMessageSetItemWithCachedSizes(number, output);
+ });
}
size_t ExtensionSet::MessageSetByteSize() const {
size_t total_size = 0;
-
- for (ExtensionMap::const_iterator iter = extensions_.begin();
- iter != extensions_.end(); ++iter) {
- total_size += iter->second.MessageSetItemByteSize(iter->first);
- }
-
+ ForEach([&total_size](int number, const Extension& ext) {
+ total_size += ext.MessageSetItemByteSize(number);
+ });
return total_size;
}
diff --git a/src/google/protobuf/extension_set_unittest.cc b/src/google/protobuf/extension_set_unittest.cc
index b8b6e428..bc65d295 100644
--- a/src/google/protobuf/extension_set_unittest.cc
+++ b/src/google/protobuf/extension_set_unittest.cc
@@ -32,19 +32,20 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
+#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/strutil.h>
-#include <google/protobuf/extension_set.h>
+#include <google/protobuf/test_util.h>
#include <google/protobuf/unittest.pb.h>
#include <google/protobuf/unittest_mset.pb.h>
-#include <google/protobuf/test_util.h>
+#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/dynamic_message.h>
+#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format.h>
-#include <google/protobuf/io/coded_stream.h>
-#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -285,7 +286,7 @@ TEST(ExtensionSetTest, CopyFrom) {
TestUtil::ExpectAllExtensionsSet(message2);
}
-TEST(ExtensioSetTest, CopyFromPacked) {
+TEST(ExtensionSetTest, CopyFromPacked) {
unittest::TestPackedExtensions message1, message2;
TestUtil::SetPackedExtensions(&message1);
@@ -444,7 +445,7 @@ TEST(ExtensionSetTest, ArenaSetAllocatedMessageAndRelease) {
TEST(ExtensionSetTest, SwapExtensionBothFullWithArena) {
::google::protobuf::Arena arena1;
- google::protobuf::scoped_ptr<google::protobuf::Arena> arena2(new ::google::protobuf::Arena());
+ std::unique_ptr<google::protobuf::Arena> arena2(new ::google::protobuf::Arena());
unittest::TestAllExtensions* message1 =
Arena::CreateMessage<unittest::TestAllExtensions>(&arena1);
@@ -601,6 +602,26 @@ TEST(ExtensionSetTest, PackedSerializationToStream) {
TestUtil::ExpectPackedFieldsSet(destination);
}
+TEST(ExtensionSetTest, NestedExtensionGroup) {
+ // Serialize as TestGroup and parse as TestGroupExtension.
+ unittest::TestGroup source;
+ unittest::TestGroupExtension destination;
+ string data;
+
+ source.mutable_optionalgroup()->set_a(117);
+ source.set_optional_foreign_enum(unittest::FOREIGN_BAZ);
+ source.SerializeToString(&data);
+ EXPECT_TRUE(destination.ParseFromString(data));
+ EXPECT_TRUE(destination.GetExtension(
+ unittest::TestNestedExtension::optionalgroup_extension).has_a());
+ EXPECT_EQ(117, destination.GetExtension(
+ unittest::TestNestedExtension::optionalgroup_extension).a());
+ EXPECT_TRUE(destination.HasExtension(
+ unittest::TestNestedExtension::optional_foreign_enum_extension));
+ EXPECT_EQ(unittest::FOREIGN_BAZ, destination.GetExtension(
+ unittest::TestNestedExtension::optional_foreign_enum_extension));
+}
+
TEST(ExtensionSetTest, Parsing) {
// Serialize as TestAllTypes and parse as TestAllExtensions.
unittest::TestAllTypes source;
@@ -998,8 +1019,8 @@ TEST(ExtensionSetTest, RepeatedFields) {
ASSERT_EQ(110, SumAllExtensions<double>(
message, unittest::repeated_double_extension, 0));
- RepeatedPtrField< ::std::string>::iterator string_iter;
- RepeatedPtrField< ::std::string>::iterator string_end;
+ RepeatedPtrField<::std::string>::iterator string_iter;
+ RepeatedPtrField<::std::string>::iterator string_end;
for (string_iter = message.MutableRepeatedExtension(
unittest::repeated_string_extension)->begin(),
string_end = message.MutableRepeatedExtension(
@@ -1007,8 +1028,8 @@ TEST(ExtensionSetTest, RepeatedFields) {
string_iter != string_end; ++string_iter) {
*string_iter += "test";
}
- RepeatedPtrField< ::std::string>::const_iterator string_const_iter;
- RepeatedPtrField< ::std::string>::const_iterator string_const_end;
+ RepeatedPtrField<::std::string>::const_iterator string_const_iter;
+ RepeatedPtrField<::std::string>::const_iterator string_const_end;
for (string_const_iter = message.GetRepeatedExtension(
unittest::repeated_string_extension).begin(),
string_const_end = message.GetRepeatedExtension(
diff --git a/src/google/protobuf/field_mask.pb.cc b/src/google/protobuf/field_mask.pb.cc
index abee4fe7..2ce061d9 100644
--- a/src/google/protobuf/field_mask.pb.cc
+++ b/src/google/protobuf/field_mask.pb.cc
@@ -7,7 +7,6 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
@@ -19,6 +18,7 @@
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
+
namespace google {
namespace protobuf {
class FieldMaskDefaultTypeInternal {
@@ -29,14 +29,9 @@ class FieldMaskDefaultTypeInternal {
} // namespace protobuf
} // namespace google
namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto {
-void InitDefaultsFieldMaskImpl() {
+static void InitDefaultsFieldMask() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_FieldMask_default_instance_;
new (ptr) ::google::protobuf::FieldMask();
@@ -45,9 +40,11 @@ void InitDefaultsFieldMaskImpl() {
::google::protobuf::FieldMask::InitAsDefaultInstance();
}
-void InitDefaultsFieldMask() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldMaskImpl);
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_FieldMask =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsFieldMask}, {}};
+
+void InitDefaults() {
+ ::google::protobuf::internal::InitSCC(&scc_info_FieldMask.base);
}
::google::protobuf::Metadata file_level_metadata[1];
@@ -68,17 +65,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_FieldMask_default_instance_),
};
-void protobuf_AssignDescriptors() {
+static void protobuf_AssignDescriptors() {
AddDescriptors();
- ::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/field_mask.proto", schemas, file_default_instances, TableStruct::offsets, factory,
+ "google/protobuf/field_mask.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
-void protobuf_AssignDescriptorsOnce() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
+static 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;
@@ -87,7 +83,7 @@ void protobuf_RegisterTypes(const ::std::string&) {
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
-void AddDescriptorsImpl() {
+static void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n google/protobuf/field_mask.proto\022\017goog"
@@ -104,8 +100,8 @@ void AddDescriptorsImpl() {
}
void AddDescriptors() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
+ 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 {
@@ -127,23 +123,20 @@ const int FieldMask::kPathsFieldNumber;
FieldMask::FieldMask()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::InitDefaultsFieldMask();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::scc_info_FieldMask.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FieldMask)
}
FieldMask::FieldMask(const FieldMask& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- paths_(from.paths_),
- _cached_size_(0) {
+ paths_(from.paths_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.FieldMask)
}
void FieldMask::SharedCtor() {
- _cached_size_ = 0;
}
FieldMask::~FieldMask() {
@@ -155,9 +148,7 @@ void FieldMask::SharedDtor() {
}
void FieldMask::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* FieldMask::descriptor() {
::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::protobuf_AssignDescriptorsOnce();
@@ -165,7 +156,7 @@ const ::google::protobuf::Descriptor* FieldMask::descriptor() {
}
const FieldMask& FieldMask::default_instance() {
- ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::InitDefaultsFieldMask();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::scc_info_FieldMask.base);
return *internal_default_instance();
}
@@ -186,7 +177,7 @@ bool FieldMask::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.FieldMask)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -293,9 +284,7 @@ size_t FieldMask::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -350,7 +339,6 @@ void FieldMask::InternalSwap(FieldMask* other) {
using std::swap;
paths_.InternalSwap(CastToBase(&other->paths_));
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata FieldMask::GetMetadata() const {
@@ -364,7 +352,7 @@ void FieldMask::InternalSwap(FieldMask* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldMask* Arena::Create< ::google::protobuf::FieldMask >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldMask* Arena::CreateMaybeMessage< ::google::protobuf::FieldMask >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::FieldMask >(arena);
}
} // namespace protobuf
diff --git a/src/google/protobuf/field_mask.pb.h b/src/google/protobuf/field_mask.pb.h
index 2d75967e..7550f7a9 100644
--- a/src/google/protobuf/field_mask.pb.h
+++ b/src/google/protobuf/field_mask.pb.h
@@ -1,19 +1,19 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/field_mask.proto
-#ifndef PROTOBUF_google_2fprotobuf_2ffield_5fmask_2eproto_INCLUDED
-#define PROTOBUF_google_2fprotobuf_2ffield_5fmask_2eproto_INCLUDED
+#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto
+#define PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3005000
+#if GOOGLE_PROTOBUF_VERSION < 3006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3005001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -24,12 +24,14 @@
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
+#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ffield_5fmask_2eproto LIBPROTOBUF_EXPORT
namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto {
// Internal implementation detail -- do not use these members.
@@ -42,11 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::uint32 offsets[];
};
void LIBPROTOBUF_EXPORT AddDescriptors();
-void LIBPROTOBUF_EXPORT InitDefaultsFieldMaskImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsFieldMask();
-inline void LIBPROTOBUF_EXPORT InitDefaults() {
- InitDefaultsFieldMask();
-}
} // namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto
namespace google {
namespace protobuf {
@@ -57,7 +54,7 @@ LIBPROTOBUF_EXPORT extern FieldMaskDefaultTypeInternal _FieldMask_default_instan
} // namespace google
namespace google {
namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldMask* Arena::Create< ::google::protobuf::FieldMask>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldMask* Arena::CreateMaybeMessage<::google::protobuf::FieldMask>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -99,7 +96,7 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
return reinterpret_cast<const FieldMask*>(
&_FieldMask_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
0;
void Swap(FieldMask* other);
@@ -109,32 +106,33 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
// implements Message ----------------------------------------------
- inline FieldMask* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<FieldMask>(NULL);
+ inline FieldMask* New() const final {
+ return CreateMaybeMessage<FieldMask>(NULL);
}
- FieldMask* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<FieldMask>(arena);
+ FieldMask* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<FieldMask>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const FieldMask& from);
void MergeFrom(const FieldMask& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(FieldMask* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
@@ -145,7 +143,7 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -178,9 +176,8 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::RepeatedPtrField< ::std::string> paths_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::InitDefaultsFieldMaskImpl();
};
// ===================================================================
@@ -273,4 +270,4 @@ FieldMask::mutable_paths() {
// @@protoc_insertion_point(global_scope)
-#endif // PROTOBUF_google_2fprotobuf_2ffield_5fmask_2eproto_INCLUDED
+#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 eb96ba00..76e09f39 100644
--- a/src/google/protobuf/field_mask.proto
+++ b/src/google/protobuf/field_mask.proto
@@ -243,8 +243,8 @@ option go_package = "google.golang.org/genproto/protobuf/field_mask;field_mask";
//
// ## Field Mask Verification
//
-// The implementation of the all the API methods, which have any FieldMask type
-// field in the request, should verify the included field paths, and return
+// The implementation of any API method which has a FieldMask type field in the
+// request should verify the included field paths, and return an
// `INVALID_ARGUMENT` error if any path is duplicated or unmappable.
message FieldMask {
// The set of field mask paths.
diff --git a/src/google/protobuf/generated_enum_util.h b/src/google/protobuf/generated_enum_util.h
index 4f5ded5b..96b03cc9 100644
--- a/src/google/protobuf/generated_enum_util.h
+++ b/src/google/protobuf/generated_enum_util.h
@@ -31,14 +31,14 @@
#ifndef GOOGLE_PROTOBUF_GENERATED_ENUM_UTIL_H__
#define GOOGLE_PROTOBUF_GENERATED_ENUM_UTIL_H__
-#include <google/protobuf/stubs/type_traits.h>
+#include <type_traits>
namespace google {
namespace protobuf {
// This type trait can be used to cause templates to only match proto2 enum
// types.
-template <typename T> struct is_proto_enum : ::google::protobuf::internal::false_type {};
+template <typename T> struct is_proto_enum : ::std::false_type {};
} // namespace protobuf
diff --git a/src/google/protobuf/generated_message_reflection.cc b/src/google/protobuf/generated_message_reflection.cc
index b0c975b4..247f772c 100644
--- a/src/google/protobuf/generated_message_reflection.cc
+++ b/src/google/protobuf/generated_message_reflection.cc
@@ -42,6 +42,7 @@
#include <google/protobuf/extension_set.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/map_field.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/wire_format.h>
@@ -290,6 +291,13 @@ size_t GeneratedMessageReflection::SpaceUsedLong(const Message& message) const {
switch (field->options().ctype()) {
default: // TODO(kenton): Support other string reps.
case FieldOptions::STRING: {
+ if (IsInlined(field)) {
+ const string* ptr =
+ &GetField<InlinedStringField>(message, field).GetNoArena();
+ total_size += StringSpaceUsedExcludingSelfLong(*ptr);
+ break;
+ }
+
// Initially, the string points to the default value stored in
// the prototype. Only count the string if it has been changed
// from the default value.
@@ -424,15 +432,25 @@ void GeneratedMessageReflection::SwapField(
{
Arena* arena1 = GetArena(message1);
Arena* arena2 = GetArena(message2);
+
+ if (IsInlined(field)) {
+ InlinedStringField* string1 =
+ MutableRaw<InlinedStringField>(message1, field);
+ InlinedStringField* string2 =
+ MutableRaw<InlinedStringField>(message2, field);
+ string1->Swap(string2);
+ break;
+ }
+
ArenaStringPtr* string1 =
MutableRaw<ArenaStringPtr>(message1, field);
ArenaStringPtr* string2 =
MutableRaw<ArenaStringPtr>(message2, field);
+ const string* default_ptr =
+ &DefaultRaw<ArenaStringPtr>(field).Get();
if (arena1 == arena2) {
- string1->Swap(string2);
+ string1->Swap(string2, default_ptr, arena1);
} else {
- const string* default_ptr =
- &DefaultRaw<ArenaStringPtr>(field).Get();
const string temp = string1->Get();
string1->Set(default_ptr, string2->Get(), arena1);
string2->Set(default_ptr, temp, arena2);
@@ -738,7 +756,15 @@ int GeneratedMessageReflection::FieldSize(const Message& message,
case FieldDescriptor::CPPTYPE_STRING:
case FieldDescriptor::CPPTYPE_MESSAGE:
if (IsMapFieldInApi(field)) {
- return GetRaw<MapFieldBase>(message, field).GetRepeatedField().size();
+ const internal::MapFieldBase& map =
+ GetRaw<MapFieldBase>(message, field);
+ if (map.IsRepeatedFieldValid()) {
+ return map.GetRepeatedField().size();
+ } else {
+ // No need to materialize the repeated field if it is out of sync:
+ // its size will be the same as the map's size.
+ return map.size();
+ }
} else {
return GetRaw<RepeatedPtrFieldBase>(message, field).size();
}
@@ -789,6 +815,14 @@ void GeneratedMessageReflection::ClearField(
switch (field->options().ctype()) {
default: // TODO(kenton): Support other string reps.
case FieldOptions::STRING: {
+ if (IsInlined(field)) {
+ const string* default_ptr =
+ &DefaultRaw<InlinedStringField>(field).GetNoArena();
+ MutableRaw<InlinedStringField>(message, field)->SetNoArena(
+ default_ptr, *default_ptr);
+ break;
+ }
+
const string* default_ptr =
&DefaultRaw<ArenaStringPtr>(field).Get();
MutableRaw<ArenaStringPtr>(message, field)->SetAllocated(
@@ -1121,6 +1155,10 @@ string GeneratedMessageReflection::GetString(
switch (field->options().ctype()) {
default: // TODO(kenton): Support other string reps.
case FieldOptions::STRING: {
+ if (IsInlined(field)) {
+ return GetField<InlinedStringField>(message, field).GetNoArena();
+ }
+
return GetField<ArenaStringPtr>(message, field).Get();
}
}
@@ -1138,6 +1176,10 @@ const string& GeneratedMessageReflection::GetStringReference(
switch (field->options().ctype()) {
default: // TODO(kenton): Support other string reps.
case FieldOptions::STRING: {
+ if (IsInlined(field)) {
+ return GetField<InlinedStringField>(message, field).GetNoArena();
+ }
+
return GetField<ArenaStringPtr>(message, field).Get();
}
}
@@ -1156,6 +1198,12 @@ void GeneratedMessageReflection::SetString(
switch (field->options().ctype()) {
default: // TODO(kenton): Support other string reps.
case FieldOptions::STRING: {
+ if (IsInlined(field)) {
+ MutableField<InlinedStringField>(message, field)->SetNoArena(
+ NULL, value);
+ break;
+ }
+
const string* default_ptr = &DefaultRaw<ArenaStringPtr>(field).Get();
if (field->containing_oneof() && !HasOneofField(*message, field)) {
ClearOneof(message, field->containing_oneof());
@@ -1868,6 +1916,10 @@ const Type& GeneratedMessageReflection::GetRaw(
return GetConstRefAtOffset<Type>(message, schema_.GetFieldOffset(field));
}
+bool GeneratedMessageReflection::IsInlined(const FieldDescriptor* field) const {
+ return schema_.IsFieldInlined(field);
+}
+
template <typename Type>
Type* GeneratedMessageReflection::MutableRaw(Message* message,
const FieldDescriptor* field) const {
@@ -1963,6 +2015,10 @@ inline bool GeneratedMessageReflection::HasBit(
case FieldDescriptor::CPPTYPE_STRING:
switch (field->options().ctype()) {
default: {
+ if (IsInlined(field)) {
+ return !GetField<InlinedStringField>(message, field)
+ .GetNoArena().empty();
+ }
return GetField<ArenaStringPtr>(message, field).Get().size() > 0;
}
}
@@ -2307,7 +2363,6 @@ struct MetadataOwner {
void AssignDescriptors(
const string& filename, const MigrationSchema* schemas,
const Message* const* default_instances_, const uint32* offsets,
- MessageFactory* factory,
// update the following descriptor arrays.
Metadata* file_level_metadata,
const EnumDescriptor** file_level_enum_descriptors,
@@ -2316,7 +2371,7 @@ void AssignDescriptors(
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(filename);
GOOGLE_CHECK(file != NULL);
- if (!factory) factory = MessageFactory::generated_factory();
+ MessageFactory* factory = MessageFactory::generated_factory();
AssignDescriptorsHelper<MigrationSchema> helper(factory, file_level_metadata,
file_level_enum_descriptors, schemas,
diff --git a/src/google/protobuf/generated_message_reflection.h b/src/google/protobuf/generated_message_reflection.h
index 3c6701cf..28a023b6 100644
--- a/src/google/protobuf/generated_message_reflection.h
+++ b/src/google/protobuf/generated_message_reflection.h
@@ -94,7 +94,7 @@ class WeakFieldMap; // weak_field_map.h
// For each oneof or weak field, the offset is relative to the
// default_instance. These can be computed at compile time
// using the
-// GOOGLE_PROTOBUF_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET()
+// PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET()
// macro. For each none oneof field, the offset is related to
// the start of the message object. These can be computed at
// compile time using the
@@ -134,7 +134,7 @@ struct ReflectionSchema {
// efficient when we know statically that it is not a oneof field.
uint32 GetFieldOffsetNonOneof(const FieldDescriptor* field) const {
GOOGLE_DCHECK(!field->containing_oneof());
- return offsets_[field->index()];
+ return OffsetValue(offsets_[field->index()], field->type());
}
// Offset of any field.
@@ -143,12 +143,23 @@ struct ReflectionSchema {
size_t offset =
static_cast<size_t>(field->containing_type()->field_count() +
field->containing_oneof()->index());
- return offsets_[offset];
+ return OffsetValue(offsets_[offset], field->type());
} else {
return GetFieldOffsetNonOneof(field);
}
}
+ bool IsFieldInlined(const FieldDescriptor* field) const {
+ if (field->containing_oneof()) {
+ size_t offset =
+ static_cast<size_t>(field->containing_type()->field_count() +
+ field->containing_oneof()->index());
+ return Inlined(offsets_[offset], field->type());
+ } else {
+ return Inlined(offsets_[field->index()], field->type());
+ }
+ }
+
uint32 GetOneofCaseOffset(const OneofDescriptor* oneof_descriptor) const {
return static_cast<uint32>(oneof_case_offset_) +
static_cast<uint32>(
@@ -198,7 +209,7 @@ struct ReflectionSchema {
// of the underlying data depends on the field's type.
const void *GetFieldDefault(const FieldDescriptor* field) const {
return reinterpret_cast<const uint8*>(default_instance_) +
- offsets_[field->index()];
+ OffsetValue(offsets_[field->index()], field->type());
}
@@ -219,6 +230,27 @@ struct ReflectionSchema {
int oneof_case_offset_;
int object_size_;
int weak_field_map_offset_;
+
+ // We tag offset values to provide additional data about fields (such as
+ // inlined).
+ static uint32 OffsetValue(uint32 v, FieldDescriptor::Type type) {
+ if (type == FieldDescriptor::TYPE_STRING ||
+ type == FieldDescriptor::TYPE_BYTES) {
+ return v & ~1u;
+ } else {
+ return v;
+ }
+ }
+
+ static bool Inlined(uint32 v, FieldDescriptor::Type type) {
+ if (type == FieldDescriptor::TYPE_STRING ||
+ type == FieldDescriptor::TYPE_BYTES) {
+ return v & 1u;
+ } else {
+ // Non string/byte fields are not inlined.
+ return false;
+ }
+ }
};
// Structs that the code generator emits directly to describe a message.
@@ -257,7 +289,7 @@ struct MigrationSchema {
// of whatever type the individual field would be. Strings and
// Messages use RepeatedPtrFields while everything else uses
// RepeatedFields.
-class LIBPROTOBUF_EXPORT GeneratedMessageReflection PROTOBUF_FINAL : public Reflection {
+class GeneratedMessageReflection final : public Reflection {
public:
// Constructs a GeneratedMessageReflection.
// Parameters:
@@ -272,199 +304,208 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection PROTOBUF_FINAL : public Refl
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;
+ const OneofDescriptor* oneof_descriptor) const override;
+ void ClearOneof(Message* message,
+ const OneofDescriptor* field) 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;
+ const std::vector<const FieldDescriptor*>& fields) const override;
void SwapElements(Message* message, const FieldDescriptor* field,
- int index1, int index2) const;
+ int index1, int index2) const override;
void ListFields(const Message& message,
- std::vector<const FieldDescriptor*>* output) const;
-
+ std::vector<const FieldDescriptor*>* output) const override;
int32 GetInt32 (const Message& message,
- const FieldDescriptor* field) const;
+ const FieldDescriptor* field) const override;
int64 GetInt64 (const Message& message,
- const FieldDescriptor* field) const;
+ 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;
+ const FieldDescriptor* field) const override;
float GetFloat (const Message& message,
- const FieldDescriptor* field) const;
+ const FieldDescriptor* field) const override;
double GetDouble(const Message& message,
- const FieldDescriptor* field) const;
+ const FieldDescriptor* field) const override;
bool GetBool (const Message& message,
- const FieldDescriptor* field) const;
+ const FieldDescriptor* field) const override;
string GetString(const Message& message,
- const FieldDescriptor* field) const;
+ const FieldDescriptor* field) const override;
const string& GetStringReference(const Message& message,
const FieldDescriptor* field,
- string* scratch) const;
- const EnumValueDescriptor* GetEnum(const Message& message,
- const FieldDescriptor* field) const;
+ 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;
+ const MapKey& key) const override;
bool InsertOrLookupMapValue(Message* message,
const FieldDescriptor* field,
const MapKey& key,
- MapValueRef* val) const;
+ MapValueRef* val) const override;
bool DeleteMapValue(Message* message,
const FieldDescriptor* field,
- const MapKey& key) const;
+ const MapKey& key) const override;
MapIterator MapBegin(
Message* message,
- const FieldDescriptor* field) const;
+ const FieldDescriptor* field) const override;
MapIterator MapEnd(
Message* message,
- const FieldDescriptor* field) const;
- int MapSize(const Message& message, const FieldDescriptor* field) const;
+ 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;
+ const FieldDescriptor* field, int32 value) const override;
void SetInt64 (Message* message,
- const FieldDescriptor* field, int64 value) const;
+ const FieldDescriptor* field, int64 value) const override;
void SetUInt32(Message* message,
- const FieldDescriptor* field, uint32 value) const;
+ const FieldDescriptor* field, uint32 value) const override;
void SetUInt64(Message* message,
- const FieldDescriptor* field, uint64 value) const;
+ const FieldDescriptor* field, uint64 value) const override;
void SetFloat (Message* message,
- const FieldDescriptor* field, float value) const;
+ const FieldDescriptor* field, float value) const override;
void SetDouble(Message* message,
- const FieldDescriptor* field, double value) const;
+ const FieldDescriptor* field, double value) const override;
void SetBool (Message* message,
- const FieldDescriptor* field, bool value) const;
+ const FieldDescriptor* field, bool value) const override;
void SetString(Message* message,
const FieldDescriptor* field,
- const string& value) const;
+ const string& value) const override;
void SetEnum (Message* message, const FieldDescriptor* field,
- const EnumValueDescriptor* value) const;
+ 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;
+ MessageFactory* factory = NULL) const override;
void SetAllocatedMessage(Message* message,
Message* sub_message,
- const FieldDescriptor* field) const;
+ 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;
+ string GetRepeatedString(const Message& message, const FieldDescriptor* field,
+ int index) const override;
+ const string &GetRepeatedStringReference(const Message& message,
const FieldDescriptor* field,
- int index, string* scratch) const;
+ int index,
+ 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;
- const Message& GetRepeatedMessage(const Message& message,
+ 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 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;
+ int index) const override;
void AddInt32 (Message* message,
- const FieldDescriptor* field, int32 value) const;
+ const FieldDescriptor* field, int32 value) const override;
void AddInt64 (Message* message,
- const FieldDescriptor* field, int64 value) const;
+ const FieldDescriptor* field, int64 value) const override;
void AddUInt32(Message* message,
- const FieldDescriptor* field, uint32 value) const;
+ const FieldDescriptor* field, uint32 value) const override;
void AddUInt64(Message* message,
- const FieldDescriptor* field, uint64 value) const;
+ const FieldDescriptor* field, uint64 value) const override;
void AddFloat (Message* message,
- const FieldDescriptor* field, float value) const;
+ const FieldDescriptor* field, float value) const override;
void AddDouble(Message* message,
- const FieldDescriptor* field, double value) const;
+ const FieldDescriptor* field, double value) const override;
void AddBool (Message* message,
- const FieldDescriptor* field, bool value) const;
- void AddString(Message* message,
- const FieldDescriptor* field, const string& value) const;
+ const FieldDescriptor* field, bool value) const override;
+ void AddString(Message* message, const FieldDescriptor* field,
+ const string& value) const override;
void AddEnum(Message* message,
const FieldDescriptor* field,
- const EnumValueDescriptor* value) const;
+ const EnumValueDescriptor* value) const override;
void AddEnumValue(Message* message,
const FieldDescriptor* field,
- int value) const;
+ int value) const override;
Message* AddMessage(Message* message, const FieldDescriptor* field,
- MessageFactory* factory = NULL) const;
+ MessageFactory* factory = NULL) const override;
void AddAllocatedMessage(
Message* message, const FieldDescriptor* field,
- Message* new_entry) const;
+ Message* new_entry) const override;
- const FieldDescriptor* FindKnownExtensionByName(const string& name) const;
- const FieldDescriptor* FindKnownExtensionByNumber(int number) const;
+ const FieldDescriptor* FindKnownExtensionByName(
+ const 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).
@@ -482,19 +523,19 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection PROTOBUF_FINAL : public Refl
protected:
void* MutableRawRepeatedField(
Message* message, const FieldDescriptor* field, FieldDescriptor::CppType,
- int ctype, const Descriptor* desc) const;
+ 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 Descriptor* desc) const override;
- virtual MessageFactory* GetMessageFactory() const;
+ virtual MessageFactory* GetMessageFactory() const override;
virtual void* RepeatedFieldData(
Message* message, const FieldDescriptor* field,
FieldDescriptor::CppType cpp_type,
- const Descriptor* message_type) const;
+ const Descriptor* message_type) const override;
private:
friend class google::protobuf::flat::MetadataBuilder;
@@ -543,6 +584,8 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection PROTOBUF_FINAL : public Refl
inline InternalMetadataWithArena*
MutableInternalMetadataWithArena(Message* message) const;
+ inline bool IsInlined(const FieldDescriptor* field) const;
+
inline bool HasBit(const Message& message,
const FieldDescriptor* field) const;
inline void SetBit(Message* message,
@@ -627,7 +670,7 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection PROTOBUF_FINAL : public Refl
const FieldDescriptor* field) const;
internal::MapFieldBase* MapData(
- Message* message, const FieldDescriptor* field) const;
+ Message* message, const FieldDescriptor* field) const override;
friend inline // inline so nobody can call this function.
void
@@ -704,7 +747,6 @@ T* DynamicCastToGenerated(Message* from) {
LIBPROTOBUF_EXPORT void AssignDescriptors(
const string& filename, const MigrationSchema* schemas,
const Message* const* default_instances_, const uint32* offsets,
- MessageFactory* factory,
// update the following descriptor arrays.
Metadata* file_level_metadata,
const EnumDescriptor** file_level_enum_descriptors,
diff --git a/src/google/protobuf/generated_message_reflection_unittest.cc b/src/google/protobuf/generated_message_reflection_unittest.cc
index 242cc4a1..61eb6603 100644
--- a/src/google/protobuf/generated_message_reflection_unittest.cc
+++ b/src/google/protobuf/generated_message_reflection_unittest.cc
@@ -44,9 +44,6 @@
#include <google/protobuf/generated_message_reflection.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/test_util.h>
#include <google/protobuf/unittest.pb.h>
@@ -360,7 +357,7 @@ TEST(GeneratedMessageReflectionTest, ReleaseLast) {
ASSERT_EQ(2, message.repeated_foreign_message_size());
const protobuf_unittest::ForeignMessage* expected =
message.mutable_repeated_foreign_message(1);
- google::protobuf::scoped_ptr<Message> released(message.GetReflection()->ReleaseLast(
+ std::unique_ptr<Message> released(message.GetReflection()->ReleaseLast(
&message, descriptor->FindFieldByName("repeated_foreign_message")));
EXPECT_EQ(expected, released.get());
}
@@ -383,7 +380,7 @@ TEST(GeneratedMessageReflectionTest, ReleaseLastExtensions) {
unittest::repeated_foreign_message_extension));
const protobuf_unittest::ForeignMessage* expected = message.MutableExtension(
unittest::repeated_foreign_message_extension, 1);
- google::protobuf::scoped_ptr<Message> released(message.GetReflection()->ReleaseLast(
+ std::unique_ptr<Message> released(message.GetReflection()->ReleaseLast(
&message, descriptor->file()->FindExtensionByName(
"repeated_foreign_message_extension")));
EXPECT_EQ(expected, released.get());
@@ -746,6 +743,10 @@ TEST(GeneratedMessageReflectionTest, Oneof) {
"change_spiece");
EXPECT_EQ("change_spiece", reflection->GetString(
message, descriptor->FindFieldByName("bar_string_piece")));
+
+ message.clear_foo();
+ message.clear_bar();
+ TestUtil::ExpectOneofClear(message);
}
TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageTest) {
diff --git a/src/google/protobuf/generated_message_table_driven.cc b/src/google/protobuf/generated_message_table_driven.cc
index 29af1ef6..d4450a6c 100644
--- a/src/google/protobuf/generated_message_table_driven.cc
+++ b/src/google/protobuf/generated_message_table_driven.cc
@@ -30,8 +30,9 @@
#include <google/protobuf/generated_message_table_driven.h>
-#include <google/protobuf/stubs/type_traits.h>
+#include <type_traits>
+#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/generated_message_table_driven_lite.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/metadata.h>
diff --git a/src/google/protobuf/generated_message_table_driven.h b/src/google/protobuf/generated_message_table_driven.h
index 6f3fe666..10ca3aaa 100644
--- a/src/google/protobuf/generated_message_table_driven.h
+++ b/src/google/protobuf/generated_message_table_driven.h
@@ -38,9 +38,6 @@
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/wire_format_lite_inl.h>
-#if LANG_CXX11
-#define PROTOBUF_CONSTEXPR constexpr
-
// We require C++11 and Clang to use constexpr for variables, as GCC 4.8
// requires constexpr to be consistent between declarations of variables
// unnecessarily (see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58541).
@@ -51,37 +48,28 @@
#define PROTOBUF_CONSTEXPR_VAR
#endif // !_clang
-#else
-#define PROTOBUF_CONSTEXPR
-#define PROTOBUF_CONSTEXPR_VAR
-#endif
-
namespace google {
namespace protobuf {
namespace internal {
// Processing-type masks.
-static PROTOBUF_CONSTEXPR const unsigned char kOneofMask = 0x40;
-static PROTOBUF_CONSTEXPR const unsigned char kRepeatedMask = 0x20;
+static constexpr const unsigned char kOneofMask = 0x40;
+static constexpr const unsigned char kRepeatedMask = 0x20;
// Mask for the raw type: either a WireFormatLite::FieldType or one of the
// ProcessingTypes below, without the oneof or repeated flag.
-static PROTOBUF_CONSTEXPR const unsigned char kTypeMask = 0x1f;
+static constexpr const unsigned char kTypeMask = 0x1f;
// Wire type masks.
-static PROTOBUF_CONSTEXPR const unsigned char kNotPackedMask = 0x10;
-static PROTOBUF_CONSTEXPR const unsigned char kInvalidMask = 0x20;
+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_MAP = 23,
+ TYPE_STRING_INLINED = 23,
+ TYPE_BYTES_INLINED = 24,
+ TYPE_MAP = 25,
};
-#if LANG_CXX11
static_assert(TYPE_MAP < kRepeatedMask, "Invalid enum");
-#endif
// TODO(ckennelly): Add a static assertion to ensure that these masks do not
// conflict with wiretypes.
@@ -124,7 +112,6 @@ union AuxillaryParseTableField {
const MessageLite* default_message() const {
return static_cast<const MessageLite*>(default_message_void);
}
- const ParseTable* parse_table;
};
message_aux messages;
// Strings
@@ -139,19 +126,14 @@ union AuxillaryParseTableField {
};
map_aux maps;
-#if LANG_CXX11
AuxillaryParseTableField() = default;
-#else
- AuxillaryParseTableField() { }
-#endif
- PROTOBUF_CONSTEXPR AuxillaryParseTableField(
- AuxillaryParseTableField::enum_aux e) : enums(e) {}
- PROTOBUF_CONSTEXPR AuxillaryParseTableField(
- AuxillaryParseTableField::message_aux m) : messages(m) {}
- PROTOBUF_CONSTEXPR AuxillaryParseTableField(
- AuxillaryParseTableField::string_aux s) : strings(s) {}
- PROTOBUF_CONSTEXPR AuxillaryParseTableField(
- AuxillaryParseTableField::map_aux m)
+ constexpr AuxillaryParseTableField(AuxillaryParseTableField::enum_aux e)
+ : enums(e) {}
+ constexpr AuxillaryParseTableField(AuxillaryParseTableField::message_aux m)
+ : messages(m) {}
+ constexpr AuxillaryParseTableField(AuxillaryParseTableField::string_aux s)
+ : strings(s) {}
+ constexpr AuxillaryParseTableField(AuxillaryParseTableField::map_aux m)
: maps(m) {}
};
@@ -178,18 +160,17 @@ struct ParseTable {
bool unknown_field_set;
};
-// TODO(jhen): Remove the __NVCC__ check when we get a version of nvcc that
-// supports these checks.
-#if LANG_CXX11 && !defined(__NVCC__)
static_assert(sizeof(ParseTableField) <= 16, "ParseTableField is too large");
// The tables must be composed of POD components to ensure link-time
// initialization.
static_assert(std::is_pod<ParseTableField>::value, "");
-static_assert(std::is_pod<AuxillaryParseTableField>::value, "");
static_assert(std::is_pod<AuxillaryParseTableField::enum_aux>::value, "");
static_assert(std::is_pod<AuxillaryParseTableField::message_aux>::value, "");
static_assert(std::is_pod<AuxillaryParseTableField::string_aux>::value, "");
static_assert(std::is_pod<ParseTable>::value, "");
+
+#ifndef __NVCC__ // This assertion currently fails under NVCC.
+static_assert(std::is_pod<AuxillaryParseTableField>::value, "");
#endif
// TODO(ckennelly): Consolidate these implementations into a single one, using
diff --git a/src/google/protobuf/generated_message_table_driven_lite.cc b/src/google/protobuf/generated_message_table_driven_lite.cc
index 90a50505..961329f3 100644
--- a/src/google/protobuf/generated_message_table_driven_lite.cc
+++ b/src/google/protobuf/generated_message_table_driven_lite.cc
@@ -30,7 +30,7 @@
#include <google/protobuf/generated_message_table_driven_lite.h>
-#include <google/protobuf/stubs/type_traits.h>
+#include <type_traits>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/metadata_lite.h>
diff --git a/src/google/protobuf/generated_message_table_driven_lite.h b/src/google/protobuf/generated_message_table_driven_lite.h
index 4dfbf678..0d90fe33 100644
--- a/src/google/protobuf/generated_message_table_driven_lite.h
+++ b/src/google/protobuf/generated_message_table_driven_lite.h
@@ -33,14 +33,15 @@
#include <google/protobuf/generated_message_table_driven.h>
-#include <google/protobuf/stubs/type_traits.h>
-
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/extension_set.h>
+#include <google/protobuf/implicit_weak_message.h>
+#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/wire_format_lite_inl.h>
+#include <type_traits>
namespace google {
@@ -50,8 +51,7 @@ namespace internal {
enum StringType {
StringType_STRING = 0,
- StringType_CORD = 1,
- StringType_STRING_PIECE = 2
+ StringType_INLINED = 3
};
// Logically a superset of StringType, consisting of all field types that
@@ -60,7 +60,8 @@ enum ProcessingType {
ProcessingType_STRING = 0,
ProcessingType_CORD = 1,
ProcessingType_STRING_PIECE = 2,
- ProcessingType_MESSAGE = 3
+ ProcessingType_INLINED = 3,
+ ProcessingType_MESSAGE = 4,
};
enum Cardinality {
@@ -99,10 +100,9 @@ inline ExtensionSet* GetExtensionSet(MessageLite* msg, int64 extension_offset) {
template <typename Type>
inline Type* AddField(MessageLite* msg, int64 offset) {
-#if LANG_CXX11
- static_assert(has_trivial_copy<Type>::value,
+ static_assert(std::is_pod<Type>::value ||
+ std::is_same<Type, InlinedStringField>::value,
"Do not assign");
-#endif
google::protobuf::RepeatedField<Type>* repeated =
Raw<google::protobuf::RepeatedField<Type> >(msg, offset);
@@ -119,15 +119,13 @@ inline string* AddField<string>(MessageLite* msg, int64 offset) {
template <typename Type>
inline void AddField(MessageLite* msg, int64 offset, Type value) {
-#if LANG_CXX11
- static_assert(has_trivial_copy<Type>::value,
+ static_assert(std::is_pod<Type>::value,
"Do not assign");
-#endif
*AddField<Type>(msg, offset) = value;
}
inline void SetBit(uint32* has_bits, uint32 has_bit_index) {
- GOOGLE_DCHECK(has_bits != NULL);
+ GOOGLE_DCHECK(has_bits != nullptr);
uint32 mask = static_cast<uint32>(1u) << (has_bit_index % 32);
has_bits[has_bit_index / 32u] |= mask;
@@ -143,10 +141,8 @@ inline Type* MutableField(MessageLite* msg, uint32* has_bits,
template <typename Type>
inline void SetField(MessageLite* msg, uint32* has_bits, uint32 has_bit_index,
int64 offset, Type value) {
-#if LANG_CXX11
- static_assert(has_trivial_copy<Type>::value,
+ static_assert(std::is_pod<Type>::value,
"Do not assign");
-#endif
*MutableField<Type>(msg, has_bits, has_bit_index, offset) = value;
}
@@ -175,6 +171,11 @@ inline void ClearOneofField(const ParseTableField& field, Arena* arena,
->Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
break;
+ case TYPE_STRING_INLINED:
+ case TYPE_BYTES_INLINED:
+ Raw<InlinedStringField>(msg, field.offset)->DestroyNoArena(NULL);
+ break;
+
default:
// No cleanup needed.
break;
@@ -207,6 +208,10 @@ inline void ResetOneofField(const ParseTable& table, int field_number,
Raw<ArenaStringPtr>(msg, offset)
->UnsafeSetDefault(static_cast<const string*>(default_ptr));
break;
+ case ProcessingType_INLINED:
+ new (Raw<InlinedStringField>(msg, offset))
+ InlinedStringField(*static_cast<const string*>(default_ptr));
+ break;
case ProcessingType_MESSAGE:
MessageLite** submessage = Raw<MessageLite*>(msg, offset);
const MessageLite* prototype =
@@ -227,32 +232,65 @@ static inline bool HandleString(io::CodedInputStream* input, MessageLite* msg,
size_t size;
#endif
- string* value;
- switch (cardinality) {
- case Cardinality_SINGULAR:
- // TODO(ckennelly): Is this optimal?
- value =
- MutableField<ArenaStringPtr>(msg, has_bits, has_bit_index, offset)
- ->Mutable(static_cast<const string*>(default_ptr), arena);
- break;
- case Cardinality_REPEATED:
- value = AddField<string>(msg, offset);
- break;
- case Cardinality_ONEOF:
- value = Raw<ArenaStringPtr>(msg, offset)
- ->Mutable(static_cast<const string*>(default_ptr), arena);
- break;
- }
- GOOGLE_DCHECK(value != NULL);
+ switch (ctype) {
+ case StringType_INLINED: {
+ InlinedStringField* s;
+ switch (cardinality) {
+ case Cardinality_SINGULAR:
+ // TODO(ckennelly): Is this optimal?
+ s = MutableField<InlinedStringField>(
+ msg, has_bits, has_bit_index, offset);
+ break;
+ case Cardinality_REPEATED:
+ s = AddField<InlinedStringField>(msg, offset);
+ break;
+ case Cardinality_ONEOF:
+ s = Raw<InlinedStringField>(msg, offset);
+ break;
+ }
+ GOOGLE_DCHECK(s != nullptr);
+ ::std::string* value = s->MutableNoArena(NULL);
+
+ if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) {
+ return false;
+ }
- if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) {
- return false;
+#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
+ sdata = value->data();
+ size = value->size();
+#endif
+ break;
}
+ case StringType_STRING: {
+ string* value;
+ switch (cardinality) {
+ case Cardinality_SINGULAR:
+ // TODO(ckennelly): Is this optimal?
+ value =
+ MutableField<ArenaStringPtr>(msg, has_bits, has_bit_index, offset)
+ ->Mutable(static_cast<const string*>(default_ptr), arena);
+ break;
+ case Cardinality_REPEATED:
+ value = AddField<string>(msg, offset);
+ break;
+ case Cardinality_ONEOF:
+ value = Raw<ArenaStringPtr>(msg, offset)
+ ->Mutable(static_cast<const string*>(default_ptr), arena);
+ break;
+ }
+ GOOGLE_DCHECK(value != nullptr);
+
+ if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) {
+ return false;
+ }
#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
- sdata = value->data();
- size = value->size();
+ sdata = value->data();
+ size = value->size();
#endif
+ break;
+ }
+ }
#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
if (validate) {
@@ -323,44 +361,6 @@ class RepeatedMessageTypeHandler {
}
};
-inline bool ReadGroup(int field_number, io::CodedInputStream* input,
- MessageLite* value) {
- if (GOOGLE_PREDICT_FALSE(!input->IncrementRecursionDepth())) {
- return false;
- }
-
- if (GOOGLE_PREDICT_FALSE(!value->MergePartialFromCodedStream(input))) {
- return false;
- }
-
- input->DecrementRecursionDepth();
- // Make sure the last thing read was an end tag for this group.
- if (GOOGLE_PREDICT_FALSE(!input->LastTagWas(WireFormatLite::MakeTag(
- field_number, WireFormatLite::WIRETYPE_END_GROUP)))) {
- return false;
- }
-
- return true;
-}
-
-inline bool ReadMessage(io::CodedInputStream* input, MessageLite* value) {
- int length;
- if (GOOGLE_PREDICT_FALSE(!input->ReadVarintSizeAsInt(&length))) {
- return false;
- }
-
- std::pair<io::CodedInputStream::Limit, int> p =
- input->IncrementRecursionDepthAndPushLimit(length);
- if (GOOGLE_PREDICT_FALSE(p.second < 0 ||
- !value->MergePartialFromCodedStream(input))) {
- return false;
- }
-
- // Make sure that parsing stopped when the limit was hit, not at an endgroup
- // tag.
- return input->DecrementRecursionDepthAndPopLimit(p.first);
-}
-
class MergePartialFromCodedStreamHelper {
public:
static MessageLite* Add(RepeatedPtrFieldBase* field,
@@ -490,6 +490,23 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
}
break;
}
+ case TYPE_BYTES_INLINED:
+#ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
+ case TYPE_STRING_INLINED:
+#endif
+ {
+ Arena* const arena =
+ GetArena<InternalMetadata>(msg, table.arena_offset);
+ const void* default_ptr = table.aux[field_number].strings.default_ptr;
+
+ if (GOOGLE_PREDICT_FALSE((!HandleString<Cardinality_SINGULAR, false,
+ StringType_INLINED>(
+ input, msg, arena, has_bits, presence_index, offset,
+ default_ptr, NULL)))) {
+ return false;
+ }
+ break;
+ }
case WireFormatLite::TYPE_BYTES | kOneofMask:
#ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
case WireFormatLite::TYPE_STRING | kOneofMask:
@@ -513,8 +530,10 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
break;
}
case (WireFormatLite::TYPE_BYTES) | kRepeatedMask:
+ case TYPE_BYTES_INLINED | kRepeatedMask:
#ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
case (WireFormatLite::TYPE_STRING) | kRepeatedMask:
+ case TYPE_STRING_INLINED | kRepeatedMask:
#endif
{
Arena* const arena =
@@ -545,6 +564,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
}
break;
}
+ case TYPE_STRING_INLINED | kRepeatedMask:
case (WireFormatLite::TYPE_STRING) | kRepeatedMask: {
Arena* const arena =
GetArena<InternalMetadata>(msg, table.arena_offset);
@@ -657,6 +677,10 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
GetArena<InternalMetadata>(msg, table.arena_offset);
const MessageLite* prototype =
table.aux[field_number].messages.default_message();
+ if (prototype == NULL) {
+ prototype =
+ ::google::protobuf::internal::ImplicitWeakMessage::default_instance();
+ }
submsg = prototype->New(arena);
*submsg_holder = submsg;
}
@@ -673,7 +697,10 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
RepeatedPtrFieldBase* field = Raw<RepeatedPtrFieldBase>(msg, offset);
const MessageLite* prototype =
table.aux[field_number].messages.default_message();
- GOOGLE_DCHECK(prototype != NULL);
+ if (prototype == NULL) {
+ prototype =
+ ::google::protobuf::internal::ImplicitWeakMessage::default_instance();
+ }
MessageLite* submsg =
MergePartialFromCodedStreamHelper::Add(field, prototype);
@@ -700,6 +727,22 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
break;
}
+#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
+ case TYPE_STRING_INLINED: {
+ Arena* const arena =
+ GetArena<InternalMetadata>(msg, table.arena_offset);
+ const void* default_ptr = table.aux[field_number].strings.default_ptr;
+ const char* field_name = table.aux[field_number].strings.field_name;
+
+ if (GOOGLE_PREDICT_FALSE((
+ !HandleString<Cardinality_SINGULAR, true, StringType_INLINED>(
+ input, msg, arena, has_bits, presence_index, offset,
+ default_ptr, field_name)))) {
+ return false;
+ }
+ break;
+ }
+#endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
case TYPE_MAP: {
if (GOOGLE_PREDICT_FALSE(!(*table.aux[field_number].maps.parse_map)(
input, Raw<void>(msg, offset)))) {
@@ -721,7 +764,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
GOOGLE_DCHECK_NE(processing_type, kRepeatedMask);
GOOGLE_DCHECK_EQ(0, processing_type & kOneofMask);
-
+ GOOGLE_DCHECK_NE(TYPE_BYTES_INLINED | kRepeatedMask, processing_type);
+ GOOGLE_DCHECK_NE(TYPE_STRING_INLINED | kRepeatedMask, processing_type);
// TODO(ckennelly): Use a computed goto on GCC/LLVM.
//
diff --git a/src/google/protobuf/generated_message_util.cc b/src/google/protobuf/generated_message_util.cc
index 15d84222..dac8ca90 100644
--- a/src/google/protobuf/generated_message_util.cc
+++ b/src/google/protobuf/generated_message_util.cc
@@ -35,6 +35,9 @@
#include <google/protobuf/generated_message_util.h>
#include <limits>
+// We're only using this as a standard way for getting the thread id.
+// We're not using any thread functionality.
+#include <thread> // NOLINT
#include <vector>
#include <google/protobuf/io/coded_stream_inl.h>
@@ -43,6 +46,7 @@
#include <google/protobuf/extension_set.h>
#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>
@@ -61,7 +65,7 @@ double NaN() {
return std::numeric_limits<double>::quiet_NaN();
}
-ExplicitlyConstructed< ::std::string> fixed_address_empty_string;
+ExplicitlyConstructed<::std::string> fixed_address_empty_string;
GOOGLE_PROTOBUF_DECLARE_ONCE(empty_string_once_init_);
void DeleteEmptyString() { fixed_address_empty_string.Destruct(); }
@@ -251,6 +255,10 @@ struct PrimitiveTypeHelper<WireFormatLite::TYPE_BYTES>
: PrimitiveTypeHelper<WireFormatLite::TYPE_STRING> {};
+template <>
+struct PrimitiveTypeHelper<FieldMetadata::kInlinedType>
+ : PrimitiveTypeHelper<WireFormatLite::TYPE_STRING> {};
+
// We want to serialize to both CodedOutputStream and directly into byte arrays
// without duplicating the code. In fact we might want extra output channels in
// the future.
@@ -274,7 +282,7 @@ void WriteLengthTo(uint32 length, O* output) {
// Specialization for coded output stream
template <int type>
-struct OutputHelper< ::google::protobuf::io::CodedOutputStream, type> {
+struct OutputHelper<::google::protobuf::io::CodedOutputStream, type> {
static void Serialize(const void* ptr,
::google::protobuf::io::CodedOutputStream* output) {
PrimitiveTypeHelper<type>::Serialize(ptr, output);
@@ -416,6 +424,15 @@ struct SingularFieldHelper<WireFormatLite::TYPE_MESSAGE> {
}
};
+template <>
+struct SingularFieldHelper<FieldMetadata::kInlinedType> {
+ template <typename O>
+ static void Serialize(const void* field, const FieldMetadata& md, O* output) {
+ WriteTagTo(md.tag, output);
+ SerializeTo<FieldMetadata::kInlinedType>(&Get<::std::string>(field), output);
+ }
+};
+
template <int type>
struct RepeatedFieldHelper {
template <typename O>
@@ -488,6 +505,10 @@ struct RepeatedFieldHelper<WireFormatLite::TYPE_MESSAGE> {
};
+template <>
+struct RepeatedFieldHelper<FieldMetadata::kInlinedType>
+ : RepeatedFieldHelper<WireFormatLite::TYPE_STRING> {};
+
template <int type>
struct PackedFieldHelper {
template <typename O>
@@ -523,6 +544,9 @@ struct PackedFieldHelper<WireFormatLite::TYPE_GROUP>
template <>
struct PackedFieldHelper<WireFormatLite::TYPE_MESSAGE>
: PackedFieldHelper<WireFormatLite::TYPE_STRING> {};
+template <>
+struct PackedFieldHelper<FieldMetadata::kInlinedType>
+ : PackedFieldHelper<WireFormatLite::TYPE_STRING> {};
template <int type>
struct OneOfFieldHelper {
@@ -533,6 +557,15 @@ struct OneOfFieldHelper {
};
+template <>
+struct OneOfFieldHelper<FieldMetadata::kInlinedType> {
+ template <typename O>
+ static void Serialize(const void* field, const FieldMetadata& md, O* output) {
+ SingularFieldHelper<FieldMetadata::kInlinedType>::Serialize(
+ Get<const ::std::string*>(field), md, output);
+ }
+};
+
void SerializeNotImplemented(int field) {
GOOGLE_LOG(FATAL) << "Not implemented field number " << field;
}
@@ -573,6 +606,11 @@ bool IsNull<WireFormatLite::TYPE_MESSAGE>(const void* ptr) {
}
+template <>
+bool IsNull<FieldMetadata::kInlinedType>(const void* ptr) {
+ return static_cast<const ::std::string*>(ptr)->empty();
+}
+
#define SERIALIZERS_FOR_TYPE(type) \
case SERIALIZE_TABLE_OP(type, FieldMetadata::kPresence): \
if (!IsPresent(base, field_metadata.has_offset)) continue; \
@@ -620,6 +658,7 @@ void SerializeInternal(const uint8* base,
SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SFIXED64);
SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT32);
SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT64);
+ SERIALIZERS_FOR_TYPE(FieldMetadata::kInlinedType);
// Special cases
case FieldMetadata::kSpecial:
@@ -663,6 +702,7 @@ uint8* SerializeInternalToArray(const uint8* base,
SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SFIXED64);
SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT32);
SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT64);
+ SERIALIZERS_FOR_TYPE(FieldMetadata::kInlinedType);
// Special cases
case FieldMetadata::kSpecial: {
io::ArrayOutputStream array_stream(array_output.ptr, INT_MAX);
@@ -698,9 +738,9 @@ void UnknownFieldSerializerLite(const uint8* ptr, uint32 offset, uint32 tag,
->unknown_fields());
}
-MessageLite* DuplicateIfNonNullInternal(MessageLite* message, Arena* arena) {
+MessageLite* DuplicateIfNonNullInternal(MessageLite* message) {
if (message) {
- MessageLite* ret = message->New(arena);
+ MessageLite* ret = message->New();
ret->CheckTypeAndMergeFrom(*message);
return ret;
} else {
@@ -725,6 +765,49 @@ MessageLite* GetOwnedMessageInternal(Arena* message_arena,
}
}
+namespace {
+
+void InitSCC_DFS(SCCInfoBase* scc) {
+ if (scc->visit_status.load(std::memory_order_relaxed) !=
+ SCCInfoBase::kUninitialized) return;
+ scc->visit_status.store(SCCInfoBase::kRunning, std::memory_order_relaxed);
+ // Each base is followed by an array of pointers to deps
+ auto deps = reinterpret_cast<SCCInfoBase* const*>(scc + 1);
+ for (int i = 0; i < scc->num_deps; i++) {
+ if (deps[i]) InitSCC_DFS(deps[i]);
+ }
+ scc->init_func();
+ // Mark done (note we use memory order release here), other threads could
+ // now see this as initialized and thus the initialization must have happened
+ // before.
+ scc->visit_status.store(SCCInfoBase::kInitialized, std::memory_order_release);
+}
+
+} // namespace
+
+void InitSCCImpl(SCCInfoBase* scc) {
+ static WrappedMutex mu{GOOGLE_PROTOBUF_LINKER_INITIALIZED};
+ // Either the default in case no initialization is running or the id of the
+ // thread that is currently initializing.
+ static std::atomic<std::thread::id> runner;
+ auto me = std::this_thread::get_id();
+ // This will only happen because the constructor will call InitSCC while
+ // constructing the default instance.
+ if (runner.load(std::memory_order_relaxed) == me) {
+ // Because we're in the process of constructing the default instance.
+ // We can be assured that we're already exploring this SCC.
+ GOOGLE_CHECK_EQ(scc->visit_status.load(std::memory_order_relaxed),
+ SCCInfoBase::kRunning);
+ return;
+ }
+ InitProtobufDefaults();
+ mu.Lock();
+ runner.store(me, std::memory_order_relaxed);
+ InitSCC_DFS(scc);
+ runner.store(std::thread::id{}, std::memory_order_relaxed);
+ mu.Unlock();
+}
+
} // namespace internal
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/generated_message_util.h b/src/google/protobuf/generated_message_util.h
index cd74b45e..4da04cae 100644
--- a/src/google/protobuf/generated_message_util.h
+++ b/src/google/protobuf/generated_message_util.h
@@ -39,13 +39,14 @@
#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_UTIL_H__
#include <assert.h>
+#include <atomic>
#include <climits>
#include <string>
#include <vector>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/once.h>
+#include <google/protobuf/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>
@@ -128,7 +129,7 @@ template <class T>
bool AllAreInitializedWeak(const ::google::protobuf::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)
+ .Get<::google::protobuf::internal::ImplicitWeakTypeHandler<T> >(i)
.IsInitialized()) {
return false;
}
@@ -164,7 +165,8 @@ struct LIBPROTOBUF_EXPORT FieldMetadata {
enum {
kCordType = 19,
kStringPieceType = 20,
- kNumTypes = 20,
+ kInlinedType = 21,
+ kNumTypes = 21,
kSpecial = kNumTypes * kNumTypeClasses,
};
@@ -173,7 +175,7 @@ struct LIBPROTOBUF_EXPORT FieldMetadata {
inline bool IsPresent(const void* base, uint32 hasbit) {
const uint32* has_bits_array = static_cast<const uint32*>(base);
- return has_bits_array[hasbit / 32] & (1u << (hasbit & 31));
+ return (has_bits_array[hasbit / 32] & (1u << (hasbit & 31))) != 0;
}
inline bool IsOneofPresent(const void* base, uint32 offset, uint32 tag) {
@@ -199,7 +201,7 @@ struct SerializationTable {
};
LIBPROTOBUF_EXPORT void SerializeInternal(const uint8* base, const FieldMetadata* table,
- int num_fields, ::google::protobuf::io::CodedOutputStream* output);
+ int32 num_fields, ::google::protobuf::io::CodedOutputStream* output);
inline void TableSerialize(const ::google::protobuf::MessageLite& msg,
const SerializationTable* table,
@@ -217,7 +219,7 @@ 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,
@@ -290,17 +292,17 @@ void MapFieldSerializer(const uint8* base, uint32 offset, uint32 tag,
}
}
-LIBPROTOBUF_EXPORT MessageLite* DuplicateIfNonNullInternal(MessageLite* message, Arena* arena);
+LIBPROTOBUF_EXPORT MessageLite* DuplicateIfNonNullInternal(MessageLite* message);
LIBPROTOBUF_EXPORT MessageLite* GetOwnedMessageInternal(Arena* message_arena,
MessageLite* submessage,
Arena* submessage_arena);
template <typename T>
-T* DuplicateIfNonNull(T* message, Arena* arena) {
+T* DuplicateIfNonNull(T* message) {
// The casts must be reinterpret_cast<> because T might be a forward-declared
// type that the compiler doesn't know is related to MessageLite.
- return reinterpret_cast<T*>(DuplicateIfNonNullInternal(
- reinterpret_cast<MessageLite*>(message), arena));
+ return reinterpret_cast<T*>(
+ DuplicateIfNonNullInternal(reinterpret_cast<MessageLite*>(message)));
}
template <typename T>
@@ -313,20 +315,57 @@ T* GetOwnedMessage(Arena* message_arena, T* submessage,
submessage_arena));
}
-// Returns a message owned by this Arena. This may require Own()ing or
-// duplicating the message.
-template <typename T>
-T* GetOwnedMessage(T* message, Arena* arena) {
- GOOGLE_DCHECK(message);
- Arena* message_arena = google::protobuf::Arena::GetArena(message);
- if (message_arena == arena) {
- return message;
- } else if (arena != NULL && message_arena == NULL) {
- arena->Own(message);
- return message;
- } else {
- return DuplicateIfNonNull(message, arena);
- }
+// 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 {
+ public:
+ int Get() const { return size_.load(std::memory_order_relaxed); }
+ void Set(int size) { size_.store(size, std::memory_order_relaxed); }
+ private:
+ std::atomic<int> size_{0};
+};
+
+// SCCInfo represents information of a strongly connected component of
+// mutual dependent messages.
+struct LIBPROTOBUF_EXPORT SCCInfoBase {
+ // We use 0 for the Initialized state, because test eax,eax, jnz is smaller
+ // and is subject to macro fusion.
+ enum {
+ kInitialized = 0, // final state
+ kRunning = 1,
+ kUninitialized = -1, // initial state
+ };
+#ifndef _MSC_VER
+ std::atomic<int> visit_status;
+#else
+ // 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;
+ };
+#endif
+ int num_deps;
+ void (*init_func)();
+ // This is followed by an array of num_deps
+ // const SCCInfoBase* deps[];
+};
+
+template <int N>
+struct SCCInfo {
+ SCCInfoBase base;
+ // Semantically this is const SCCInfo<T>* which is is a templated type.
+ // The obvious inheriting from SCCInfoBase mucks with struct initialization.
+ // Attempts showed the compiler was generating dynamic initialization code.
+ // Zero length arrays produce warnings with MSVC.
+ SCCInfoBase* deps[N ? N : 1];
+};
+
+LIBPROTOBUF_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);
}
} // namespace internal
diff --git a/src/google/protobuf/implicit_weak_message.cc b/src/google/protobuf/implicit_weak_message.cc
index 0dd126be..7a1d4446 100644
--- a/src/google/protobuf/implicit_weak_message.cc
+++ b/src/google/protobuf/implicit_weak_message.cc
@@ -30,6 +30,7 @@
#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/wire_format_lite.h>
@@ -37,15 +38,26 @@ namespace google {
namespace protobuf {
namespace internal {
-::google::protobuf::internal::ExplicitlyConstructed<ImplicitWeakMessage>
- implicit_weak_message_default_instance;
-
bool ImplicitWeakMessage::MergePartialFromCodedStream(io::CodedInputStream* input) {
io::StringOutputStream string_stream(&data_);
io::CodedOutputStream coded_stream(&string_stream, false);
return WireFormatLite::SkipMessage(input, &coded_stream);
}
+::google::protobuf::internal::ExplicitlyConstructed<ImplicitWeakMessage>
+ implicit_weak_message_default_instance;
+GOOGLE_PROTOBUF_DECLARE_ONCE(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);
+ return &implicit_weak_message_default_instance.get();
+}
+
} // namespace internal
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/implicit_weak_message.h b/src/google/protobuf/implicit_weak_message.h
index a822172e..3279bd17 100644
--- a/src/google/protobuf/implicit_weak_message.h
+++ b/src/google/protobuf/implicit_weak_message.h
@@ -50,6 +50,8 @@ class LIBPROTOBUF_EXPORT ImplicitWeakMessage : public MessageLite {
ImplicitWeakMessage() : arena_(NULL) {}
explicit ImplicitWeakMessage(Arena* arena) : arena_(arena) {}
+ static const ImplicitWeakMessage* default_instance();
+
string GetTypeName() const { return ""; }
MessageLite* New() const { return new ImplicitWeakMessage; }
@@ -91,9 +93,7 @@ class ImplicitWeakTypeHandler {
public:
typedef ImplicitWeakType Type;
typedef ::google::protobuf::MessageLite WeakType;
-#if LANG_CXX11
static const bool Moveable = false;
-#endif
// With implicit weak fields, we need separate NewFromPrototype and
// NewFromPrototypeWeak functions. The former is used when we want to create a
@@ -128,9 +128,6 @@ class ImplicitWeakTypeHandler {
}
};
-extern ::google::protobuf::internal::ExplicitlyConstructed<ImplicitWeakMessage>
- implicit_weak_message_default_instance;
-
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/inlined_string_field.h b/src/google/protobuf/inlined_string_field.h
new file mode 100644
index 00000000..95d4687b
--- /dev/null
+++ b/src/google/protobuf/inlined_string_field.h
@@ -0,0 +1,271 @@
+// 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_INLINED_STRING_FIELD_H__
+#define GOOGLE_PROTOBUF_INLINED_STRING_FIELD_H__
+
+#include <string>
+
+#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/stubs/stringpiece.h>
+
+namespace google {
+namespace protobuf {
+
+class Arena;
+
+namespace internal {
+
+// InlinedStringField wraps a ::std::string instance and exposes an API similar to
+// ArenaStringPtr's wrapping of a ::std::string* instance. As ::std::string is never
+// allocated on the Arena, we expose only the *NoArena methods of
+// ArenaStringPtr.
+//
+// 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 {
+ public:
+ InlinedStringField()
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+ explicit InlinedStringField(const ::std::string& default_value);
+
+ void AssignWithDefault(const ::std::string* default_value,
+ const InlinedStringField& from)
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+
+ void ClearToEmpty(const ::std::string* default_value, Arena* arena)
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ ClearToEmptyNoArena(default_value);
+ }
+ void ClearNonDefaultToEmpty() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ ClearNonDefaultToEmptyNoArena();
+ }
+ void ClearToEmptyNoArena(const ::std::string* default_value)
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ ClearNonDefaultToEmptyNoArena();
+ }
+ void ClearNonDefaultToEmptyNoArena()
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+
+ void ClearToDefault(const ::std::string* default_value, Arena* arena)
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ ClearToDefaultNoArena(default_value);
+ }
+ void ClearToDefaultNoArena(const ::std::string* default_value)
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+
+ void Destroy(const ::std::string* default_value, Arena* arena)
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ DestroyNoArena(default_value);
+ }
+ void DestroyNoArena(const ::std::string* default_value)
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+
+ const ::std::string& Get() const GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ return GetNoArena();
+ }
+ const ::std::string& GetNoArena() const GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+
+ ::std::string* Mutable(const ::std::string* default_value, Arena* arena)
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ return MutableNoArena(default_value);
+ }
+ ::std::string* MutableNoArena(const ::std::string* default_value)
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+
+ ::std::string* Release(const ::std::string* default_value, Arena* arena) {
+ return ReleaseNoArena(default_value);
+ }
+ ::std::string* ReleaseNonDefault(const ::std::string* default_value, Arena* arena) {
+ return ReleaseNonDefaultNoArena(default_value);
+ }
+ ::std::string* ReleaseNoArena(const ::std::string* default_value) {
+ return ReleaseNonDefaultNoArena(default_value);
+ }
+ ::std::string* ReleaseNonDefaultNoArena(const ::std::string* default_value);
+
+ void Set(const ::std::string* default_value,
+ StringPiece value,
+ Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ SetNoArena(default_value, value);
+ }
+ void SetLite(const ::std::string* default_value,
+ StringPiece value,
+ Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ SetNoArena(default_value, value);
+ }
+ void SetNoArena(const ::std::string* default_value,
+ StringPiece value) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+
+ void Set(const ::std::string* default_value,
+ const ::std::string& value,
+ Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ SetNoArena(default_value, value);
+ }
+ void SetLite(const ::std::string* default_value,
+ const ::std::string& value,
+ Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ SetNoArena(default_value, value);
+ }
+ void SetNoArena(const ::std::string* default_value,
+ const ::std::string& value)
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+
+#if LANG_CXX11
+ void SetNoArena(const ::std::string* default_value,
+ ::std::string&& value)
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+#endif
+ void SetAllocated(const ::std::string* default_value,
+ ::std::string* value,
+ Arena* arena) {
+ SetAllocatedNoArena(default_value, value);
+ }
+ void SetAllocatedNoArena(const ::std::string* default_value,
+ ::std::string* value);
+ void Swap(InlinedStringField* from)
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+ ::std::string* UnsafeMutablePointer();
+ void UnsafeSetDefault(const ::std::string* default_value);
+ ::std::string* UnsafeArenaRelease(const ::std::string* default_value, Arena* arena);
+ void UnsafeArenaSetAllocated(
+ const ::std::string* default_value, ::std::string* value, Arena* arena);
+
+ bool IsDefault(const ::std::string* default_value) {
+ return false;
+ }
+ private:
+ ::std::string value_;
+};
+
+inline InlinedStringField::InlinedStringField() {}
+
+inline InlinedStringField::InlinedStringField(const ::std::string& default_value) :
+ value_(default_value) {}
+
+inline void InlinedStringField::AssignWithDefault(
+ const ::std::string* default_value, const InlinedStringField& from) {
+ value_ = from.value_;
+}
+
+inline const ::std::string& InlinedStringField::GetNoArena() const {
+ return value_;
+}
+
+inline ::std::string* InlinedStringField::MutableNoArena(const ::std::string*) {
+ return &value_;
+}
+
+inline void InlinedStringField::SetAllocatedNoArena(
+ const ::std::string* default_value, ::std::string* value) {
+ if (value == NULL) {
+ value_.assign(*default_value);
+ } else {
+#if LANG_CXX11
+ value_.assign(std::move(*value));
+#else
+ value_.swap(*value);
+#endif
+ delete value;
+ }
+}
+
+inline void InlinedStringField::DestroyNoArena(const ::std::string*) {
+ // This is invoked from the generated message's ArenaDtor, which is used to
+ // clean up objects not allocated on the Arena.
+ this->~InlinedStringField();
+}
+
+inline void InlinedStringField::ClearNonDefaultToEmptyNoArena() {
+ value_.clear();
+}
+
+inline void InlinedStringField::ClearToDefaultNoArena(
+ const ::std::string* default_value) {
+ value_.assign(*default_value);
+}
+
+inline ::std::string* InlinedStringField::ReleaseNonDefaultNoArena(
+ const ::std::string* default_value) {
+ ::std::string* released = new ::std::string(*default_value);
+ value_.swap(*released);
+ return released;
+}
+
+inline void InlinedStringField::SetNoArena(
+ const ::std::string* default_value, StringPiece value) {
+ value_.assign(value.data(), value.length());
+}
+
+inline void InlinedStringField::SetNoArena(
+ const ::std::string* default_value, const ::std::string& value) {
+ value_.assign(value);
+}
+
+#if LANG_CXX11
+inline void InlinedStringField::SetNoArena(
+ const ::std::string* default_value, ::std::string&& value) {
+ value_.assign(std::move(value));
+}
+#endif
+
+inline void InlinedStringField::Swap(InlinedStringField* from) {
+ value_.swap(from->value_);
+}
+
+inline ::std::string* InlinedStringField::UnsafeMutablePointer() {
+ return &value_;
+}
+
+inline void InlinedStringField::UnsafeSetDefault(
+ const ::std::string* default_value) {
+ value_.assign(*default_value);
+}
+
+inline ::std::string* InlinedStringField::UnsafeArenaRelease(
+ const ::std::string* default_value, Arena* arena) {
+ return ReleaseNoArena(default_value);
+}
+
+inline void InlinedStringField::UnsafeArenaSetAllocated(
+ const ::std::string* default_value, ::std::string* value, Arena* arena) {
+ if (value == NULL) {
+ value_.assign(*default_value);
+ } else {
+ value_.assign(*value);
+ }
+}
+
+} // namespace internal
+} // namespace protobuf
+
+} // namespace google
+#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 d3bc7c6d..0851ff0c 100644
--- a/src/google/protobuf/io/coded_stream.cc
+++ b/src/google/protobuf/io/coded_stream.cc
@@ -217,8 +217,12 @@ bool CodedInputStream::SkipFallback(int count, int original_buffer_size) {
return false;
}
+ if (!input_->Skip(count)) {
+ total_bytes_read_ = input_->ByteCount();
+ return false;
+ }
total_bytes_read_ += count;
- return input_->Skip(count);
+ return true;
}
bool CodedInputStream::GetDirectBufferPointer(const void** data, int* size) {
@@ -615,23 +619,11 @@ bool CodedInputStream::Refresh() {
// CodedOutputStream =================================================
-google::protobuf::internal::AtomicWord CodedOutputStream::default_serialization_deterministic_ = 0;
+std::atomic<bool> CodedOutputStream::default_serialization_deterministic_{
+ false};
CodedOutputStream::CodedOutputStream(ZeroCopyOutputStream* output)
- : output_(output),
- buffer_(NULL),
- buffer_size_(0),
- total_bytes_(0),
- had_error_(false),
- aliasing_enabled_(false),
- serialization_deterministic_is_overridden_(false) {
- // Eagerly Refresh() so buffer space is immediately available.
- Refresh();
- // The Refresh() may have failed. If the client doesn't write any data,
- // though, don't consider this an error. If the client does write data, then
- // another Refresh() will be attempted and it will set the error once again.
- had_error_ = false;
-}
+ : CodedOutputStream(output, true) {}
CodedOutputStream::CodedOutputStream(ZeroCopyOutputStream* output,
bool do_eager_refresh)
@@ -641,7 +633,7 @@ CodedOutputStream::CodedOutputStream(ZeroCopyOutputStream* output,
total_bytes_(0),
had_error_(false),
aliasing_enabled_(false),
- serialization_deterministic_is_overridden_(false) {
+ is_serialization_deterministic_(IsDefaultSerializationDeterministic()) {
if (do_eager_refresh) {
// Eagerly Refresh() so buffer space is immediately available.
Refresh();
diff --git a/src/google/protobuf/io/coded_stream.h b/src/google/protobuf/io/coded_stream.h
index ec85147b..0f70ecde 100644
--- a/src/google/protobuf/io/coded_stream.h
+++ b/src/google/protobuf/io/coded_stream.h
@@ -110,6 +110,7 @@
#define GOOGLE_PROTOBUF_IO_CODED_STREAM_H__
#include <assert.h>
+#include <atomic>
#include <climits>
#include <string>
#include <utility>
@@ -131,7 +132,6 @@
#define PROTOBUF_LITTLE_ENDIAN 1
#endif
#endif
-#include <google/protobuf/stubs/atomicops.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/port.h>
@@ -829,7 +829,7 @@ class LIBPROTOBUF_EXPORT CodedOutputStream {
// canonicalization specification and implement the serializer using
// reflection APIs rather than relying on this API.
//
- // If determinisitc serialization is requested, the serializer will
+ // If deterministic serialization is requested, the serializer will
// sort map entries by keys in lexicographical order or numerical order.
// (This is an implementation detail and may subject to change.)
//
@@ -840,21 +840,18 @@ class LIBPROTOBUF_EXPORT CodedOutputStream {
// Otherwise, SetSerializationDeterministic has been called, and the last
// value passed to it is all that matters.
void SetSerializationDeterministic(bool value) {
- serialization_deterministic_is_overridden_ = true;
- serialization_deterministic_override_ = value;
+ is_serialization_deterministic_ = value;
}
// See above. Also, note that users of this CodedOutputStream may need to
// call IsSerializationDeterministic() to serialize in the intended way. This
// CodedOutputStream cannot enforce a desire for deterministic serialization
// by itself.
bool IsSerializationDeterministic() const {
- return serialization_deterministic_is_overridden_ ?
- serialization_deterministic_override_ :
- IsDefaultSerializationDeterministic();
+ return is_serialization_deterministic_;
}
static bool IsDefaultSerializationDeterministic() {
- return google::protobuf::internal::NoBarrier_Load(&default_serialization_deterministic_);
+ return default_serialization_deterministic_.load(std::memory_order_relaxed) != 0;
}
private:
@@ -866,12 +863,8 @@ class LIBPROTOBUF_EXPORT CodedOutputStream {
int total_bytes_; // Sum of sizes of all buffers seen so far.
bool had_error_; // Whether an error occurred during output.
bool aliasing_enabled_; // See EnableAliasing().
- // See SetSerializationDeterministic() regarding these three fields.
- bool serialization_deterministic_is_overridden_;
- bool serialization_deterministic_override_;
- // Conceptually, default_serialization_deterministic_ is an atomic bool.
- // TODO(haberman): replace with std::atomic<bool> when we move to C++11.
- static google::protobuf::internal::AtomicWord default_serialization_deterministic_;
+ bool is_serialization_deterministic_;
+ static std::atomic<bool> default_serialization_deterministic_;
// Advance the buffer by a given number of bytes.
void Advance(int amount);
@@ -898,7 +891,7 @@ class LIBPROTOBUF_EXPORT CodedOutputStream {
// thread has done so.
friend void ::google::protobuf::internal::MapTestForceDeterministic();
static void SetDefaultSerializationDeterministic() {
- google::protobuf::internal::NoBarrier_Store(&default_serialization_deterministic_, 1);
+ default_serialization_deterministic_.store(true, std::memory_order_relaxed);
}
};
diff --git a/src/google/protobuf/io/coded_stream_unittest.cc b/src/google/protobuf/io/coded_stream_unittest.cc
index 96f91ae9..1c8d3272 100644
--- a/src/google/protobuf/io/coded_stream_unittest.cc
+++ b/src/google/protobuf/io/coded_stream_unittest.cc
@@ -35,9 +35,6 @@
// This file contains tests and benchmarks.
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
#include <google/protobuf/io/coded_stream.h>
@@ -737,7 +734,7 @@ TEST_F(CodedStreamTest, ReadStringImpossiblyLargeFromStringOnStack) {
}
TEST_F(CodedStreamTest, ReadStringImpossiblyLargeFromStringOnHeap) {
- google::protobuf::scoped_array<uint8> buffer(new uint8[8]);
+ std::unique_ptr<uint8[]> buffer(new uint8[8]);
CodedInputStream coded_input(buffer.get(), 8);
string str;
EXPECT_FALSE(coded_input.ReadString(&str, 1 << 30));
diff --git a/src/google/protobuf/io/gzip_stream.h b/src/google/protobuf/io/gzip_stream.h
index 15b02fe3..df1a446e 100644
--- a/src/google/protobuf/io/gzip_stream.h
+++ b/src/google/protobuf/io/gzip_stream.h
@@ -118,7 +118,7 @@ class LIBPROTOBUF_EXPORT GzipOutputStream : public ZeroCopyOutputStream {
ZLIB = 2,
};
- struct Options {
+ struct LIBPROTOBUF_EXPORT Options {
// Defaults to GZIP.
Format format;
diff --git a/src/google/protobuf/io/printer.cc b/src/google/protobuf/io/printer.cc
index 8493268d..de67cef1 100644
--- a/src/google/protobuf/io/printer.cc
+++ b/src/google/protobuf/io/printer.cc
@@ -350,10 +350,12 @@ void Printer::CopyToBuffer(const char* data, int size) {
while (size > buffer_size_) {
// Data exceeds space in the buffer. Copy what we can and request a
// new buffer.
- memcpy(buffer_, data, buffer_size_);
- offset_ += buffer_size_;
- data += buffer_size_;
- size -= buffer_size_;
+ if (buffer_size_ > 0) {
+ memcpy(buffer_, data, buffer_size_);
+ offset_ += buffer_size_;
+ data += buffer_size_;
+ size -= buffer_size_;
+ }
void* void_buffer;
failed_ = !output_->Next(&void_buffer, &buffer_size_);
if (failed_) return;
diff --git a/src/google/protobuf/io/zero_copy_stream_impl.h b/src/google/protobuf/io/zero_copy_stream_impl.h
index ea978bfb..ef9fc9d2 100644
--- a/src/google/protobuf/io/zero_copy_stream_impl.h
+++ b/src/google/protobuf/io/zero_copy_stream_impl.h
@@ -87,24 +87,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 {
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.
@@ -144,7 +144,7 @@ class LIBPROTOBUF_EXPORT FileOutputStream : public ZeroCopyOutputStream {
// 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 +170,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 {
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.
@@ -220,19 +220,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 {
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:
@@ -261,21 +261,21 @@ class LIBPROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream {
// 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 {
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.
@@ -304,12 +304,13 @@ class LIBPROTOBUF_EXPORT ConcatenatingInputStream : public ZeroCopyInputStream {
// All streams passed in as well as the array itself must remain valid
// until the ConcatenatingInputStream is destroyed.
ConcatenatingInputStream(ZeroCopyInputStream* const streams[], int count);
+ ~ConcatenatingInputStream() 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:
@@ -329,13 +330,13 @@ class LIBPROTOBUF_EXPORT ConcatenatingInputStream : public ZeroCopyInputStream {
class LIBPROTOBUF_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:
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 ab0fd5ac..38b6cde6 100644
--- a/src/google/protobuf/io/zero_copy_stream_impl_lite.h
+++ b/src/google/protobuf/io/zero_copy_stream_impl_lite.h
@@ -45,9 +45,6 @@
#define GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
#include <iosfwd>
#include <google/protobuf/io/zero_copy_stream.h>
@@ -73,12 +70,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:
@@ -106,11 +104,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.
@@ -139,11 +138,12 @@ class LIBPROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream {
// the first call to Next() will return at least n bytes of buffer
// space.
explicit StringOutputStream(string* target);
+ ~StringOutputStream() 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);
@@ -208,17 +208,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.
@@ -239,7 +239,7 @@ class LIBPROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream
// Data is read into this buffer. It may be NULL if no buffer is currently
// in use. Otherwise, it points to an array of size buffer_size_.
- google::protobuf::scoped_array<uint8> buffer_;
+ std::unique_ptr<uint8[]> buffer_;
const int buffer_size_;
// Number of valid bytes currently in the buffer (i.e. the size last
@@ -291,7 +291,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
@@ -303,9 +303,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.
@@ -328,7 +328,7 @@ class LIBPROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStrea
// Data is written from this buffer. It may be NULL if no buffer is
// currently in use. Otherwise, it points to an array of size buffer_size_.
- google::protobuf::scoped_array<uint8> buffer_;
+ std::unique_ptr<uint8[]> buffer_;
const int buffer_size_;
// Number of valid bytes currently in the buffer (i.e. the size last
diff --git a/src/google/protobuf/io/zero_copy_stream_unittest.cc b/src/google/protobuf/io/zero_copy_stream_unittest.cc
index 91792f18..08de8cb1 100644
--- a/src/google/protobuf/io/zero_copy_stream_unittest.cc
+++ b/src/google/protobuf/io/zero_copy_stream_unittest.cc
@@ -56,9 +56,6 @@
#include <fcntl.h>
#include <errno.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <sstream>
#include <google/protobuf/testing/file.h>
@@ -206,7 +203,7 @@ void IoTest::WriteString(ZeroCopyOutputStream* output, const string& str) {
}
void IoTest::ReadString(ZeroCopyInputStream* input, const string& str) {
- google::protobuf::scoped_array<char> buffer(new char[str.size() + 1]);
+ std::unique_ptr<char[]> buffer(new char[str.size() + 1]);
buffer[str.size()] = '\0';
EXPECT_EQ(ReadFromInput(input, buffer.get(), str.size()), str.size());
EXPECT_STREQ(str.c_str(), buffer.get());
diff --git a/src/google/protobuf/lite_arena_unittest.cc b/src/google/protobuf/lite_arena_unittest.cc
index dadaffb6..3e88314d 100644
--- a/src/google/protobuf/lite_arena_unittest.cc
+++ b/src/google/protobuf/lite_arena_unittest.cc
@@ -30,7 +30,6 @@
#include <google/protobuf/arena_test_util.h>
#include <google/protobuf/map_lite_test_util.h>
-#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
namespace google {
@@ -49,7 +48,7 @@ class LiteArenaTest : public testing::Test {
google::protobuf::Arena::CreateArray<char>(arena_.get(), 1);
}
- google::protobuf::scoped_ptr<Arena> arena_;
+ std::unique_ptr<Arena> arena_;
};
TEST_F(LiteArenaTest, MapNoHeapAllocation) {
diff --git a/src/google/protobuf/lite_unittest.cc b/src/google/protobuf/lite_unittest.cc
index d6693963..b42a7b14 100644
--- a/src/google/protobuf/lite_unittest.cc
+++ b/src/google/protobuf/lite_unittest.cc
@@ -621,7 +621,7 @@ TEST(Lite, AllLite28) {
google::protobuf::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* 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));
@@ -1003,3 +1003,34 @@ TEST(Lite, AllLite45) {
EXPECT_EQ(serialized.substr(0, 2), data);
EXPECT_EQ(serialized.substr(2), data);
}
+
+// The following two tests check for wire compatibility between packed and
+// unpacked repeated fields. There used to be a bug in the generated parsing
+// code that caused us to calculate the highest possible tag number without
+// taking into account that a repeated field might not be in the packed (or
+// unpacked) state we expect. These tests specifically check for that issue by
+// making sure we can parse repeated fields when the tag is higher than we would
+// expect.
+TEST(Lite, AllLite46) {
+ protobuf_unittest::PackedInt32 packed;
+ packed.add_repeated_int32(42);
+ string serialized;
+ ASSERT_TRUE(packed.SerializeToString(&serialized));
+
+ protobuf_unittest::NonPackedInt32 non_packed;
+ ASSERT_TRUE(non_packed.ParseFromString(serialized));
+ ASSERT_EQ(1, non_packed.repeated_int32_size());
+ EXPECT_EQ(42, non_packed.repeated_int32(0));
+}
+
+TEST(Lite, AllLite47) {
+ protobuf_unittest::NonPackedFixed32 non_packed;
+ non_packed.add_repeated_fixed32(42);
+ string serialized;
+ ASSERT_TRUE(non_packed.SerializeToString(&serialized));
+
+ protobuf_unittest::PackedFixed32 packed;
+ ASSERT_TRUE(packed.ParseFromString(serialized));
+ ASSERT_EQ(1, packed.repeated_fixed32_size());
+ EXPECT_EQ(42, packed.repeated_fixed32(0));
+}
diff --git a/src/google/protobuf/map.h b/src/google/protobuf/map.h
index a75fb786..6463ac2e 100644
--- a/src/google/protobuf/map.h
+++ b/src/google/protobuf/map.h
@@ -37,6 +37,7 @@
#ifndef GOOGLE_PROTOBUF_MAP_H__
#define GOOGLE_PROTOBUF_MAP_H__
+#include <initializer_list>
#include <iterator>
#include <limits> // To support Visual Studio 2008
#include <set>
@@ -48,10 +49,6 @@
#include <google/protobuf/map_type_handler.h>
#include <google/protobuf/stubs/hash.h>
-#if LANG_CXX11
-#include <initializer_list>
-#endif
-
namespace google {
namespace protobuf {
@@ -146,7 +143,6 @@ class Map {
insert(other.begin(), other.end());
}
-#if LANG_CXX11
Map(Map&& other) noexcept : Map() {
if (other.arena_) {
*this = other;
@@ -164,7 +160,6 @@ class Map {
}
return *this;
}
-#endif
template <class InputIt>
Map(const InputIt& first, const InputIt& last)
@@ -1117,11 +1112,9 @@ class Map {
}
}
}
-#if LANG_CXX11
void insert(std::initializer_list<value_type> values) {
insert(values.begin(), values.end());
}
-#endif
// Erase and clear
size_type erase(const key_type& key) {
diff --git a/src/google/protobuf/map_entry.h b/src/google/protobuf/map_entry.h
index 801def97..f25b5834 100644
--- a/src/google/protobuf/map_entry.h
+++ b/src/google/protobuf/map_entry.h
@@ -95,6 +95,19 @@ class MapEntry
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
+ using typename MapEntryImpl<Derived, Message, Key, Value, kKeyFieldType,
+ kValueFieldType,
+ default_enum_value>::KeyTypeHandler;
+ using typename MapEntryImpl<Derived, Message, Key, Value, kKeyFieldType,
+ kValueFieldType,
+ default_enum_value>::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:
diff --git a/src/google/protobuf/map_entry_lite.h b/src/google/protobuf/map_entry_lite.h
index dc6ec917..01c734bc 100644
--- a/src/google/protobuf/map_entry_lite.h
+++ b/src/google/protobuf/map_entry_lite.h
@@ -33,6 +33,7 @@
#include <assert.h>
+#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/map.h>
@@ -176,13 +177,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 ""; }
+ 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(::google::protobuf::io::CodedInputStream* input) override {
uint32 tag;
for (;;) {
@@ -223,7 +224,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;
@@ -232,13 +233,13 @@ class MapEntryImpl : public Base {
return size;
}
- void SerializeWithCachedSizes(::google::protobuf::io::CodedOutputStream* output) const {
+ void SerializeWithCachedSizes(::google::protobuf::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* output) const override {
output = KeyTypeHandler::InternalWriteToArray(kKeyFieldNumber, key(),
deterministic, output);
output = ValueTypeHandler::InternalWriteToArray(kValueFieldNumber, value(),
@@ -248,7 +249,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())
@@ -259,25 +260,18 @@ 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&).
@@ -297,7 +291,7 @@ class MapEntryImpl : public Base {
}
public:
- void Clear() {
+ void Clear() override {
KeyTypeHandler::Clear(&key_, GetArenaNoVirtual());
ValueTypeHandler::ClearMaybeByDefaultEnum(
&value_, GetArenaNoVirtual(), default_enum_value);
@@ -311,7 +305,7 @@ class MapEntryImpl : public Base {
ValueTypeHandler::AssignDefaultValue(&d->value_);
}
- Arena* GetArena() const {
+ Arena* GetArena() const override {
return GetArenaNoVirtual();
}
@@ -354,9 +348,9 @@ class MapEntryImpl : public Base {
// We could use memcmp here, but we don't bother. The tag is one byte.
GOOGLE_COMPILE_ASSERT(kTagSize == 1, tag_size_error);
if (size > 0 && *reinterpret_cast<const char*>(data) == kValueTag) {
- typename Map::size_type size = map_->size();
+ typename Map::size_type map_size = map_->size();
value_ptr_ = &(*map_)[key_];
- if (GOOGLE_PREDICT_TRUE(size != map_->size())) {
+ if (GOOGLE_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;
@@ -431,7 +425,7 @@ class MapEntryImpl : public Base {
Value* value_ptr_;
// On the fast path entry_ is not used. And, when entry_ is used, it's set
// to mf_->NewEntry(), so in the arena case we must call entry_.release.
- google::protobuf::scoped_ptr<MapEntryImpl> entry_;
+ std::unique_ptr<MapEntryImpl> entry_;
};
protected:
@@ -465,8 +459,8 @@ 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_;
@@ -603,7 +597,7 @@ template <>
struct FromHelper<WireFormatLite::TYPE_STRING> {
static ArenaStringPtr From(const string& x) {
ArenaStringPtr res;
- TaggedPtr< ::std::string> ptr;
+ TaggedPtr<::std::string> ptr;
ptr.Set(const_cast<string*>(&x));
res.UnsafeSetTaggedPointer(ptr);
return res;
@@ -613,7 +607,7 @@ template <>
struct FromHelper<WireFormatLite::TYPE_BYTES> {
static ArenaStringPtr From(const string& x) {
ArenaStringPtr res;
- TaggedPtr< ::std::string> ptr;
+ TaggedPtr<::std::string> ptr;
ptr.Set(const_cast<string*>(&x));
res.UnsafeSetTaggedPointer(ptr);
return res;
diff --git a/src/google/protobuf/map_field.cc b/src/google/protobuf/map_field.cc
index ec4f83e1..ac29c7e9 100644
--- a/src/google/protobuf/map_field.cc
+++ b/src/google/protobuf/map_field.cc
@@ -43,14 +43,14 @@ MapFieldBase::~MapFieldBase() {
const RepeatedPtrFieldBase& MapFieldBase::GetRepeatedField() const {
SyncRepeatedFieldWithMap();
- return *reinterpret_cast< ::google::protobuf::internal::RepeatedPtrFieldBase*>(
+ return *reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
repeated_field_);
}
RepeatedPtrFieldBase* MapFieldBase::MutableRepeatedField() {
SyncRepeatedFieldWithMap();
SetRepeatedDirty();
- return reinterpret_cast< ::google::protobuf::internal::RepeatedPtrFieldBase*>(
+ return reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
repeated_field_);
}
@@ -72,29 +72,39 @@ size_t MapFieldBase::SpaceUsedExcludingSelfNoLock() const {
bool MapFieldBase::IsMapValid() const {
// "Acquire" insures the operation after SyncRepeatedFieldWithMap won't get
// executed before state_ is checked.
- Atomic32 state = google::protobuf::internal::Acquire_Load(&state_);
+ int state = state_.load(std::memory_order_acquire);
return state != STATE_MODIFIED_REPEATED;
}
-void MapFieldBase::SetMapDirty() { state_ = STATE_MODIFIED_MAP; }
+bool MapFieldBase::IsRepeatedFieldValid() const {
+ int state = state_.load(std::memory_order_acquire);
+ return state != STATE_MODIFIED_MAP;
+}
+
+void MapFieldBase::SetMapDirty() {
+ // These are called by (non-const) mutator functions. So by our API it's the
+ // callers responsibility to have these calls properly ordered.
+ state_.store(STATE_MODIFIED_MAP, std::memory_order_relaxed);
+}
-void MapFieldBase::SetRepeatedDirty() { state_ = STATE_MODIFIED_REPEATED; }
+void MapFieldBase::SetRepeatedDirty() {
+ // These are called by (non-const) mutator functions. So by our API it's the
+ // callers responsibility to have these calls properly ordered.
+ state_.store(STATE_MODIFIED_REPEATED, std::memory_order_relaxed);
+}
void* MapFieldBase::MutableRepeatedPtrField() const { return repeated_field_; }
void MapFieldBase::SyncRepeatedFieldWithMap() const {
- // "Acquire" insures the operation after SyncRepeatedFieldWithMap won't get
- // executed before state_ is checked.
- Atomic32 state = google::protobuf::internal::Acquire_Load(&state_);
- if (state == STATE_MODIFIED_MAP) {
+ // acquire here matches with release below to ensure that we can only see a
+ // value of CLEAN after all previous changes have been synced.
+ if (state_.load(std::memory_order_acquire) == STATE_MODIFIED_MAP) {
mutex_.Lock();
// Double check state, because another thread may have seen the same state
// and done the synchronization before the current thread.
- if (state_ == STATE_MODIFIED_MAP) {
+ if (state_.load(std::memory_order_relaxed) == STATE_MODIFIED_MAP) {
SyncRepeatedFieldWithMapNoLock();
- // "Release" insures state_ can only be changed "after"
- // SyncRepeatedFieldWithMapNoLock is finished.
- google::protobuf::internal::Release_Store(&state_, CLEAN);
+ state_.store(CLEAN, std::memory_order_release);
}
mutex_.Unlock();
}
@@ -107,18 +117,15 @@ void MapFieldBase::SyncRepeatedFieldWithMapNoLock() const {
}
void MapFieldBase::SyncMapWithRepeatedField() const {
- // "Acquire" insures the operation after SyncMapWithRepeatedField won't get
- // executed before state_ is checked.
- Atomic32 state = google::protobuf::internal::Acquire_Load(&state_);
- if (state == STATE_MODIFIED_REPEATED) {
+ // acquire here matches with release below to ensure that we can only see a
+ // value of CLEAN after all previous changes have been synced.
+ if (state_.load(std::memory_order_acquire) == STATE_MODIFIED_REPEATED) {
mutex_.Lock();
// Double check state, because another thread may have seen the same state
// and done the synchronization before the current thread.
- if (state_ == STATE_MODIFIED_REPEATED) {
+ if (state_.load(std::memory_order_relaxed) == STATE_MODIFIED_REPEATED) {
SyncMapWithRepeatedFieldNoLock();
- // "Release" insures state_ can only be changed "after"
- // SyncRepeatedFieldWithMapNoLock is finished.
- google::protobuf::internal::Release_Store(&state_, CLEAN);
+ state_.store(CLEAN, std::memory_order_release);
}
mutex_.Unlock();
}
diff --git a/src/google/protobuf/map_field.h b/src/google/protobuf/map_field.h
index 6c75a6da..44ca29b3 100644
--- a/src/google/protobuf/map_field.h
+++ b/src/google/protobuf/map_field.h
@@ -31,7 +31,8 @@
#ifndef GOOGLE_PROTOBUF_MAP_FIELD_H__
#define GOOGLE_PROTOBUF_MAP_FIELD_H__
-#include <google/protobuf/stubs/atomicops.h>
+#include <atomic>
+
#include <google/protobuf/stubs/mutex.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/generated_message_reflection.h>
@@ -86,6 +87,8 @@ class LIBPROTOBUF_EXPORT MapFieldBase {
virtual bool ContainsMapKey(const MapKey& map_key) const = 0;
virtual bool InsertOrLookupMapValue(
const MapKey& map_key, MapValueRef* val) = 0;
+ // Returns whether changes to the map are reflected in the repeated field.
+ bool IsRepeatedFieldValid() const;
// Insures operations after won't get executed before calling this.
bool IsMapValid() const;
virtual bool DeleteMapValue(const MapKey& map_key) = 0;
@@ -140,9 +143,7 @@ class LIBPROTOBUF_EXPORT MapFieldBase {
mutable Mutex mutex_; // The thread to synchronize map and repeated field
// needs to get lock first;
- mutable volatile Atomic32 state_; // 0: STATE_MODIFIED_MAP
- // 1: STATE_MODIFIED_REPEATED
- // 2: CLEAN
+ mutable std::atomic<State> state_;
private:
friend class ContendedMapCleanTest;
@@ -180,10 +181,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;
@@ -193,11 +194,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);
@@ -242,16 +243,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();
@@ -259,7 +260,7 @@ 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);
@@ -284,12 +285,13 @@ class MapField : public TypeDefinedMapFieldBase<Key, T> {
typedef void InternalArenaConstructable_;
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 MapFieldStateTest; // For testing, it needs raw access to impl_
@@ -310,27 +312,27 @@ class LIBPROTOBUF_EXPORT DynamicMapField: public TypeDefinedMapFieldBase<MapKey,
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;
- 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);
};
@@ -814,13 +816,13 @@ struct hash<google::protobuf::MapKey> {
case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
return hash<string>()(map_key.GetStringValue());
case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
- return hash< ::google::protobuf::int64>()(map_key.GetInt64Value());
+ return hash<::google::protobuf::int64>()(map_key.GetInt64Value());
case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
- return hash< ::google::protobuf::int32>()(map_key.GetInt32Value());
+ return hash<::google::protobuf::int32>()(map_key.GetInt32Value());
case google::protobuf::FieldDescriptor::CPPTYPE_UINT64:
- return hash< ::google::protobuf::uint64>()(map_key.GetUInt64Value());
+ return hash<::google::protobuf::uint64>()(map_key.GetUInt64Value());
case google::protobuf::FieldDescriptor::CPPTYPE_UINT32:
- return hash< ::google::protobuf::uint32>()(map_key.GetUInt32Value());
+ return hash<::google::protobuf::uint32>()(map_key.GetUInt32Value());
case google::protobuf::FieldDescriptor::CPPTYPE_BOOL:
return hash<bool>()(map_key.GetBoolValue());
}
diff --git a/src/google/protobuf/map_field_inl.h b/src/google/protobuf/map_field_inl.h
index e317b5ed..d0517792 100644
--- a/src/google/protobuf/map_field_inl.h
+++ b/src/google/protobuf/map_field_inl.h
@@ -32,10 +32,8 @@
#define GOOGLE_PROTOBUF_MAP_FIELD_INL_H__
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
+#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/map.h>
#include <google/protobuf/map_field.h>
#include <google/protobuf/map_type_handler.h>
@@ -254,7 +252,11 @@ void MapField<Derived, Key, T, kKeyFieldType, kValueFieldType,
default_enum_value>::Swap(MapField* other) {
std::swap(this->MapFieldBase::repeated_field_, other->repeated_field_);
impl_.Swap(&other->impl_);
- std::swap(this->MapFieldBase::state_, other->state_);
+ // a relaxed swap of the atomic
+ auto other_state = other->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);
+ this->MapFieldBase::state_.store(other_state, std::memory_order_relaxed);
}
template <typename Derived, typename Key, typename T,
diff --git a/src/google/protobuf/map_field_test.cc b/src/google/protobuf/map_field_test.cc
index 4e0e751c..f58d59e5 100644
--- a/src/google/protobuf/map_field_test.cc
+++ b/src/google/protobuf/map_field_test.cc
@@ -30,9 +30,6 @@
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -71,10 +68,18 @@ class MapFieldBaseStub : public MapFieldBase {
RepeatedPtrField<Message>* InternalRepeatedField() {
return repeated_field_;
}
- bool IsMapClean() { return state_ != 0; }
- bool IsRepeatedClean() { return state_ != 1; }
- void SetMapDirty() { state_ = 0; }
- void SetRepeatedDirty() { state_ = 1; }
+ bool IsMapClean() {
+ return state_.load(std::memory_order_relaxed) != STATE_MODIFIED_MAP;
+ }
+ bool IsRepeatedClean() {
+ return state_.load(std::memory_order_relaxed) != STATE_MODIFIED_REPEATED;
+ }
+ void SetMapDirty() {
+ state_.store(STATE_MODIFIED_MAP, std::memory_order_relaxed);
+ }
+ void SetRepeatedDirty() {
+ state_.store(STATE_MODIFIED_REPEATED, std::memory_order_relaxed);
+ }
bool ContainsMapKey(const MapKey& map_key) const {
return false;
}
@@ -124,7 +129,7 @@ class MapFieldBasePrimitiveTest : public ::testing::Test {
EXPECT_EQ(2, map_->size());
}
- google::protobuf::scoped_ptr<MapFieldType> map_field_;
+ std::unique_ptr<MapFieldType> map_field_;
MapFieldBase* map_field_base_;
Map<int32, int32>* map_;
const Descriptor* map_descriptor_;
@@ -291,7 +296,7 @@ class MapFieldStateTest
}
}
- google::protobuf::scoped_ptr<MapFieldType> map_field_;
+ std::unique_ptr<MapFieldType> map_field_;
MapFieldBase* map_field_base_;
State state_;
};
diff --git a/src/google/protobuf/map_test.cc b/src/google/protobuf/map_test.cc
index d59f92d2..829a60ff 100644
--- a/src/google/protobuf/map_test.cc
+++ b/src/google/protobuf/map_test.cc
@@ -40,9 +40,6 @@
#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <set>
#include <sstream>
#include <vector>
@@ -170,7 +167,7 @@ class MapImplTest : public ::testing::Test {
EXPECT_EQ(value, const_it_copy->second);
}
- google::protobuf::scoped_ptr<Map<int32, int32> > map_ptr_;
+ std::unique_ptr<Map<int32, int32> > map_ptr_;
Map<int32, int32>& map_;
const Map<int32, int32>& const_map_;
};
@@ -676,7 +673,6 @@ TEST_F(MapImplTest, InsertByIterator) {
ExpectElements(map1);
}
-#if LANG_CXX11
TEST_F(MapImplTest, InsertByInitializerList) {
map_.insert({{1, 100}, {2, 200}});
ExpectElements({{1, 100}, {2, 200}});
@@ -684,7 +680,6 @@ TEST_F(MapImplTest, InsertByInitializerList) {
map_.insert({{2, 201}, {3, 301}});
ExpectElements({{1, 100}, {2, 200}, {3, 301}});
}
-#endif
TEST_F(MapImplTest, EraseSingleByKey) {
int32 key = 0;
@@ -1269,19 +1264,19 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) {
&message, fd_map_int32_foreign_message);
// Get entry default instances
- google::protobuf::scoped_ptr<Message> entry_int32_int32(
+ std::unique_ptr<Message> entry_int32_int32(
MessageFactory::generated_factory()
->GetPrototype(fd_map_int32_int32->message_type())
->New());
- google::protobuf::scoped_ptr<Message> entry_int32_double(
+ std::unique_ptr<Message> entry_int32_double(
MessageFactory::generated_factory()
->GetPrototype(fd_map_int32_double->message_type())
->New());
- google::protobuf::scoped_ptr<Message> entry_string_string(
+ std::unique_ptr<Message> entry_string_string(
MessageFactory::generated_factory()
->GetPrototype(fd_map_string_string->message_type())
->New());
- google::protobuf::scoped_ptr<Message> entry_int32_foreign_message(
+ std::unique_ptr<Message> entry_int32_foreign_message(
MessageFactory::generated_factory()
->GetPrototype(fd_map_int32_foreign_message->message_type())
->New());
@@ -1819,7 +1814,7 @@ TEST_F(MapFieldReflectionTest, MapSizeWithDuplicatedKey) {
// Dynamic Message
{
DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<Message> message(
+ std::unique_ptr<Message> message(
factory.GetPrototype(unittest::TestMap::descriptor())->New());
const Reflection* reflection = message->GetReflection();
const FieldDescriptor* field =
@@ -1836,6 +1831,7 @@ TEST_F(MapFieldReflectionTest, MapSizeWithDuplicatedKey) {
EXPECT_EQ(2, reflection->FieldSize(*message, field));
EXPECT_EQ(1, MapSize(reflection, field, *message));
+ EXPECT_EQ(2, reflection->FieldSize(*message, field));
}
// Generated Message
@@ -2004,7 +2000,7 @@ TEST(GeneratedMapFieldTest, CopyFromDynamicMessage) {
// Construct a new version of the dynamic message via the factory.
DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<Message> message1;
+ std::unique_ptr<Message> message1;
message1.reset(
factory.GetPrototype(unittest::TestMap::descriptor())->New());
MapReflectionTester reflection_tester(
@@ -2021,7 +2017,7 @@ TEST(GeneratedMapFieldTest, CopyFromDynamicMessageMapReflection) {
// Construct a new version of the dynamic message via the factory.
DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<Message> message1;
+ std::unique_ptr<Message> message1;
message1.reset(
factory.GetPrototype(unittest::TestMap::descriptor())->New());
MapReflectionTester reflection_tester(
@@ -2040,7 +2036,7 @@ TEST(GeneratedMapFieldTest, DynamicMessageCopyFrom) {
// Construct a new version of the dynamic message via the factory.
DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<Message> message1;
+ std::unique_ptr<Message> message1;
message1.reset(
factory.GetPrototype(unittest::TestMap::descriptor())->New());
@@ -2059,7 +2055,7 @@ TEST(GeneratedMapFieldTest, DynamicMessageCopyFromMapReflection) {
// Construct a dynamic message via the factory.
DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<Message> message1;
+ std::unique_ptr<Message> message1;
message1.reset(
factory.GetPrototype(unittest::TestMap::descriptor())->New());
@@ -2073,7 +2069,7 @@ TEST(GeneratedMapFieldTest, SyncDynamicMapWithRepeatedField) {
MapReflectionTester reflection_tester(
unittest::TestMap::descriptor());
DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<Message> message;
+ std::unique_ptr<Message> message;
message.reset(
factory.GetPrototype(unittest::TestMap::descriptor())->New());
reflection_tester.SetMapFieldsViaReflection(message.get());
@@ -2725,7 +2721,7 @@ TEST_F(MapFieldInDynamicMessageTest, MapIndependentOffsets) {
// Check that all fields have independent offsets by setting each
// one to a unique value then checking that they all still have those
// unique values (i.e. they don't stomp each other).
- google::protobuf::scoped_ptr<Message> message(map_prototype_->New());
+ std::unique_ptr<Message> message(map_prototype_->New());
MapReflectionTester reflection_tester(map_descriptor_);
reflection_tester.SetMapFieldsViaReflection(message.get());
@@ -2734,7 +2730,7 @@ TEST_F(MapFieldInDynamicMessageTest, MapIndependentOffsets) {
TEST_F(MapFieldInDynamicMessageTest, DynamicMapReflection) {
// Check that map fields work properly.
- google::protobuf::scoped_ptr<Message> message(map_prototype_->New());
+ std::unique_ptr<Message> message(map_prototype_->New());
// Check set functions.
MapReflectionTester reflection_tester(map_descriptor_);
@@ -2748,7 +2744,7 @@ TEST_F(MapFieldInDynamicMessageTest, MapSpaceUsed) {
// Since we share the implementation with generated messages, we don't need
// to test very much here. Just make sure it appears to be working.
- google::protobuf::scoped_ptr<Message> message(map_prototype_->New());
+ std::unique_ptr<Message> message(map_prototype_->New());
MapReflectionTester reflection_tester(map_descriptor_);
int initial_space_used = message->SpaceUsed();
@@ -2761,13 +2757,13 @@ TEST_F(MapFieldInDynamicMessageTest, RecursiveMap) {
TestRecursiveMapMessage from;
(*from.mutable_a())[""];
string data = from.SerializeAsString();
- google::protobuf::scoped_ptr<Message> to(
+ std::unique_ptr<Message> to(
factory_.GetPrototype(recursive_map_descriptor_)->New());
ASSERT_TRUE(to->ParseFromString(data));
}
TEST_F(MapFieldInDynamicMessageTest, MapValueReferernceValidAfterSerialize) {
- google::protobuf::scoped_ptr<Message> message(map_prototype_->New());
+ std::unique_ptr<Message> message(map_prototype_->New());
MapReflectionTester reflection_tester(map_descriptor_);
reflection_tester.SetMapFieldsViaMapReflection(message.get());
@@ -2798,7 +2794,7 @@ TEST_F(MapFieldInDynamicMessageTest, MapValueReferernceValidAfterSerialize) {
}
TEST_F(MapFieldInDynamicMessageTest, MapEntryReferernceValidAfterSerialize) {
- google::protobuf::scoped_ptr<Message> message(map_prototype_->New());
+ std::unique_ptr<Message> message(map_prototype_->New());
MapReflectionTester reflection_tester(map_descriptor_);
reflection_tester.SetMapFieldsViaReflection(message.get());
@@ -2967,7 +2963,7 @@ TEST(WireFormatForMapFieldTest, SerializeMap) {
TEST(WireFormatForMapFieldTest, SerializeMapDynamicMessage) {
DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<Message> dynamic_message;
+ std::unique_ptr<Message> dynamic_message;
dynamic_message.reset(
factory.GetPrototype(unittest::TestMap::descriptor())->New());
MapReflectionTester reflection_tester(
@@ -3293,7 +3289,6 @@ TEST(ArenaTest, IsInitialized) {
EXPECT_EQ(0, (*message->mutable_map_int32_int32())[0]);
}
-#if LANG_CXX11
TEST(MoveTest, MoveConstructorWorks) {
Map<int32, TestAllTypes> original_map;
original_map[42].mutable_optional_nested_message()->set_bb(42);
@@ -3329,7 +3324,6 @@ TEST(MoveTest, MoveAssignmentWorks) {
EXPECT_EQ(nested_msg42_ptr, &moved_to_map[42].optional_nested_message());
EXPECT_EQ(nested_msg43_ptr, &moved_to_map[43].optional_nested_message());
}
-#endif
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/message.cc b/src/google/protobuf/message.cc
index 42ec0337..7fda0c79 100644
--- a/src/google/protobuf/message.cc
+++ b/src/google/protobuf/message.cc
@@ -38,20 +38,22 @@
#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>
#include <google/protobuf/io/zero_copy_stream_impl.h>
-#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/map_field.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.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>
@@ -270,7 +272,7 @@ class GeneratedMessageFactory : public MessageFactory {
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.
diff --git a/src/google/protobuf/message.h b/src/google/protobuf/message.h
index fc630b58..4bdda3ad 100644
--- a/src/google/protobuf/message.h
+++ b/src/google/protobuf/message.h
@@ -112,7 +112,7 @@
#include <iosfwd>
#include <string>
-#include <google/protobuf/stubs/type_traits.h>
+#include <type_traits>
#include <vector>
#include <google/protobuf/arena.h>
@@ -196,12 +196,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;
+ virtual 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 {
+ virtual Message* New(::google::protobuf::Arena* arena) const override {
Message* message = New();
if (arena != NULL) {
arena->Own(message);
@@ -233,7 +233,7 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite {
// Like FindInitializationErrors, but joins all the strings, delimited by
// commas, and returns them.
- string InitializationErrorString() const;
+ 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,
@@ -305,13 +305,13 @@ 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;
+ virtual string GetTypeName() const override;
+ virtual void Clear() override;
+ virtual bool IsInitialized() const override;
+ virtual void CheckTypeAndMergeFrom(const MessageLite& other) override;
+ virtual bool MergePartialFromCodedStream(io::CodedInputStream* input) override;
+ virtual size_t ByteSizeLong() const override;
+ virtual void SerializeWithCachedSizes(io::CodedOutputStream* output) const override;
private:
// This is called only by the default implementation of ByteSize(), to
@@ -342,7 +342,7 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite {
//
// This method remains virtual in case a subclass does not implement
// reflection and wants to override the default behavior.
- virtual const Reflection* GetReflection() const PROTOBUF_FINAL {
+ virtual const Reflection* GetReflection() const final {
return GetMetadata().reflection;
}
diff --git a/src/google/protobuf/message_lite.cc b/src/google/protobuf/message_lite.cc
index 123b142d..65af7cea 100644
--- a/src/google/protobuf/message_lite.cc
+++ b/src/google/protobuf/message_lite.cc
@@ -316,7 +316,11 @@ bool MessageLite::SerializeToArray(void* data, int size) const {
}
bool MessageLite::SerializePartialToArray(void* data, int size) const {
- int byte_size = ByteSizeLong();
+ size_t byte_size = ByteSizeLong();
+ if (byte_size > INT_MAX) {
+ GOOGLE_LOG(ERROR) << "Exceeded maximum protobuf size of 2GB: " << size;
+ return false;
+ }
if (size < byte_size) return false;
uint8* start = reinterpret_cast<uint8*>(data);
uint8* end = SerializeWithCachedSizesToArray(start);
diff --git a/src/google/protobuf/message_lite.h b/src/google/protobuf/message_lite.h
index 0b2b24b2..4cbec330 100644
--- a/src/google/protobuf/message_lite.h
+++ b/src/google/protobuf/message_lite.h
@@ -43,11 +43,11 @@
#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>
namespace google {
namespace protobuf {
-class Arena;
template <typename T>
class RepeatedPtrField;
namespace io {
@@ -60,6 +60,7 @@ namespace internal {
class RepeatedPtrFieldBase;
class WireFormatLite;
+class WeakFieldMap;
#ifndef SWIG
// We compute sizes as size_t but cache them as int. This function converts a
@@ -113,13 +114,7 @@ class ExplicitlyConstructed {
get_mutable()->~T();
}
-#if LANG_CXX11
- constexpr
-#endif
- const T&
- get() const {
- return reinterpret_cast<const T&>(union_);
- }
+ constexpr const T& get() const { return reinterpret_cast<const T&>(union_); }
T* get_mutable() { return reinterpret_cast<T*>(&union_); }
private:
@@ -133,7 +128,7 @@ class ExplicitlyConstructed {
// Default empty string object. Don't use this directly. Instead, call
// GetEmptyString() to get the reference.
-extern ExplicitlyConstructed< ::std::string> fixed_address_empty_string;
+LIBPROTOBUF_EXPORT extern ExplicitlyConstructed<::std::string> fixed_address_empty_string;
LIBPROTOBUF_EXPORT extern ProtobufOnceType empty_string_once_init_;
LIBPROTOBUF_EXPORT void InitEmptyString();
@@ -274,7 +269,7 @@ class LIBPROTOBUF_EXPORT MessageLite {
// Reads a protocol buffer from the stream and merges it into this
- // Message. Singular fields read from the input overwrite what is
+ // Message. Singular fields read from the what is
// already in the Message and repeated fields are appended to those
// already present.
//
@@ -399,12 +394,18 @@ class LIBPROTOBUF_EXPORT MessageLite {
return repeated;
}
+ template <typename T>
+ static T* CreateMaybeMessage(Arena* arena) {
+ return Arena::CreateMaybeMessage<T>(arena);
+ }
+
private:
// TODO(gerbens) make this a pure abstract function
virtual const void* InternalGetTable() const { return NULL; }
friend class internal::WireFormatLite;
friend class Message;
+ friend class internal::WeakFieldMap;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageLite);
};
diff --git a/src/google/protobuf/message_unittest.cc b/src/google/protobuf/message_unittest.cc
index a27036e7..45b46bee 100644
--- a/src/google/protobuf/message_unittest.cc
+++ b/src/google/protobuf/message_unittest.cc
@@ -32,542 +32,20 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
-#include <google/protobuf/message.h>
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#ifndef _MSC_VER
-#include <unistd.h>
-#endif
-#include <sstream>
-#include <fstream>
-
-#include <google/protobuf/test_util.h>
#include <google/protobuf/unittest.pb.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>
-#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/arena.h>
-#include <google/protobuf/descriptor.h>
-#include <google/protobuf/generated_message_reflection.h>
-#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/testing/googletest.h>
-#include <gtest/gtest.h>
-#include <google/protobuf/stubs/io_win32.h>
+#define MESSAGE_TEST_NAME MessageTest
+#define MESSAGE_FACTORY_TEST_NAME MessageFactoryTest
+#define UNITTEST_PACKAGE_NAME "protobuf_unittest"
+#define UNITTEST ::protobuf_unittest
+#define UNITTEST_IMPORT ::protobuf_unittest_import
+
+// 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 {
-
-#if defined(_WIN32)
-// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
-// them like we do below.
-using google::protobuf::internal::win32::close;
-using google::protobuf::internal::win32::open;
-#endif
-
-#ifndef O_BINARY
-#ifdef _O_BINARY
-#define O_BINARY _O_BINARY
-#else
-#define O_BINARY 0 // If this isn't defined, the platform doesn't need it.
-#endif
-#endif
-
-TEST(MessageTest, SerializeHelpers) {
- // TODO(kenton): Test more helpers? They're all two-liners so it seems
- // like a waste of time.
-
- protobuf_unittest::TestAllTypes message;
- TestUtil::SetAllFields(&message);
- std::stringstream stream;
-
- string str1("foo");
- string str2("bar");
-
- EXPECT_TRUE(message.SerializeToString(&str1));
- EXPECT_TRUE(message.AppendToString(&str2));
- EXPECT_TRUE(message.SerializeToOstream(&stream));
-
- EXPECT_EQ(str1.size() + 3, str2.size());
- EXPECT_EQ("bar", str2.substr(0, 3));
- // Don't use EXPECT_EQ because we don't want to dump raw binary data to
- // stdout.
- EXPECT_TRUE(str2.substr(3) == str1);
-
- // GCC gives some sort of error if we try to just do stream.str() == str1.
- string temp = stream.str();
- EXPECT_TRUE(temp == str1);
-
- EXPECT_TRUE(message.SerializeAsString() == str1);
-
-}
-
-TEST(MessageTest, SerializeToBrokenOstream) {
- std::ofstream out;
- protobuf_unittest::TestAllTypes message;
- message.set_optional_int32(123);
-
- EXPECT_FALSE(message.SerializeToOstream(&out));
-}
-
-TEST(MessageTest, ParseFromFileDescriptor) {
- string filename = TestSourceDir() +
- "/google/protobuf/testdata/golden_message";
- int file = open(filename.c_str(), O_RDONLY | O_BINARY);
- ASSERT_GE(file, 0);
-
- protobuf_unittest::TestAllTypes message;
- EXPECT_TRUE(message.ParseFromFileDescriptor(file));
- TestUtil::ExpectAllFieldsSet(message);
-
- EXPECT_GE(close(file), 0);
-}
-
-TEST(MessageTest, ParsePackedFromFileDescriptor) {
- string filename =
- TestSourceDir() +
- "/google/protobuf/testdata/golden_packed_fields_message";
- int file = open(filename.c_str(), O_RDONLY | O_BINARY);
- ASSERT_GE(file, 0);
-
- protobuf_unittest::TestPackedTypes message;
- EXPECT_TRUE(message.ParseFromFileDescriptor(file));
- TestUtil::ExpectPackedFieldsSet(message);
-
- EXPECT_GE(close(file), 0);
-}
-
-TEST(MessageTest, ParseHelpers) {
- // TODO(kenton): Test more helpers? They're all two-liners so it seems
- // like a waste of time.
- string data;
-
- {
- // Set up.
- protobuf_unittest::TestAllTypes message;
- TestUtil::SetAllFields(&message);
- message.SerializeToString(&data);
- }
-
- {
- // Test ParseFromString.
- protobuf_unittest::TestAllTypes message;
- EXPECT_TRUE(message.ParseFromString(data));
- TestUtil::ExpectAllFieldsSet(message);
- }
-
- {
- // Test ParseFromIstream.
- protobuf_unittest::TestAllTypes message;
- std::stringstream stream(data);
- EXPECT_TRUE(message.ParseFromIstream(&stream));
- EXPECT_TRUE(stream.eof());
- TestUtil::ExpectAllFieldsSet(message);
- }
-
- {
- // Test ParseFromBoundedZeroCopyStream.
- string data_with_junk(data);
- data_with_junk.append("some junk on the end");
- io::ArrayInputStream stream(data_with_junk.data(), data_with_junk.size());
- protobuf_unittest::TestAllTypes message;
- EXPECT_TRUE(message.ParseFromBoundedZeroCopyStream(&stream, data.size()));
- TestUtil::ExpectAllFieldsSet(message);
- }
-
- {
- // Test that ParseFromBoundedZeroCopyStream fails (but doesn't crash) if
- // EOF is reached before the expected number of bytes.
- io::ArrayInputStream stream(data.data(), data.size());
- protobuf_unittest::TestAllTypes message;
- EXPECT_FALSE(
- message.ParseFromBoundedZeroCopyStream(&stream, data.size() + 1));
- }
-}
-
-TEST(MessageTest, ParseFailsIfNotInitialized) {
- unittest::TestRequired message;
- std::vector<string> errors;
-
- {
- ScopedMemoryLog log;
- EXPECT_FALSE(message.ParseFromString(""));
- errors = log.GetMessages(ERROR);
- }
-
- ASSERT_EQ(1, errors.size());
- EXPECT_EQ("Can't parse message of type \"protobuf_unittest.TestRequired\" "
- "because it is missing required fields: a, b, c",
- errors[0]);
-}
-
-TEST(MessageTest, BypassInitializationCheckOnParse) {
- unittest::TestRequired message;
- io::ArrayInputStream raw_input(NULL, 0);
- io::CodedInputStream input(&raw_input);
- EXPECT_TRUE(message.MergePartialFromCodedStream(&input));
-}
-
-TEST(MessageTest, InitializationErrorString) {
- unittest::TestRequired message;
- EXPECT_EQ("a, b, c", message.InitializationErrorString());
-}
-
-TEST(MessageTest, 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(NULL,
- google::protobuf::internal::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(
- NULL,
- google::protobuf::internal::DynamicCastToGenerated<const unittest::TestRequired>(
- test_all_types_pointer_const));
-}
-
-#ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet.
-
-TEST(MessageTest, SerializeFailsIfNotInitialized) {
- unittest::TestRequired message;
- string data;
- EXPECT_DEBUG_DEATH(EXPECT_TRUE(message.SerializeToString(&data)),
- "Can't serialize message of type \"protobuf_unittest.TestRequired\" because "
- "it is missing required fields: a, b, c");
-}
-
-TEST(MessageTest, CheckInitialized) {
- unittest::TestRequired message;
- EXPECT_DEATH(message.CheckInitialized(),
- "Message of type \"protobuf_unittest.TestRequired\" is missing required "
- "fields: a, b, c");
-}
-
-#endif // PROTOBUF_HAS_DEATH_TEST
-
-namespace {
-// An input stream that repeats a string's content for a number of times. It
-// helps us create a really large input without consuming too much memory. Used
-// to test the parsing behavior when the input size exceeds 2G or close to it.
-class RepeatedInputStream : public io::ZeroCopyInputStream {
- public:
- RepeatedInputStream(const string& data, size_t count)
- : data_(data), count_(count), position_(0), total_byte_count_(0) {}
-
- virtual bool Next(const void** data, int* size) {
- if (position_ == data_.size()) {
- if (--count_ == 0) {
- return false;
- }
- position_ = 0;
- }
- *data = &data_[position_];
- *size = static_cast<int>(data_.size() - position_);
- position_ = data_.size();
- total_byte_count_ += *size;
- return true;
- }
-
- virtual void BackUp(int count) {
- position_ -= static_cast<size_t>(count);
- total_byte_count_ -= count;
- }
-
- virtual bool Skip(int count) {
- while (count > 0) {
- const void* data;
- int size;
- if (!Next(&data, &size)) {
- break;
- }
- if (size >= count) {
- BackUp(size - count);
- return true;
- } else {
- count -= size;
- }
- }
- return false;
- }
-
- virtual int64 ByteCount() const { return total_byte_count_; }
-
- private:
- string data_;
- size_t count_; // The number of strings that haven't been consuemd.
- size_t position_; // Position in the string for the next read.
- int64 total_byte_count_;
-};
-} // namespace
-
-TEST(MessageTest, TestParseMessagesCloseTo2G) {
- // Create a message with a large string field.
- string value = string(64 * 1024 * 1024, 'x');
- protobuf_unittest::TestAllTypes message;
- message.set_optional_string(value);
-
- // Repeat this message in the input stream to make the total input size
- // close to 2G.
- string data = message.SerializeAsString();
- size_t count = static_cast<size_t>(kint32max) / data.size();
- RepeatedInputStream input(data, count);
-
- // The parsing should succeed.
- protobuf_unittest::TestAllTypes result;
- EXPECT_TRUE(result.ParseFromZeroCopyStream(&input));
-
- // When there are multiple occurences of a singulr field, the last one
- // should win.
- EXPECT_EQ(value, result.optional_string());
-}
-
-TEST(MessageTest, TestParseMessagesOver2G) {
- // Create a message with a large string field.
- string value = string(64 * 1024 * 1024, 'x');
- protobuf_unittest::TestAllTypes message;
- message.set_optional_string(value);
-
- // Repeat this message in the input stream to make the total input size
- // larger than 2G.
- string data = message.SerializeAsString();
- size_t count = static_cast<size_t>(kint32max) / data.size() + 1;
- RepeatedInputStream input(data, count);
-
- // The parsing should fail.
- protobuf_unittest::TestAllTypes result;
- EXPECT_FALSE(result.ParseFromZeroCopyStream(&input));
-}
-
-TEST(MessageTest, BypassInitializationCheckOnSerialize) {
- unittest::TestRequired message;
- io::ArrayOutputStream raw_output(NULL, 0);
- io::CodedOutputStream output(&raw_output);
- EXPECT_TRUE(message.SerializePartialToCodedStream(&output));
-}
-
-TEST(MessageTest, FindInitializationErrors) {
- unittest::TestRequired message;
- std::vector<string> errors;
- message.FindInitializationErrors(&errors);
- ASSERT_EQ(3, errors.size());
- EXPECT_EQ("a", errors[0]);
- EXPECT_EQ("b", errors[1]);
- EXPECT_EQ("c", errors[2]);
-}
-
-TEST(MessageTest, ParseFailsOnInvalidMessageEnd) {
- unittest::TestAllTypes message;
-
- // Control case.
- EXPECT_TRUE(message.ParseFromArray("", 0));
-
- // The byte is a valid varint, but not a valid tag (zero).
- EXPECT_FALSE(message.ParseFromArray("\0", 1));
-
- // The byte is a malformed varint.
- EXPECT_FALSE(message.ParseFromArray("\200", 1));
-
- // The byte is an endgroup tag, but we aren't parsing a group.
- EXPECT_FALSE(message.ParseFromArray("\014", 1));
-}
-
-// Regression test for b/23630858
-TEST(MessageTest, MessageIsStillValidAfterParseFails) {
- unittest::TestAllTypes message;
-
- // 9 0xFFs for the "optional_uint64" field.
- string invalid_data = "\x20\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF";
-
- EXPECT_FALSE(message.ParseFromString(invalid_data));
- message.Clear();
- EXPECT_EQ(0, message.optional_uint64());
-
- // invalid data for field "optional_string". Length prefix is 1 but no
- // payload.
- string invalid_string_data = "\x72\x01";
- {
- google::protobuf::Arena arena;
- unittest::TestAllTypes* arena_message =
- google::protobuf::Arena::CreateMessage<unittest::TestAllTypes>(&arena);
- EXPECT_FALSE(arena_message->ParseFromString(invalid_string_data));
- arena_message->Clear();
- EXPECT_EQ("", arena_message->optional_string());
- }
-}
-
-
-namespace {
-
-void ExpectMessageMerged(const unittest::TestAllTypes& message) {
- EXPECT_EQ(3, message.optional_int32());
- EXPECT_EQ(2, message.optional_int64());
- EXPECT_EQ("hello", message.optional_string());
-}
-
-void AssignParsingMergeMessages(
- unittest::TestAllTypes* msg1,
- unittest::TestAllTypes* msg2,
- unittest::TestAllTypes* msg3) {
- msg1->set_optional_int32(1);
- msg2->set_optional_int64(2);
- msg3->set_optional_int32(3);
- msg3->set_optional_string("hello");
-}
-
-} // namespace
-
-// Test that if an optional or required message/group field appears multiple
-// times in the input, they need to be merged.
-TEST(MessageTest, ParsingMerge) {
- unittest::TestParsingMerge::RepeatedFieldsGenerator generator;
- unittest::TestAllTypes* msg1;
- unittest::TestAllTypes* msg2;
- unittest::TestAllTypes* msg3;
-
-#define ASSIGN_REPEATED_FIELD(FIELD) \
- msg1 = generator.add_##FIELD(); \
- msg2 = generator.add_##FIELD(); \
- msg3 = generator.add_##FIELD(); \
- AssignParsingMergeMessages(msg1, msg2, msg3)
-
- ASSIGN_REPEATED_FIELD(field1);
- ASSIGN_REPEATED_FIELD(field2);
- ASSIGN_REPEATED_FIELD(field3);
- ASSIGN_REPEATED_FIELD(ext1);
- ASSIGN_REPEATED_FIELD(ext2);
-
-#undef ASSIGN_REPEATED_FIELD
-#define ASSIGN_REPEATED_GROUP(FIELD) \
- msg1 = generator.add_##FIELD()->mutable_field1(); \
- msg2 = generator.add_##FIELD()->mutable_field1(); \
- msg3 = generator.add_##FIELD()->mutable_field1(); \
- AssignParsingMergeMessages(msg1, msg2, msg3)
-
- ASSIGN_REPEATED_GROUP(group1);
- ASSIGN_REPEATED_GROUP(group2);
-
-#undef ASSIGN_REPEATED_GROUP
-
- string buffer;
- generator.SerializeToString(&buffer);
- unittest::TestParsingMerge parsing_merge;
- parsing_merge.ParseFromString(buffer);
-
- // Required and optional fields should be merged.
- ExpectMessageMerged(parsing_merge.required_all_types());
- ExpectMessageMerged(parsing_merge.optional_all_types());
- ExpectMessageMerged(
- parsing_merge.optionalgroup().optional_group_all_types());
- ExpectMessageMerged(
- parsing_merge.GetExtension(unittest::TestParsingMerge::optional_ext));
-
- // Repeated fields should not be merged.
- EXPECT_EQ(3, parsing_merge.repeated_all_types_size());
- EXPECT_EQ(3, parsing_merge.repeatedgroup_size());
- EXPECT_EQ(3, parsing_merge.ExtensionSize(
- unittest::TestParsingMerge::repeated_ext));
-}
-
-TEST(MessageTest, MergeFrom) {
- unittest::TestAllTypes source;
- unittest::TestAllTypes dest;
-
- // Optional fields
- source.set_optional_int32(1); // only source
- source.set_optional_int64(2); // both source and dest
- dest.set_optional_int64(3);
- dest.set_optional_uint32(4); // only dest
-
- // Optional fields with defaults
- source.set_default_int32(13); // only source
- source.set_default_int64(14); // both source and dest
- dest.set_default_int64(15);
- dest.set_default_uint32(16); // only dest
-
- // Repeated fields
- source.add_repeated_int32(5); // only source
- source.add_repeated_int32(6);
- source.add_repeated_int64(7); // both source and dest
- source.add_repeated_int64(8);
- dest.add_repeated_int64(9);
- dest.add_repeated_int64(10);
- dest.add_repeated_uint32(11); // only dest
- dest.add_repeated_uint32(12);
-
- dest.MergeFrom(source);
-
- // Optional fields: source overwrites dest if source is specified
- EXPECT_EQ(1, dest.optional_int32()); // only source: use source
- EXPECT_EQ(2, dest.optional_int64()); // source and dest: use source
- EXPECT_EQ(4, dest.optional_uint32()); // only dest: use dest
- EXPECT_EQ(0, dest.optional_uint64()); // neither: use default
-
- // Optional fields with defaults
- EXPECT_EQ(13, dest.default_int32()); // only source: use source
- EXPECT_EQ(14, dest.default_int64()); // source and dest: use source
- EXPECT_EQ(16, dest.default_uint32()); // only dest: use dest
- EXPECT_EQ(44, dest.default_uint64()); // neither: use default
-
- // Repeated fields: concatenate source onto the end of dest
- ASSERT_EQ(2, dest.repeated_int32_size());
- EXPECT_EQ(5, dest.repeated_int32(0));
- EXPECT_EQ(6, dest.repeated_int32(1));
- ASSERT_EQ(4, dest.repeated_int64_size());
- EXPECT_EQ(9, dest.repeated_int64(0));
- EXPECT_EQ(10, dest.repeated_int64(1));
- EXPECT_EQ(7, dest.repeated_int64(2));
- EXPECT_EQ(8, dest.repeated_int64(3));
- ASSERT_EQ(2, dest.repeated_uint32_size());
- EXPECT_EQ(11, dest.repeated_uint32(0));
- EXPECT_EQ(12, dest.repeated_uint32(1));
- ASSERT_EQ(0, dest.repeated_uint64_size());
-}
-
-TEST(MessageTest, IsInitialized) {
- protobuf_unittest::TestIsInitialized msg;
- EXPECT_TRUE(msg.IsInitialized());
- protobuf_unittest::TestIsInitialized::SubMessage* sub_message = msg.mutable_sub_message();
- EXPECT_TRUE(msg.IsInitialized());
- protobuf_unittest::TestIsInitialized::SubMessage::SubGroup* sub_group = sub_message->mutable_subgroup();
- EXPECT_FALSE(msg.IsInitialized());
- sub_group->set_i(1);
- EXPECT_TRUE(msg.IsInitialized());
-}
-
-TEST(MessageFactoryTest, GeneratedFactoryLookup) {
- EXPECT_EQ(
- MessageFactory::generated_factory()->GetPrototype(
- protobuf_unittest::TestAllTypes::descriptor()),
- &protobuf_unittest::TestAllTypes::default_instance());
-}
-
-TEST(MessageFactoryTest, GeneratedFactoryUnknownType) {
- // Construct a new descriptor.
- DescriptorPool pool;
- FileDescriptorProto file;
- file.set_name("foo.proto");
- file.add_message_type()->set_name("Foo");
- const Descriptor* descriptor = pool.BuildFile(file)->message_type(0);
-
- // Trying to construct it should return NULL.
- EXPECT_TRUE(
- MessageFactory::generated_factory()->GetPrototype(descriptor) == NULL);
-}
-
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/message_unittest.inc b/src/google/protobuf/message_unittest.inc
new file mode 100644
index 00000000..6ffdcce0
--- /dev/null
+++ b/src/google/protobuf/message_unittest.inc
@@ -0,0 +1,577 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: kenton@google.com (Kenton Varda)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+//
+// This file needs to be included as .inc as it depends on certain macros being
+// defined prior to its inclusion.
+
+#include <google/protobuf/message.h>
+
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#ifndef _MSC_VER
+#include <unistd.h>
+#endif
+#include <fstream>
+#include <sstream>
+
+#include <google/protobuf/io/coded_stream.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/arena.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/generated_message_reflection.h>
+
+#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/testing/googletest.h>
+#include <gtest/gtest.h>
+#include <google/protobuf/stubs/io_win32.h>
+
+namespace google {
+namespace protobuf {
+
+#if defined(_WIN32)
+// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
+// them like we do below.
+using google::protobuf::internal::win32::close;
+using google::protobuf::internal::win32::open;
+#endif
+
+#ifndef O_BINARY
+#ifdef _O_BINARY
+#define O_BINARY _O_BINARY
+#else
+#define O_BINARY 0 // If this isn't defined, the platform doesn't need it.
+#endif
+#endif
+
+TEST(MESSAGE_TEST_NAME, SerializeHelpers) {
+ // TODO(kenton): Test more helpers? They're all two-liners so it seems
+ // like a waste of time.
+
+ UNITTEST::TestAllTypes message;
+ TestUtil::SetAllFields(&message);
+ std::stringstream stream;
+
+ string str1("foo");
+ string str2("bar");
+
+ EXPECT_TRUE(message.SerializeToString(&str1));
+ EXPECT_TRUE(message.AppendToString(&str2));
+ EXPECT_TRUE(message.SerializeToOstream(&stream));
+
+ EXPECT_EQ(str1.size() + 3, str2.size());
+ EXPECT_EQ("bar", str2.substr(0, 3));
+ // Don't use EXPECT_EQ because we don't want to dump raw binary data to
+ // stdout.
+ EXPECT_TRUE(str2.substr(3) == str1);
+
+ // GCC gives some sort of error if we try to just do stream.str() == str1.
+ string temp = stream.str();
+ EXPECT_TRUE(temp == str1);
+
+ EXPECT_TRUE(message.SerializeAsString() == str1);
+
+}
+
+TEST(MESSAGE_TEST_NAME, SerializeToBrokenOstream) {
+ std::ofstream out;
+ UNITTEST::TestAllTypes message;
+ message.set_optional_int32(123);
+
+ EXPECT_FALSE(message.SerializeToOstream(&out));
+}
+
+TEST(MESSAGE_TEST_NAME, ParseFromFileDescriptor) {
+ string filename = TestSourceDir() +
+ "/google/protobuf/testdata/golden_message";
+ int file = open(filename.c_str(), O_RDONLY | O_BINARY);
+ ASSERT_GE(file, 0);
+
+ UNITTEST::TestAllTypes message;
+ EXPECT_TRUE(message.ParseFromFileDescriptor(file));
+ TestUtil::ExpectAllFieldsSet(message);
+
+ EXPECT_GE(close(file), 0);
+}
+
+TEST(MESSAGE_TEST_NAME, ParsePackedFromFileDescriptor) {
+ string filename =
+ TestSourceDir() +
+ "/google/protobuf/testdata/golden_packed_fields_message";
+ int file = open(filename.c_str(), O_RDONLY | O_BINARY);
+ ASSERT_GE(file, 0);
+
+ UNITTEST::TestPackedTypes message;
+ EXPECT_TRUE(message.ParseFromFileDescriptor(file));
+ TestUtil::ExpectPackedFieldsSet(message);
+
+ EXPECT_GE(close(file), 0);
+}
+
+TEST(MESSAGE_TEST_NAME, ParseHelpers) {
+ // TODO(kenton): Test more helpers? They're all two-liners so it seems
+ // like a waste of time.
+ string data;
+
+ {
+ // Set up.
+ UNITTEST::TestAllTypes message;
+ TestUtil::SetAllFields(&message);
+ message.SerializeToString(&data);
+ }
+
+ {
+ // Test ParseFromString.
+ UNITTEST::TestAllTypes message;
+ EXPECT_TRUE(message.ParseFromString(data));
+ TestUtil::ExpectAllFieldsSet(message);
+ }
+
+ {
+ // Test ParseFromIstream.
+ UNITTEST::TestAllTypes message;
+ std::stringstream stream(data);
+ EXPECT_TRUE(message.ParseFromIstream(&stream));
+ EXPECT_TRUE(stream.eof());
+ TestUtil::ExpectAllFieldsSet(message);
+ }
+
+ {
+ // Test ParseFromBoundedZeroCopyStream.
+ string data_with_junk(data);
+ data_with_junk.append("some junk on the end");
+ io::ArrayInputStream stream(data_with_junk.data(), data_with_junk.size());
+ UNITTEST::TestAllTypes message;
+ EXPECT_TRUE(message.ParseFromBoundedZeroCopyStream(&stream, data.size()));
+ TestUtil::ExpectAllFieldsSet(message);
+ }
+
+ {
+ // Test that ParseFromBoundedZeroCopyStream fails (but doesn't crash) if
+ // EOF is reached before the expected number of bytes.
+ io::ArrayInputStream stream(data.data(), data.size());
+ UNITTEST::TestAllTypes message;
+ EXPECT_FALSE(
+ message.ParseFromBoundedZeroCopyStream(&stream, data.size() + 1));
+ }
+}
+
+TEST(MESSAGE_TEST_NAME, ParseFailsIfNotInitialized) {
+ UNITTEST::TestRequired message;
+ std::vector<string> errors;
+
+ {
+ ScopedMemoryLog log;
+ EXPECT_FALSE(message.ParseFromString(""));
+ errors = log.GetMessages(ERROR);
+ }
+
+ ASSERT_EQ(1, errors.size());
+ EXPECT_EQ(
+ "Can't parse message of type \"" + string(UNITTEST_PACKAGE_NAME) +
+ ".TestRequired\" because it is missing required fields: a, b, c",
+ errors[0]);
+}
+
+TEST(MESSAGE_TEST_NAME, BypassInitializationCheckOnParse) {
+ UNITTEST::TestRequired message;
+ io::ArrayInputStream raw_input(nullptr, 0);
+ io::CodedInputStream input(&raw_input);
+ EXPECT_TRUE(message.MergePartialFromCodedStream(&input));
+}
+
+TEST(MESSAGE_TEST_NAME, InitializationErrorString) {
+ UNITTEST::TestRequired message;
+ EXPECT_EQ("a, b, c", message.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));
+
+ 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));
+}
+
+#ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet.
+
+TEST(MESSAGE_TEST_NAME, SerializeFailsIfNotInitialized) {
+ UNITTEST::TestRequired message;
+ string data;
+ EXPECT_DEBUG_DEATH(EXPECT_TRUE(message.SerializeToString(&data)),
+ "Can't serialize message of type \"" +
+ string(UNITTEST_PACKAGE_NAME) +
+ ".TestRequired\" because "
+ "it is missing required fields: a, b, c");
+}
+
+TEST(MESSAGE_TEST_NAME, CheckInitialized) {
+ UNITTEST::TestRequired message;
+ EXPECT_DEATH(message.CheckInitialized(),
+ "Message of type \"" +
+ string(UNITTEST_PACKAGE_NAME) +
+ ".TestRequired\" is missing required "
+ "fields: a, b, c");
+}
+
+#endif // PROTOBUF_HAS_DEATH_TEST
+
+namespace {
+// An input stream that repeats a string's content for a number of times. It
+// helps us create a really large input without consuming too much memory. Used
+// to test the parsing behavior when the input size exceeds 2G or close to it.
+class RepeatedInputStream : public io::ZeroCopyInputStream {
+ public:
+ RepeatedInputStream(const string& data, size_t count)
+ : data_(data), count_(count), position_(0), total_byte_count_(0) {}
+
+ virtual bool Next(const void** data, int* size) {
+ if (position_ == data_.size()) {
+ if (--count_ == 0) {
+ return false;
+ }
+ position_ = 0;
+ }
+ *data = &data_[position_];
+ *size = static_cast<int>(data_.size() - position_);
+ position_ = data_.size();
+ total_byte_count_ += *size;
+ return true;
+ }
+
+ virtual void BackUp(int count) {
+ position_ -= static_cast<size_t>(count);
+ total_byte_count_ -= count;
+ }
+
+ virtual bool Skip(int count) {
+ while (count > 0) {
+ const void* data;
+ int size;
+ if (!Next(&data, &size)) {
+ break;
+ }
+ if (size >= count) {
+ BackUp(size - count);
+ return true;
+ } else {
+ count -= size;
+ }
+ }
+ return false;
+ }
+
+ virtual int64 ByteCount() const { return total_byte_count_; }
+
+ private:
+ string data_;
+ size_t count_; // The number of strings that haven't been consuemd.
+ size_t position_; // Position in the string for the next read.
+ int64 total_byte_count_;
+};
+} // namespace
+
+TEST(MESSAGE_TEST_NAME, TestParseMessagesCloseTo2G) {
+ // Create a message with a large string field.
+ string value = string(64 * 1024 * 1024, 'x');
+ UNITTEST::TestAllTypes message;
+ message.set_optional_string(value);
+
+ // Repeat this message in the input stream to make the total input size
+ // close to 2G.
+ string data = message.SerializeAsString();
+ size_t count = static_cast<size_t>(kint32max) / data.size();
+ RepeatedInputStream input(data, count);
+
+ // The parsing should succeed.
+ UNITTEST::TestAllTypes result;
+ EXPECT_TRUE(result.ParseFromZeroCopyStream(&input));
+
+ // When there are multiple occurences of a singulr field, the last one
+ // should win.
+ EXPECT_EQ(value, result.optional_string());
+}
+
+TEST(MESSAGE_TEST_NAME, TestParseMessagesOver2G) {
+ // Create a message with a large string field.
+ string value = string(64 * 1024 * 1024, 'x');
+ UNITTEST::TestAllTypes message;
+ message.set_optional_string(value);
+
+ // Repeat this message in the input stream to make the total input size
+ // larger than 2G.
+ string data = message.SerializeAsString();
+ size_t count = static_cast<size_t>(kint32max) / data.size() + 1;
+ RepeatedInputStream input(data, count);
+
+ // The parsing should fail.
+ UNITTEST::TestAllTypes result;
+ EXPECT_FALSE(result.ParseFromZeroCopyStream(&input));
+}
+
+TEST(MESSAGE_TEST_NAME, BypassInitializationCheckOnSerialize) {
+ UNITTEST::TestRequired message;
+ io::ArrayOutputStream raw_output(nullptr, 0);
+ io::CodedOutputStream output(&raw_output);
+ EXPECT_TRUE(message.SerializePartialToCodedStream(&output));
+}
+
+TEST(MESSAGE_TEST_NAME, FindInitializationErrors) {
+ UNITTEST::TestRequired message;
+ std::vector<string> errors;
+ message.FindInitializationErrors(&errors);
+ ASSERT_EQ(3, errors.size());
+ EXPECT_EQ("a", errors[0]);
+ EXPECT_EQ("b", errors[1]);
+ EXPECT_EQ("c", errors[2]);
+}
+
+TEST(MESSAGE_TEST_NAME, ParseFailsOnInvalidMessageEnd) {
+ UNITTEST::TestAllTypes message;
+
+ // Control case.
+ EXPECT_TRUE(message.ParseFromArray("", 0));
+
+ // The byte is a valid varint, but not a valid tag (zero).
+ EXPECT_FALSE(message.ParseFromArray("\0", 1));
+
+ // The byte is a malformed varint.
+ EXPECT_FALSE(message.ParseFromArray("\200", 1));
+
+ // The byte is an endgroup tag, but we aren't parsing a group.
+ EXPECT_FALSE(message.ParseFromArray("\014", 1));
+}
+
+// Regression test for b/23630858
+TEST(MESSAGE_TEST_NAME, MessageIsStillValidAfterParseFails) {
+ UNITTEST::TestAllTypes message;
+
+ // 9 0xFFs for the "optional_uint64" field.
+ string invalid_data = "\x20\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF";
+
+ EXPECT_FALSE(message.ParseFromString(invalid_data));
+ message.Clear();
+ EXPECT_EQ(0, message.optional_uint64());
+
+ // invalid data for field "optional_string". Length prefix is 1 but no
+ // payload.
+ string invalid_string_data = "\x72\x01";
+ {
+ google::protobuf::Arena arena;
+ UNITTEST::TestAllTypes* arena_message =
+ google::protobuf::Arena::CreateMessage<UNITTEST::TestAllTypes>(&arena);
+ EXPECT_FALSE(arena_message->ParseFromString(invalid_string_data));
+ arena_message->Clear();
+ EXPECT_EQ("", arena_message->optional_string());
+ }
+}
+
+
+namespace {
+
+void ExpectMessageMerged(const UNITTEST::TestAllTypes& message) {
+ EXPECT_EQ(3, message.optional_int32());
+ EXPECT_EQ(2, message.optional_int64());
+ EXPECT_EQ("hello", message.optional_string());
+}
+
+void AssignParsingMergeMessages(UNITTEST::TestAllTypes* msg1,
+ UNITTEST::TestAllTypes* msg2,
+ UNITTEST::TestAllTypes* msg3) {
+ msg1->set_optional_int32(1);
+ msg2->set_optional_int64(2);
+ msg3->set_optional_int32(3);
+ msg3->set_optional_string("hello");
+}
+
+} // namespace
+
+// Test that if an optional or required message/group field appears multiple
+// times in the input, they need to be merged.
+TEST(MESSAGE_TEST_NAME, ParsingMerge) {
+ UNITTEST::TestParsingMerge::RepeatedFieldsGenerator generator;
+ UNITTEST::TestAllTypes* msg1;
+ UNITTEST::TestAllTypes* msg2;
+ UNITTEST::TestAllTypes* msg3;
+
+#define ASSIGN_REPEATED_FIELD(FIELD) \
+ msg1 = generator.add_##FIELD(); \
+ msg2 = generator.add_##FIELD(); \
+ msg3 = generator.add_##FIELD(); \
+ AssignParsingMergeMessages(msg1, msg2, msg3)
+
+ ASSIGN_REPEATED_FIELD(field1);
+ ASSIGN_REPEATED_FIELD(field2);
+ ASSIGN_REPEATED_FIELD(field3);
+ ASSIGN_REPEATED_FIELD(ext1);
+ ASSIGN_REPEATED_FIELD(ext2);
+
+#undef ASSIGN_REPEATED_FIELD
+#define ASSIGN_REPEATED_GROUP(FIELD) \
+ msg1 = generator.add_##FIELD()->mutable_field1(); \
+ msg2 = generator.add_##FIELD()->mutable_field1(); \
+ msg3 = generator.add_##FIELD()->mutable_field1(); \
+ AssignParsingMergeMessages(msg1, msg2, msg3)
+
+ ASSIGN_REPEATED_GROUP(group1);
+ ASSIGN_REPEATED_GROUP(group2);
+
+#undef ASSIGN_REPEATED_GROUP
+
+ string buffer;
+ generator.SerializeToString(&buffer);
+ UNITTEST::TestParsingMerge parsing_merge;
+ parsing_merge.ParseFromString(buffer);
+
+ // Required and optional fields should be merged.
+ ExpectMessageMerged(parsing_merge.required_all_types());
+ ExpectMessageMerged(parsing_merge.optional_all_types());
+ ExpectMessageMerged(parsing_merge.optionalgroup().optional_group_all_types());
+ ExpectMessageMerged(
+ parsing_merge.GetExtension(UNITTEST::TestParsingMerge::optional_ext));
+
+ // Repeated fields should not be merged.
+ EXPECT_EQ(3, parsing_merge.repeated_all_types_size());
+ EXPECT_EQ(3, parsing_merge.repeatedgroup_size());
+ EXPECT_EQ(
+ 3, parsing_merge.ExtensionSize(UNITTEST::TestParsingMerge::repeated_ext));
+}
+
+TEST(MESSAGE_TEST_NAME, MergeFrom) {
+ UNITTEST::TestAllTypes source, dest;
+
+ // Optional fields
+ source.set_optional_int32(1); // only source
+ source.set_optional_int64(2); // both source and dest
+ dest.set_optional_int64(3);
+ dest.set_optional_uint32(4); // only dest
+
+ // Optional fields with defaults
+ source.set_default_int32(13); // only source
+ source.set_default_int64(14); // both source and dest
+ dest.set_default_int64(15);
+ dest.set_default_uint32(16); // only dest
+
+ // Repeated fields
+ source.add_repeated_int32(5); // only source
+ source.add_repeated_int32(6);
+ source.add_repeated_int64(7); // both source and dest
+ source.add_repeated_int64(8);
+ dest.add_repeated_int64(9);
+ dest.add_repeated_int64(10);
+ dest.add_repeated_uint32(11); // only dest
+ dest.add_repeated_uint32(12);
+
+ dest.MergeFrom(source);
+
+ // Optional fields: source overwrites dest if source is specified
+ EXPECT_EQ(1, dest.optional_int32()); // only source: use source
+ EXPECT_EQ(2, dest.optional_int64()); // source and dest: use source
+ EXPECT_EQ(4, dest.optional_uint32()); // only dest: use dest
+ EXPECT_EQ(0, dest.optional_uint64()); // neither: use default
+
+ // Optional fields with defaults
+ EXPECT_EQ(13, dest.default_int32()); // only source: use source
+ EXPECT_EQ(14, dest.default_int64()); // source and dest: use source
+ EXPECT_EQ(16, dest.default_uint32()); // only dest: use dest
+ EXPECT_EQ(44, dest.default_uint64()); // neither: use default
+
+ // Repeated fields: concatenate source onto the end of dest
+ ASSERT_EQ(2, dest.repeated_int32_size());
+ EXPECT_EQ(5, dest.repeated_int32(0));
+ EXPECT_EQ(6, dest.repeated_int32(1));
+ ASSERT_EQ(4, dest.repeated_int64_size());
+ EXPECT_EQ(9, dest.repeated_int64(0));
+ EXPECT_EQ(10, dest.repeated_int64(1));
+ EXPECT_EQ(7, dest.repeated_int64(2));
+ EXPECT_EQ(8, dest.repeated_int64(3));
+ ASSERT_EQ(2, dest.repeated_uint32_size());
+ EXPECT_EQ(11, dest.repeated_uint32(0));
+ EXPECT_EQ(12, dest.repeated_uint32(1));
+ ASSERT_EQ(0, dest.repeated_uint64_size());
+}
+
+TEST(MESSAGE_TEST_NAME, IsInitialized) {
+ UNITTEST::TestIsInitialized msg;
+ EXPECT_TRUE(msg.IsInitialized());
+ UNITTEST::TestIsInitialized::SubMessage* sub_message =
+ msg.mutable_sub_message();
+ EXPECT_TRUE(msg.IsInitialized());
+ UNITTEST::TestIsInitialized::SubMessage::SubGroup* sub_group =
+ sub_message->mutable_subgroup();
+ EXPECT_FALSE(msg.IsInitialized());
+ sub_group->set_i(1);
+ EXPECT_TRUE(msg.IsInitialized());
+}
+
+TEST(MESSAGE_FACTORY_TEST_NAME, GeneratedFactoryLookup) {
+ EXPECT_EQ(MessageFactory::generated_factory()->GetPrototype(
+ UNITTEST::TestAllTypes::descriptor()),
+ &UNITTEST::TestAllTypes::default_instance());
+}
+
+TEST(MESSAGE_FACTORY_TEST_NAME, GeneratedFactoryUnknownType) {
+ // Construct a new descriptor.
+ DescriptorPool pool;
+ FileDescriptorProto file;
+ file.set_name("foo.proto");
+ file.add_message_type()->set_name("Foo");
+ const Descriptor* descriptor = pool.BuildFile(file)->message_type(0);
+
+ // Trying to construct it should return nullptr.
+ EXPECT_TRUE(MessageFactory::generated_factory()->GetPrototype(descriptor) ==
+ nullptr);
+}
+
+
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/preserve_unknown_enum_test.cc b/src/google/protobuf/preserve_unknown_enum_test.cc
index 1673e8af..e292199e 100644
--- a/src/google/protobuf/preserve_unknown_enum_test.cc
+++ b/src/google/protobuf/preserve_unknown_enum_test.cc
@@ -120,7 +120,7 @@ TEST(PreserveUnknownEnumTest, PreserveParseAndSerializeDynamicMessage) {
string serialized = orig_message.SerializeAsString();
google::protobuf::DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<google::protobuf::Message> message(factory.GetPrototype(
+ std::unique_ptr<google::protobuf::Message> message(factory.GetPrototype(
proto3_preserve_unknown_enum_unittest::MyMessage::descriptor())->New());
EXPECT_EQ(true, message->ParseFromString(serialized));
message->DiscardUnknownFields();
@@ -161,7 +161,7 @@ TEST(PreserveUnknownEnumTest, DynamicProto2HidesUnknownValues) {
orig_message.SerializeToString(&serialized);
google::protobuf::DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<google::protobuf::Message> message(factory.GetPrototype(
+ std::unique_ptr<google::protobuf::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".
diff --git a/src/google/protobuf/proto3_arena_lite_unittest.cc b/src/google/protobuf/proto3_arena_lite_unittest.cc
index 0f18c027..2ac775d7 100644
--- a/src/google/protobuf/proto3_arena_lite_unittest.cc
+++ b/src/google/protobuf/proto3_arena_lite_unittest.cc
@@ -30,20 +30,15 @@
#include <string>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
-#include <google/protobuf/test_util.h>
-#include <google/protobuf/unittest.pb.h>
-#include <google/protobuf/unittest_proto3_arena_lite.pb.h>
+#include <google/protobuf/unittest_proto3_arena.pb.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
namespace google {
-using proto3_arena_lite_unittest::TestAllTypes;
+using proto3_arena_unittest::TestAllTypes;
namespace protobuf {
namespace {
@@ -56,9 +51,9 @@ void SetAllFields(TestAllTypes* m) {
m->mutable_optional_nested_message()->set_bb(42);
m->mutable_optional_foreign_message()->set_c(43);
m->set_optional_nested_enum(
- proto3_arena_lite_unittest::TestAllTypes_NestedEnum_BAZ);
+ proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ);
m->set_optional_foreign_enum(
- proto3_arena_lite_unittest::FOREIGN_BAZ);
+ proto3_arena_unittest::FOREIGN_BAZ);
m->mutable_optional_lazy_message()->set_bb(45);
m->add_repeated_int32(100);
m->add_repeated_string("asdf");
@@ -66,9 +61,9 @@ void SetAllFields(TestAllTypes* m) {
m->add_repeated_nested_message()->set_bb(46);
m->add_repeated_foreign_message()->set_c(47);
m->add_repeated_nested_enum(
- proto3_arena_lite_unittest::TestAllTypes_NestedEnum_BAZ);
+ proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ);
m->add_repeated_foreign_enum(
- proto3_arena_lite_unittest::FOREIGN_BAZ);
+ proto3_arena_unittest::FOREIGN_BAZ);
m->add_repeated_lazy_message()->set_bb(49);
m->set_oneof_uint32(1);
@@ -84,9 +79,9 @@ void ExpectAllFieldsSet(const TestAllTypes& m) {
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_arena_lite_unittest::TestAllTypes_NestedEnum_BAZ,
+ EXPECT_EQ(proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ,
m.optional_nested_enum());
- EXPECT_EQ(proto3_arena_lite_unittest::FOREIGN_BAZ,
+ EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ,
m.optional_foreign_enum());
EXPECT_EQ(true, m.has_optional_lazy_message());
EXPECT_EQ(45, m.optional_lazy_message().bb());
@@ -102,15 +97,15 @@ void ExpectAllFieldsSet(const TestAllTypes& m) {
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_arena_lite_unittest::TestAllTypes_NestedEnum_BAZ,
+ EXPECT_EQ(proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ,
m.repeated_nested_enum(0));
EXPECT_EQ(1, m.repeated_foreign_enum_size());
- EXPECT_EQ(proto3_arena_lite_unittest::FOREIGN_BAZ,
+ EXPECT_EQ(proto3_arena_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_arena_lite_unittest::TestAllTypes::kOneofString,
+ EXPECT_EQ(proto3_arena_unittest::TestAllTypes::kOneofString,
m.oneof_field_case());
EXPECT_EQ("test", m.oneof_string());
}
@@ -154,7 +149,7 @@ TEST(Proto3ArenaLiteTest, ReleaseMessage) {
Arena arena;
TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
arena_message->mutable_optional_nested_message()->set_bb(118);
- google::protobuf::scoped_ptr<TestAllTypes::NestedMessage> nested(
+ std::unique_ptr<TestAllTypes::NestedMessage> nested(
arena_message->release_optional_nested_message());
EXPECT_EQ(118, nested->bb());
}
diff --git a/src/google/protobuf/proto3_arena_unittest.cc b/src/google/protobuf/proto3_arena_unittest.cc
index 3a0fb804..dac73781 100644
--- a/src/google/protobuf/proto3_arena_unittest.cc
+++ b/src/google/protobuf/proto3_arena_unittest.cc
@@ -30,9 +30,6 @@
#include <string>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
#include <google/protobuf/test_util.h>
@@ -198,7 +195,7 @@ TEST(Proto3ArenaTest, ReleaseMessage) {
Arena arena;
TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
arena_message->mutable_optional_nested_message()->set_bb(118);
- google::protobuf::scoped_ptr<TestAllTypes::NestedMessage> nested(
+ std::unique_ptr<TestAllTypes::NestedMessage> nested(
arena_message->release_optional_nested_message());
EXPECT_EQ(118, nested->bb());
}
diff --git a/src/google/protobuf/proto3_lite_unittest.cc b/src/google/protobuf/proto3_lite_unittest.cc
index 2e2beea9..8b2c5742 100644
--- a/src/google/protobuf/proto3_lite_unittest.cc
+++ b/src/google/protobuf/proto3_lite_unittest.cc
@@ -30,13 +30,8 @@
#include <string>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
-#include <google/protobuf/test_util.h>
-#include <google/protobuf/unittest.pb.h>
#include <google/protobuf/unittest_proto3_lite.pb.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/testing/googletest.h>
diff --git a/src/google/protobuf/reflection.h b/src/google/protobuf/reflection.h
index fcb9a435..5d0fc42b 100755..100644
--- a/src/google/protobuf/reflection.h
+++ b/src/google/protobuf/reflection.h
@@ -34,9 +34,6 @@
#define GOOGLE_PROTOBUF_REFLECTION_H__
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/message.h>
#include <google/protobuf/generated_enum_util.h>
@@ -63,7 +60,7 @@ MutableRepeatedFieldRef<T> Reflection::GetMutableRepeatedFieldRef(
// RepeatedFieldRef definition for non-message types.
template<typename T>
class RepeatedFieldRef<
- T, typename internal::enable_if<!internal::is_base_of<Message, T>::value>::type> {
+ T, typename std::enable_if<!std::is_base_of<Message, T>::value>::type> {
typedef typename internal::RefTypeTraits<T>::iterator IteratorType;
typedef typename internal::RefTypeTraits<T>::AccessorType AccessorType;
@@ -112,7 +109,7 @@ class RepeatedFieldRef<
// MutableRepeatedFieldRef definition for non-message types.
template<typename T>
class MutableRepeatedFieldRef<
- T, typename internal::enable_if<!internal::is_base_of<Message, T>::value>::type> {
+ T, typename std::enable_if<!std::is_base_of<Message, T>::value>::type> {
typedef typename internal::RefTypeTraits<T>::AccessorType AccessorType;
public:
@@ -177,7 +174,7 @@ class MutableRepeatedFieldRef<
// RepeatedFieldRef definition for message types.
template<typename T>
class RepeatedFieldRef<
- T, typename internal::enable_if<internal::is_base_of<Message, T>::value>::type> {
+ T, typename std::enable_if<std::is_base_of<Message, T>::value>::type> {
typedef typename internal::RefTypeTraits<T>::iterator IteratorType;
typedef typename internal::RefTypeTraits<T>::AccessorType AccessorType;
@@ -219,7 +216,7 @@ class RepeatedFieldRef<
}
iterator end() const {
// The end iterator must not be dereferenced, no need for scratch space.
- return iterator(data_, accessor_, false, NULL);
+ return iterator(data_, accessor_, false, nullptr);
}
private:
@@ -245,7 +242,7 @@ class RepeatedFieldRef<
// MutableRepeatedFieldRef definition for message types.
template<typename T>
class MutableRepeatedFieldRef<
- T, typename internal::enable_if<internal::is_base_of<Message, T>::value>::type> {
+ T, typename std::enable_if<std::is_base_of<Message, T>::value>::type> {
typedef typename internal::RefTypeTraits<T>::AccessorType AccessorType;
public:
@@ -447,7 +444,7 @@ class RepeatedFieldRefIterator
iterator_(begin ? accessor->BeginIterator(data)
: accessor->EndIterator(data)),
// The end iterator must not be dereferenced, no need for scratch space.
- scratch_space_(begin ? new AccessorValueType : NULL) {}
+ scratch_space_(begin ? new AccessorValueType : nullptr) {}
// Constructor for message fields.
RepeatedFieldRefIterator(const void* data,
const RepeatedFieldAccessor* accessor,
@@ -508,7 +505,7 @@ class RepeatedFieldRefIterator
const void* data_;
const RepeatedFieldAccessor* accessor_;
void* iterator_;
- google::protobuf::scoped_ptr<AccessorValueType> scratch_space_;
+ std::unique_ptr<AccessorValueType> scratch_space_;
};
// TypeTraits that maps the type parameter T of RepeatedFieldRef or
@@ -535,7 +532,7 @@ DEFINE_PRIMITIVE(BOOL, bool)
template<typename T>
struct RefTypeTraits<
- T, typename internal::enable_if<PrimitiveTraits<T>::is_primitive>::type> {
+ T, typename std::enable_if<PrimitiveTraits<T>::is_primitive>::type> {
typedef RepeatedFieldRefIterator<T> iterator;
typedef RepeatedFieldAccessor AccessorType;
typedef T AccessorValueType;
@@ -550,7 +547,7 @@ struct RefTypeTraits<
template<typename T>
struct RefTypeTraits<
- T, typename internal::enable_if<is_proto_enum<T>::value>::type> {
+ T, typename std::enable_if<is_proto_enum<T>::value>::type> {
typedef RepeatedFieldRefIterator<T> iterator;
typedef RepeatedFieldAccessor AccessorType;
// We use int32 for repeated enums in RepeatedFieldAccessor.
@@ -566,7 +563,7 @@ struct RefTypeTraits<
template<typename T>
struct RefTypeTraits<
- T, typename internal::enable_if< ::google::protobuf::internal::is_same<string, T>::value>::type> {
+ T, typename std::enable_if<std::is_same<string, T>::value>::type> {
typedef RepeatedFieldRefIterator<T> iterator;
typedef RepeatedFieldAccessor AccessorType;
typedef string AccessorValueType;
@@ -594,7 +591,7 @@ struct MessageDescriptorGetter<Message> {
template<typename T>
struct RefTypeTraits<
- T, typename internal::enable_if<internal::is_base_of<Message, T>::value>::type> {
+ T, typename std::enable_if<std::is_base_of<Message, T>::value>::type> {
typedef RepeatedFieldRefIterator<T> iterator;
typedef RepeatedFieldAccessor AccessorType;
typedef Message AccessorValueType;
diff --git a/src/google/protobuf/reflection_internal.h b/src/google/protobuf/reflection_internal.h
index fcb42471..840d611f 100644
--- a/src/google/protobuf/reflection_internal.h
+++ b/src/google/protobuf/reflection_internal.h
@@ -43,32 +43,32 @@ namespace internal {
// corresponding random-access methods.
class RandomAccessRepeatedFieldAccessor : public RepeatedFieldAccessor {
public:
- virtual ~RandomAccessRepeatedFieldAccessor() {}
+ virtual ~RandomAccessRepeatedFieldAccessor() override {}
- virtual Iterator* BeginIterator(const Field* data) const {
+ virtual Iterator* BeginIterator(const Field* data) const override {
return PositionToIterator(0);
}
- virtual Iterator* EndIterator(const Field* data) const {
+ virtual Iterator* EndIterator(const Field* data) const override {
return PositionToIterator(this->Size(data));
}
virtual Iterator* CopyIterator(const Field* data,
- const Iterator* iterator) const {
+ const Iterator* iterator) const override {
return const_cast<Iterator*>(iterator);
}
virtual Iterator* AdvanceIterator(const Field* data,
- Iterator* iterator) const {
+ Iterator* iterator) const override {
return PositionToIterator(IteratorToPosition(iterator) + 1);
}
virtual bool EqualsIterator(const Field* data,
- const Iterator* a,
- const Iterator* b) const {
+ const Iterator* a,
+ const Iterator* b) const override {
return a == b;
}
- virtual void DeleteIterator(const Field* data, Iterator* iterator) const {
+ virtual void DeleteIterator(const Field* data, Iterator* iterator) const override {
}
virtual const Value* GetIteratorValue(const Field* data,
- const Iterator* iterator,
- Value* scratch_space) const {
+ const Iterator* iterator,
+ Value* scratch_space) const override {
return Get(data, static_cast<int>(IteratorToPosition(iterator)),
scratch_space);
}
@@ -88,30 +88,30 @@ template<typename T>
class RepeatedFieldWrapper : public RandomAccessRepeatedFieldAccessor {
public:
RepeatedFieldWrapper() {}
- virtual ~RepeatedFieldWrapper() {}
- virtual bool IsEmpty(const Field* data) const {
+ virtual ~RepeatedFieldWrapper() override {}
+ virtual bool IsEmpty(const Field* data) const override {
return GetRepeatedField(data)->empty();
}
- virtual int Size(const Field* data) const {
+ virtual int Size(const Field* data) const override {
return GetRepeatedField(data)->size();
}
virtual const Value* Get(const Field* data, int index,
- Value* scratch_space) const {
+ Value* scratch_space) const override {
return ConvertFromT(GetRepeatedField(data)->Get(index), scratch_space);
}
- virtual void Clear(Field* data) const {
+ virtual void Clear(Field* data) const override {
MutableRepeatedField(data)->Clear();
}
- virtual void Set(Field* data, int index, const Value* value) const {
+ virtual 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 {
+ virtual void Add(Field* data, const Value* value) const override {
MutableRepeatedField(data)->Add(ConvertToT(value));
}
- virtual void RemoveLast(Field* data) const {
+ virtual void RemoveLast(Field* data) const override {
MutableRepeatedField(data)->RemoveLast();
}
- virtual void SwapElements(Field* data, int index1, int index2) const {
+ virtual void SwapElements(Field* data, int index1, int index2) const override {
MutableRepeatedField(data)->SwapElements(index1, index2);
}
@@ -144,31 +144,31 @@ class RepeatedPtrFieldWrapper : public RandomAccessRepeatedFieldAccessor {
public:
RepeatedPtrFieldWrapper() {}
virtual ~RepeatedPtrFieldWrapper() {}
- virtual bool IsEmpty(const Field* data) const {
+ virtual bool IsEmpty(const Field* data) const override {
return GetRepeatedField(data)->empty();
}
- virtual int Size(const Field* data) const {
+ virtual int Size(const Field* data) const override {
return GetRepeatedField(data)->size();
}
virtual const Value* Get(const Field* data, int index,
- Value* scratch_space) const {
+ Value* scratch_space) const override {
return ConvertFromT(GetRepeatedField(data)->Get(index), scratch_space);
}
- virtual void Clear(Field* data) const {
+ virtual void Clear(Field* data) const override {
MutableRepeatedField(data)->Clear();
}
- virtual void Set(Field* data, int index, const Value* value) const {
+ virtual 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 {
+ virtual 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 {
+ virtual void RemoveLast(Field* data) const override {
MutableRepeatedField(data)->RemoveLast();
}
- virtual void SwapElements(Field* data, int index1, int index2) const {
+ virtual void SwapElements(Field* data, int index1, int index2) const override {
MutableRepeatedField(data)->SwapElements(index1, index2);
}
@@ -205,38 +205,38 @@ class RepeatedPtrFieldWrapper : public RandomAccessRepeatedFieldAccessor {
class MapFieldAccessor : public RandomAccessRepeatedFieldAccessor {
public:
MapFieldAccessor() {}
- virtual ~MapFieldAccessor() {}
- virtual bool IsEmpty(const Field* data) const {
+ virtual ~MapFieldAccessor() override {}
+ virtual bool IsEmpty(const Field* data) const override {
return GetRepeatedField(data)->empty();
}
- virtual int Size(const Field* data) const {
+ virtual int Size(const Field* data) const override {
return GetRepeatedField(data)->size();
}
virtual const Value* Get(const Field* data, int index,
- Value* scratch_space) const {
+ Value* scratch_space) const override {
return ConvertFromEntry(GetRepeatedField(data)->Get(index), scratch_space);
}
- virtual void Clear(Field* data) const {
+ virtual void Clear(Field* data) const override {
MutableRepeatedField(data)->Clear();
}
- virtual void Set(Field* data, int index, const Value* value) const {
+ virtual 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 {
+ virtual 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 {
+ virtual void RemoveLast(Field* data) const override {
MutableRepeatedField(data)->RemoveLast();
}
- virtual void SwapElements(Field* data, int index1, int index2) const {
+ virtual 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 {
+ Field* other_data) const override {
GOOGLE_CHECK(this == other_mutator);
MutableRepeatedField(data)->Swap(MutableRepeatedField(other_data));
}
@@ -276,11 +276,11 @@ class RepeatedFieldPrimitiveAccessor : public RepeatedFieldWrapper<T> {
public:
RepeatedFieldPrimitiveAccessor() {}
- virtual ~RepeatedFieldPrimitiveAccessor() {}
+ virtual ~RepeatedFieldPrimitiveAccessor() override {}
virtual void Swap(
Field* data,
const internal::RepeatedFieldAccessor* other_mutator,
- Field* other_data) const {
+ 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,11 +289,11 @@ class RepeatedFieldPrimitiveAccessor : public RepeatedFieldWrapper<T> {
}
protected:
- virtual T ConvertToT(const Value* value) const {
+ virtual T ConvertToT(const Value* value) const override {
return *static_cast<const T*>(value);
}
virtual const Value* ConvertFromT(const T& value,
- Value* scratch_space) const {
+ Value* scratch_space) const override {
return static_cast<const Value*>(&value);
}
};
@@ -307,11 +307,11 @@ class RepeatedPtrFieldStringAccessor : public RepeatedPtrFieldWrapper<string> {
public:
RepeatedPtrFieldStringAccessor() {}
- virtual ~RepeatedPtrFieldStringAccessor() {}
+ virtual ~RepeatedPtrFieldStringAccessor() override {}
virtual void Swap(
Field* data,
const internal::RepeatedFieldAccessor* other_mutator,
- Field* other_data) const {
+ Field* other_data) const override {
if (this == other_mutator) {
MutableRepeatedField(data)->Swap(MutableRepeatedField(other_data));
} else {
@@ -330,14 +330,14 @@ class RepeatedPtrFieldStringAccessor : public RepeatedPtrFieldWrapper<string> {
}
protected:
- virtual string* New(const Value*) const {
+ virtual string* New(const Value*) const override {
return new string();
}
- virtual void ConvertToT(const Value* value, string* result) const {
+ virtual void ConvertToT(const Value* value, string* result) const override {
*result = *static_cast<const string*>(value);
}
virtual const Value* ConvertFromT(const string& value,
- Value* scratch_space) const {
+ Value* scratch_space) const override {
return static_cast<const Value*>(&value);
}
};
@@ -350,24 +350,24 @@ class RepeatedPtrFieldMessageAccessor
public:
RepeatedPtrFieldMessageAccessor() {}
- virtual ~RepeatedPtrFieldMessageAccessor() {}
+ virtual ~RepeatedPtrFieldMessageAccessor() override {}
virtual void Swap(
Field* data,
const internal::RepeatedFieldAccessor* other_mutator,
- Field* other_data) const {
+ Field* other_data) const override {
GOOGLE_CHECK(this == other_mutator);
MutableRepeatedField(data)->Swap(MutableRepeatedField(other_data));
}
protected:
- virtual Message* New(const Value* value) const {
+ virtual Message* New(const Value* value) const override {
return static_cast<const Message*>(value)->New();
}
- virtual void ConvertToT(const Value* value, Message* result) const {
+ virtual 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 {
+ Value* scratch_space) const override {
return static_cast<const Value*>(&value);
}
};
diff --git a/src/google/protobuf/reflection_ops.cc b/src/google/protobuf/reflection_ops.cc
index eb2a0e7a..3cd50340 100644
--- a/src/google/protobuf/reflection_ops.cc
+++ b/src/google/protobuf/reflection_ops.cc
@@ -50,10 +50,10 @@ namespace internal {
static const Reflection* GetReflectionOrDie(const Message& m) {
const Reflection* r = m.GetReflection();
- if (r == NULL) {
+ if (r == nullptr) {
const Descriptor* d = m.GetDescriptor();
const string& mtype = d ? d->name() : "unknown";
- // RawMessage is one known type for which GetReflection() returns NULL.
+ // RawMessage is one known type for which GetReflection() returns nullptr.
GOOGLE_LOG(FATAL) << "Message does not support reflection (type " << mtype << ").";
}
return r;
diff --git a/src/google/protobuf/repeated_field.h b/src/google/protobuf/repeated_field.h
index 5fc619f2..fbfbf942 100644
--- a/src/google/protobuf/repeated_field.h
+++ b/src/google/protobuf/repeated_field.h
@@ -61,6 +61,7 @@
#include <google/protobuf/implicit_weak_message.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/stubs/port.h>
+#include <type_traits>
// Forward-declare these so that we can make them friends.
@@ -108,7 +109,7 @@ inline int CalculateReserve(Iter begin, Iter end) {
// not ever use a RepeatedField directly; they will use the get-by-index,
// set-by-index, and add accessors that are generated for all repeated fields.
template <typename Element>
-class RepeatedField PROTOBUF_FINAL {
+class RepeatedField final {
public:
RepeatedField();
explicit RepeatedField(Arena* arena);
@@ -119,10 +120,8 @@ class RepeatedField PROTOBUF_FINAL {
RepeatedField& operator=(const RepeatedField& other);
-#if LANG_CXX11
RepeatedField(RepeatedField&& other) noexcept;
RepeatedField& operator=(RepeatedField&& other) noexcept;
-#endif
bool empty() const;
int size() const;
@@ -352,7 +351,7 @@ namespace internal {
// effectively.
template <typename Element,
bool HasTrivialCopy =
- has_trivial_copy<Element>::value>
+ std::is_pod<Element>::value>
struct ElementCopier {
void operator()(Element* to, const Element* from, int array_size);
};
@@ -386,8 +385,8 @@ struct TypeImplementsMergeBehaviorProbeForMergeFrom {
CheckType<U, bool, &U::MergeFrom>*);
template<typename U> static HasNoMerge Check(...);
- // Resolves to either google::protobuf::internal::true_type or google::protobuf::internal::false_type.
- typedef google::protobuf::internal::integral_constant<bool,
+ // Resolves to either std::true_type or std::false_type.
+ typedef std::integral_constant<bool,
(sizeof(Check<T>(0)) == sizeof(HasMerge))> type;
};
@@ -398,7 +397,7 @@ struct TypeImplementsMergeBehavior :
template <>
struct TypeImplementsMergeBehavior< ::std::string> {
- typedef google::protobuf::internal::true_type type;
+ typedef std::true_type type;
};
// This is the common base class for RepeatedPtrFields. It deals only in void*
@@ -465,11 +464,9 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
inline void InternalSwap(RepeatedPtrFieldBase* other);
protected:
-#if LANG_CXX11
template <typename TypeHandler>
void Add(typename TypeHandler::Type&& value,
- internal::enable_if<TypeHandler::Moveable>* dummy = NULL);
-#endif
+ std::enable_if<TypeHandler::Moveable>* dummy = NULL);
template <typename TypeHandler>
void RemoveLast();
@@ -532,9 +529,9 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
typename TypeHandler::Type* ReleaseCleared();
template <typename TypeHandler>
- void AddAllocatedInternal(typename TypeHandler::Type* value, google::protobuf::internal::true_type);
+ void AddAllocatedInternal(typename TypeHandler::Type* value, std::true_type);
template <typename TypeHandler>
- void AddAllocatedInternal(typename TypeHandler::Type* value, google::protobuf::internal::false_type);
+ void AddAllocatedInternal(typename TypeHandler::Type* value, std::false_type);
template <typename TypeHandler> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
void AddAllocatedSlowWithCopy(typename TypeHandler::Type* value,
@@ -544,9 +541,9 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
void AddAllocatedSlowWithoutCopy(typename TypeHandler::Type* value);
template <typename TypeHandler>
- typename TypeHandler::Type* ReleaseLastInternal(google::protobuf::internal::true_type);
+ typename TypeHandler::Type* ReleaseLastInternal(std::true_type);
template <typename TypeHandler>
- typename TypeHandler::Type* ReleaseLastInternal(google::protobuf::internal::false_type);
+ typename TypeHandler::Type* ReleaseLastInternal(std::false_type);
template<typename TypeHandler> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
void SwapFallback(RepeatedPtrFieldBase* other);
@@ -640,9 +637,7 @@ class GenericTypeHandler {
public:
typedef GenericType Type;
typedef GenericType WeakType;
-#if LANG_CXX11
static const bool Moveable = false;
-#endif
static inline GenericType* New(Arena* arena) {
return ::google::protobuf::Arena::CreateMaybeMessage<Type>(arena);
@@ -710,13 +705,13 @@ void GenericTypeHandler<string>::Merge(const string& from,
// 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<> \
+ template<> LIBPROTOBUF_EXPORT \
TypeName* GenericTypeHandler<TypeName>::NewFromPrototype( \
const TypeName* prototype, google::protobuf::Arena* arena); \
- template<> \
+ template<> LIBPROTOBUF_EXPORT \
google::protobuf::Arena* GenericTypeHandler<TypeName>::GetArena( \
TypeName* value); \
- template<> \
+ template<> LIBPROTOBUF_EXPORT \
void* GenericTypeHandler<TypeName>::GetMaybeArenaPointer( \
TypeName* value);
@@ -732,20 +727,15 @@ class StringTypeHandler {
public:
typedef string Type;
typedef string WeakType;
-#if LANG_CXX11
- static const bool Moveable =
- std::is_move_constructible<Type>::value &&
- std::is_move_assignable<Type>::value;
-#endif
+ 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);
}
-#if LANG_CXX11
static inline string* New(Arena* arena, string&& value) {
return Arena::Create<string>(arena, std::move(value));
}
-#endif
static inline string* NewFromPrototype(const string*,
::google::protobuf::Arena* arena) {
return New(arena);
@@ -773,7 +763,7 @@ class StringTypeHandler {
// RepeatedPtrField is like RepeatedField, but used for repeated strings or
// Messages.
template <typename Element>
-class RepeatedPtrField PROTOBUF_FINAL : private internal::RepeatedPtrFieldBase {
+class RepeatedPtrField final : private internal::RepeatedPtrFieldBase {
public:
RepeatedPtrField();
explicit RepeatedPtrField(::google::protobuf::Arena* arena);
@@ -785,10 +775,8 @@ class RepeatedPtrField PROTOBUF_FINAL : private internal::RepeatedPtrFieldBase {
RepeatedPtrField& operator=(const RepeatedPtrField& other);
-#if LANG_CXX11
RepeatedPtrField(RepeatedPtrField&& other) noexcept;
RepeatedPtrField& operator=(RepeatedPtrField&& other) noexcept;
-#endif
bool empty() const;
int size() const;
@@ -796,9 +784,7 @@ class RepeatedPtrField PROTOBUF_FINAL : private internal::RepeatedPtrFieldBase {
const Element& Get(int index) const;
Element* Mutable(int index);
Element* Add();
-#if LANG_CXX11
void Add(Element&& value);
-#endif
const Element& operator[](int index) const { return Get(index); }
Element& operator[](int index) { return *Mutable(index); }
@@ -928,7 +914,7 @@ class RepeatedPtrField PROTOBUF_FINAL : private internal::RepeatedPtrFieldBase {
// RepeatedPtrField<T> temp_field;
// temp_field.AddAllocated(new T);
// ... // Do something with temp_field
- // temp_field.ExtractSubrange(0, temp_field.size(), NULL);
+ // temp_field.ExtractSubrange(0, temp_field.size(), nullptr);
// 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. UnsafeArenaAddAllocated prevents this.
@@ -1027,9 +1013,9 @@ class RepeatedPtrField PROTOBUF_FINAL : private internal::RepeatedPtrFieldBase {
// MergeFrom()), so we must resolve this at compile time. ExtractSubrange()
// uses SFINAE to choose one of the below implementations.
void ExtractSubrangeInternal(int start, int num, Element** elements,
- google::protobuf::internal::true_type);
+ std::true_type);
void ExtractSubrangeInternal(int start, int num, Element** elements,
- google::protobuf::internal::false_type);
+ std::false_type);
friend class Arena;
friend class MessageLite;
@@ -1100,8 +1086,6 @@ RepeatedField<Element>::operator=(const RepeatedField& other) {
return *this;
}
-#if LANG_CXX11
-
template <typename Element>
inline RepeatedField<Element>::RepeatedField(RepeatedField&& other) noexcept
: RepeatedField() {
@@ -1129,8 +1113,6 @@ inline RepeatedField<Element>& RepeatedField<Element>::operator=(
return *this;
}
-#endif // LANG_CXX11
-
template <typename Element>
inline bool RepeatedField<Element>::empty() const {
return current_size_ == 0;
@@ -1556,11 +1538,10 @@ inline typename TypeHandler::Type* RepeatedPtrFieldBase::Add(
return result;
}
-#if LANG_CXX11
template <typename TypeHandler>
inline void RepeatedPtrFieldBase::Add(
typename TypeHandler::Type&& value,
- internal::enable_if<TypeHandler::Moveable>*) {
+ std::enable_if<TypeHandler::Moveable>*) {
if (rep_ != NULL && current_size_ < rep_->allocated_size) {
*cast<TypeHandler>(rep_->elements[current_size_++]) = std::move(value);
return;
@@ -1573,7 +1554,6 @@ inline void RepeatedPtrFieldBase::Add(
TypeHandler::New(arena_, std::move(value));
rep_->elements[current_size_++] = result;
}
-#endif
template <typename TypeHandler>
inline void RepeatedPtrFieldBase::RemoveLast() {
@@ -1716,7 +1696,7 @@ inline typename TypeHandler::Type* RepeatedPtrFieldBase::AddFromCleared() {
template <typename TypeHandler>
void RepeatedPtrFieldBase::AddAllocatedInternal(
typename TypeHandler::Type* value,
- google::protobuf::internal::true_type) {
+ std::true_type) {
Arena* element_arena = reinterpret_cast<Arena*>(
TypeHandler::GetMaybeArenaPointer(value));
Arena* arena = GetArenaNoVirtual();
@@ -1766,7 +1746,7 @@ void RepeatedPtrFieldBase::AddAllocatedSlowWithCopy(
template <typename TypeHandler>
void RepeatedPtrFieldBase::AddAllocatedInternal(
typename TypeHandler::Type* value,
- google::protobuf::internal::false_type) {
+ std::false_type) {
if (rep_ && rep_->allocated_size < total_size_) {
// Fast path: underlying arena representation (tagged pointer) is equal to
// our arena pointer, and we can add to array without resizing it (at least
@@ -1816,7 +1796,7 @@ void RepeatedPtrFieldBase::UnsafeArenaAddAllocated(
// ReleaseLast() for types that implement merge/copy behavior.
template <typename TypeHandler>
inline typename TypeHandler::Type*
-RepeatedPtrFieldBase::ReleaseLastInternal(google::protobuf::internal::true_type) {
+RepeatedPtrFieldBase::ReleaseLastInternal(std::true_type) {
// First, release an element.
typename TypeHandler::Type* result = UnsafeArenaReleaseLast<TypeHandler>();
// Now perform a copy if we're on an arena.
@@ -1837,7 +1817,7 @@ RepeatedPtrFieldBase::ReleaseLastInternal(google::protobuf::internal::true_type)
// case.
template <typename TypeHandler>
inline typename TypeHandler::Type*
-RepeatedPtrFieldBase::ReleaseLastInternal(google::protobuf::internal::false_type) {
+RepeatedPtrFieldBase::ReleaseLastInternal(std::false_type) {
GOOGLE_DCHECK(GetArenaNoVirtual() == NULL)
<< "ReleaseLast() called on a RepeatedPtrField that is on an arena, "
<< "with a type that does not implement MergeFrom. This is unsafe; "
@@ -1943,8 +1923,6 @@ inline RepeatedPtrField<Element>& RepeatedPtrField<Element>::operator=(
return *this;
}
-#if LANG_CXX11
-
template <typename Element>
inline RepeatedPtrField<Element>::RepeatedPtrField(
RepeatedPtrField&& other) noexcept
@@ -1973,8 +1951,6 @@ inline RepeatedPtrField<Element>& RepeatedPtrField<Element>::operator=(
return *this;
}
-#endif // LANG_CXX11
-
template <typename Element>
inline bool RepeatedPtrField<Element>::empty() const {
return RepeatedPtrFieldBase::empty();
@@ -2001,12 +1977,10 @@ inline Element* RepeatedPtrField<Element>::Add() {
return RepeatedPtrFieldBase::Add<TypeHandler>();
}
-#if LANG_CXX11
template <typename Element>
inline void RepeatedPtrField<Element>::Add(Element&& value) {
RepeatedPtrFieldBase::Add<TypeHandler>(std::move(value));
}
-#endif
template <typename Element>
inline void RepeatedPtrField<Element>::RemoveLast() {
@@ -2036,7 +2010,7 @@ inline void RepeatedPtrField<Element>::ExtractSubrange(
// behavior.
template <typename Element>
inline void RepeatedPtrField<Element>::ExtractSubrangeInternal(
- int start, int num, Element** elements, google::protobuf::internal::true_type) {
+ int start, int num, Element** elements, std::true_type) {
GOOGLE_DCHECK_GE(start, 0);
GOOGLE_DCHECK_GE(num, 0);
GOOGLE_DCHECK_LE(start + num, size());
@@ -2069,7 +2043,7 @@ inline void RepeatedPtrField<Element>::ExtractSubrangeInternal(
// behavior.
template<typename Element>
inline void RepeatedPtrField<Element>::ExtractSubrangeInternal(
- int start, int num, Element** elements, google::protobuf::internal::false_type) {
+ int start, int num, Element** elements, std::false_type) {
// This case is identical to UnsafeArenaExtractSubrange(). However, since
// ExtractSubrange() must return heap-allocated objects by contract, and we
// cannot fulfill this contract if we are an on arena, we must GOOGLE_DCHECK() that
@@ -2241,7 +2215,7 @@ class RepeatedPtrIterator
// Shadow the value_type in std::iterator<> because const_iterator::value_type
// needs to be T, not const T.
- typedef typename remove_const<Element>::type value_type;
+ typedef typename std::remove_const<Element>::type value_type;
// Let the compiler know that these are type names, so we don't have to
// write "typename" in front of them everywhere.
@@ -2259,7 +2233,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*>(NULL));
+ implicit_cast<Element*>(static_cast<OtherElement*>(nullptr));
}
}
@@ -2335,7 +2309,7 @@ class RepeatedPtrOverPtrsIterator
// Shadow the value_type in std::iterator<> because const_iterator::value_type
// needs to be T, not const T.
- typedef typename remove_const<Element>::type value_type;
+ typedef typename std::remove_const<Element>::type value_type;
// Let the compiler know that these are type names, so we don't have to
// write "typename" in front of them everywhere.
@@ -2520,12 +2494,10 @@ template<typename T> class RepeatedPtrFieldBackInsertIterator
*field_->Add() = *ptr_to_value;
return *this;
}
-#if LANG_CXX11
RepeatedPtrFieldBackInsertIterator<T>& operator=(T&& value) {
*field_->Add() = std::move(value);
return *this;
}
-#endif
RepeatedPtrFieldBackInsertIterator<T>& operator*() {
return *this;
}
@@ -2640,7 +2612,7 @@ AllocatedRepeatedPtrFieldBackInserter(
// RepeatedPtrField<T> temp_field;
// temp_field.AddAllocated(new T);
// ... // Do something with temp_field
-// temp_field.ExtractSubrange(0, temp_field.size(), NULL);
+// temp_field.ExtractSubrange(0, temp_field.size(), nullptr);
// 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.
diff --git a/src/google/protobuf/repeated_field_reflection_unittest.cc b/src/google/protobuf/repeated_field_reflection_unittest.cc
index fd466565..74ec83b0 100644
--- a/src/google/protobuf/repeated_field_reflection_unittest.cc
+++ b/src/google/protobuf/repeated_field_reflection_unittest.cc
@@ -704,7 +704,7 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefDynamicMessage) {
desc->FindFieldByName("repeated_int32");
DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<Message> dynamic_message(factory.GetPrototype(desc)->New());
+ std::unique_ptr<Message> dynamic_message(factory.GetPrototype(desc)->New());
const Reflection* refl = dynamic_message->GetReflection();
MutableRepeatedFieldRef<int32> rf_int32 =
diff --git a/src/google/protobuf/repeated_field_unittest.cc b/src/google/protobuf/repeated_field_unittest.cc
index 16919711..053a4d68 100644
--- a/src/google/protobuf/repeated_field_unittest.cc
+++ b/src/google/protobuf/repeated_field_unittest.cc
@@ -383,8 +383,6 @@ TEST(RepeatedField, SelfAssign) {
EXPECT_EQ(8, source.Get(1));
}
-#if LANG_CXX11
-
TEST(RepeatedField, MoveConstruct) {
{
RepeatedField<int> source;
@@ -405,7 +403,7 @@ TEST(RepeatedField, MoveConstruct) {
source->Add(1);
source->Add(2);
RepeatedField<int> destination = std::move(*source);
- EXPECT_EQ(NULL, destination.GetArena());
+ EXPECT_EQ(nullptr, destination.GetArena());
EXPECT_THAT(destination, ElementsAre(1, 2));
// This property isn't guaranteed but it's useful to have a test that would
// catch changes in this area.
@@ -517,8 +515,6 @@ TEST(RepeatedField, MoveAssign) {
}
}
-#endif // LANG_CXX11
-
TEST(RepeatedField, MutableDataIsMutable) {
RepeatedField<int> field;
field.Add(1);
@@ -1045,8 +1041,6 @@ TEST(RepeatedPtrField, SelfAssign) {
EXPECT_EQ("8", source.Get(1));
}
-#if LANG_CXX11
-
TEST(RepeatedPtrField, MoveConstruct) {
{
RepeatedPtrField<string> source;
@@ -1067,7 +1061,7 @@ TEST(RepeatedPtrField, MoveConstruct) {
*source->Add() = "1";
*source->Add() = "2";
RepeatedPtrField<string> destination = std::move(*source);
- EXPECT_EQ(NULL, destination.GetArena());
+ EXPECT_EQ(nullptr, destination.GetArena());
EXPECT_THAT(destination, ElementsAre("1", "2"));
// This property isn't guaranteed but it's useful to have a test that would
// catch changes in this area.
@@ -1179,8 +1173,6 @@ TEST(RepeatedPtrField, MoveAssign) {
}
}
-#endif // LANG_CXX11
-
TEST(RepeatedPtrField, MutableDataIsMutable) {
RepeatedPtrField<string> field;
*field.Add() = "1";
@@ -1844,7 +1836,6 @@ TEST_F(RepeatedFieldInsertionIteratorsTest,
EXPECT_EQ(testproto.DebugString(), goldenproto.DebugString());
}
-#if LANG_CXX11
TEST_F(RepeatedFieldInsertionIteratorsTest, MoveStrings) {
std::vector<string> src = {"a", "b", "c", "d"};
std::vector<string> copy = src; // copy since move leaves in undefined state
@@ -1874,7 +1865,6 @@ TEST_F(RepeatedFieldInsertionIteratorsTest, MoveProtos) {
testproto.repeated_nested_message(i).DebugString());
}
}
-#endif
} // namespace
diff --git a/src/google/protobuf/source_context.pb.cc b/src/google/protobuf/source_context.pb.cc
index b9d8f3cb..af93e6b2 100644
--- a/src/google/protobuf/source_context.pb.cc
+++ b/src/google/protobuf/source_context.pb.cc
@@ -7,7 +7,6 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
@@ -19,6 +18,7 @@
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
+
namespace google {
namespace protobuf {
class SourceContextDefaultTypeInternal {
@@ -29,14 +29,9 @@ class SourceContextDefaultTypeInternal {
} // namespace protobuf
} // namespace google
namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto {
-void InitDefaultsSourceContextImpl() {
+static void InitDefaultsSourceContext() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_SourceContext_default_instance_;
new (ptr) ::google::protobuf::SourceContext();
@@ -45,9 +40,11 @@ void InitDefaultsSourceContextImpl() {
::google::protobuf::SourceContext::InitAsDefaultInstance();
}
-void InitDefaultsSourceContext() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSourceContextImpl);
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsSourceContext}, {}};
+
+void InitDefaults() {
+ ::google::protobuf::internal::InitSCC(&scc_info_SourceContext.base);
}
::google::protobuf::Metadata file_level_metadata[1];
@@ -68,17 +65,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_SourceContext_default_instance_),
};
-void protobuf_AssignDescriptors() {
+static void protobuf_AssignDescriptors() {
AddDescriptors();
- ::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/source_context.proto", schemas, file_default_instances, TableStruct::offsets, factory,
+ "google/protobuf/source_context.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
-void protobuf_AssignDescriptorsOnce() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
+static 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;
@@ -87,7 +83,7 @@ void protobuf_RegisterTypes(const ::std::string&) {
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
-void AddDescriptorsImpl() {
+static void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n$google/protobuf/source_context.proto\022\017"
@@ -105,8 +101,8 @@ void AddDescriptorsImpl() {
}
void AddDescriptors() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
+ 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 {
@@ -128,16 +124,14 @@ const int SourceContext::kFileNameFieldNumber;
SourceContext::SourceContext()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.SourceContext)
}
SourceContext::SourceContext(const SourceContext& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
file_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.file_name().size() > 0) {
@@ -148,7 +142,6 @@ SourceContext::SourceContext(const SourceContext& from)
void SourceContext::SharedCtor() {
file_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- _cached_size_ = 0;
}
SourceContext::~SourceContext() {
@@ -161,9 +154,7 @@ void SourceContext::SharedDtor() {
}
void SourceContext::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* SourceContext::descriptor() {
::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::protobuf_AssignDescriptorsOnce();
@@ -171,7 +162,7 @@ const ::google::protobuf::Descriptor* SourceContext::descriptor() {
}
const SourceContext& SourceContext::default_instance() {
- ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base);
return *internal_default_instance();
}
@@ -192,7 +183,7 @@ bool SourceContext::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.SourceContext)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -298,9 +289,7 @@ size_t SourceContext::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -356,9 +345,9 @@ void SourceContext::Swap(SourceContext* other) {
}
void SourceContext::InternalSwap(SourceContext* other) {
using std::swap;
- file_name_.Swap(&other->file_name_);
+ file_name_.Swap(&other->file_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata SourceContext::GetMetadata() const {
@@ -372,7 +361,7 @@ void SourceContext::InternalSwap(SourceContext* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceContext* Arena::Create< ::google::protobuf::SourceContext >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceContext* Arena::CreateMaybeMessage< ::google::protobuf::SourceContext >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::SourceContext >(arena);
}
} // namespace protobuf
diff --git a/src/google/protobuf/source_context.pb.h b/src/google/protobuf/source_context.pb.h
index 81893b1a..eee1b73f 100644
--- a/src/google/protobuf/source_context.pb.h
+++ b/src/google/protobuf/source_context.pb.h
@@ -1,19 +1,19 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/source_context.proto
-#ifndef PROTOBUF_google_2fprotobuf_2fsource_5fcontext_2eproto_INCLUDED
-#define PROTOBUF_google_2fprotobuf_2fsource_5fcontext_2eproto_INCLUDED
+#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto
+#define PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3005000
+#if GOOGLE_PROTOBUF_VERSION < 3006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3005001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -24,12 +24,14 @@
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
+#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto LIBPROTOBUF_EXPORT
namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto {
// Internal implementation detail -- do not use these members.
@@ -42,11 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::uint32 offsets[];
};
void LIBPROTOBUF_EXPORT AddDescriptors();
-void LIBPROTOBUF_EXPORT InitDefaultsSourceContextImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsSourceContext();
-inline void LIBPROTOBUF_EXPORT InitDefaults() {
- InitDefaultsSourceContext();
-}
} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto
namespace google {
namespace protobuf {
@@ -57,7 +54,7 @@ LIBPROTOBUF_EXPORT extern SourceContextDefaultTypeInternal _SourceContext_defaul
} // namespace google
namespace google {
namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceContext* Arena::Create< ::google::protobuf::SourceContext>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceContext* Arena::CreateMaybeMessage<::google::protobuf::SourceContext>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -99,7 +96,7 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
return reinterpret_cast<const SourceContext*>(
&_SourceContext_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
0;
void Swap(SourceContext* other);
@@ -109,32 +106,33 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
// implements Message ----------------------------------------------
- inline SourceContext* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<SourceContext>(NULL);
+ inline SourceContext* New() const final {
+ return CreateMaybeMessage<SourceContext>(NULL);
}
- SourceContext* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::Create<SourceContext>(arena);
+ SourceContext* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<SourceContext>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const SourceContext& from);
void MergeFrom(const SourceContext& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(SourceContext* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
@@ -145,7 +143,7 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -170,9 +168,8 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::ArenaStringPtr file_name_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContextImpl();
};
// ===================================================================
@@ -249,4 +246,4 @@ inline void SourceContext::set_allocated_file_name(::std::string* file_name) {
// @@protoc_insertion_point(global_scope)
-#endif // PROTOBUF_google_2fprotobuf_2fsource_5fcontext_2eproto_INCLUDED
+#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 309a4d2d..ead81689 100644
--- a/src/google/protobuf/struct.pb.cc
+++ b/src/google/protobuf/struct.pb.cc
@@ -7,7 +7,6 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
@@ -19,6 +18,10 @@
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
+
+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
namespace google {
namespace protobuf {
class Struct_FieldsEntry_DoNotUseDefaultTypeInternal {
@@ -50,14 +53,9 @@ class ListValueDefaultTypeInternal {
} // namespace protobuf
} // namespace google
namespace protobuf_google_2fprotobuf_2fstruct_2eproto {
-void InitDefaultsListValueImpl() {
+static void InitDefaultsListValue() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_Struct_FieldsEntry_DoNotUse_default_instance_;
new (ptr) ::google::protobuf::Struct_FieldsEntry_DoNotUse();
@@ -83,9 +81,11 @@ void InitDefaultsListValueImpl() {
::google::protobuf::ListValue::InitAsDefaultInstance();
}
-void InitDefaultsListValue() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsListValueImpl);
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_ListValue =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsListValue}, {}};
+
+void InitDefaults() {
+ ::google::protobuf::internal::InitSCC(&scc_info_ListValue.base);
}
::google::protobuf::Metadata file_level_metadata[4];
@@ -140,17 +140,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_ListValue_default_instance_),
};
-void protobuf_AssignDescriptors() {
+static void protobuf_AssignDescriptors() {
AddDescriptors();
- ::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/struct.proto", schemas, file_default_instances, TableStruct::offsets, factory,
+ "google/protobuf/struct.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, file_level_enum_descriptors, NULL);
}
-void protobuf_AssignDescriptorsOnce() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
+static 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;
@@ -159,7 +158,7 @@ void protobuf_RegisterTypes(const ::std::string&) {
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 4);
}
-void AddDescriptorsImpl() {
+static void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\034google/protobuf/struct.proto\022\017google.p"
@@ -187,8 +186,8 @@ void AddDescriptorsImpl() {
}
void AddDescriptors() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
+ 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 {
@@ -240,9 +239,8 @@ const int Struct::kFieldsFieldNumber;
Struct::Struct()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Struct)
}
@@ -250,22 +248,20 @@ Struct::Struct(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
fields_(arena) {
- ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Struct)
}
Struct::Struct(const Struct& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
fields_.MergeFrom(from.fields_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Struct)
}
void Struct::SharedCtor() {
- _cached_size_ = 0;
}
Struct::~Struct() {
@@ -281,12 +277,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Struct::descriptor() {
::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
@@ -294,7 +288,7 @@ const ::google::protobuf::Descriptor* Struct::descriptor() {
}
const Struct& Struct::default_instance() {
- ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
return *internal_default_instance();
}
@@ -315,7 +309,7 @@ bool Struct::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Struct)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -385,7 +379,7 @@ void Struct::SerializeWithCachedSizes(
if (output->IsSerializationDeterministic() &&
this->fields().size() > 1) {
- ::google::protobuf::scoped_array<SortItem> items(
+ ::std::unique_ptr<SortItem[]> items(
new SortItem[this->fields().size()]);
typedef ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::size_type size_type;
size_type n = 0;
@@ -395,7 +389,7 @@ void Struct::SerializeWithCachedSizes(
items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);
}
::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());
- ::google::protobuf::scoped_ptr<Struct_FieldsEntry_DoNotUse> entry;
+ ::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));
@@ -407,7 +401,7 @@ void Struct::SerializeWithCachedSizes(
Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]);
}
} else {
- ::google::protobuf::scoped_ptr<Struct_FieldsEntry_DoNotUse> entry;
+ ::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) {
@@ -454,7 +448,7 @@ void Struct::SerializeWithCachedSizes(
if (deterministic &&
this->fields().size() > 1) {
- ::google::protobuf::scoped_array<SortItem> items(
+ ::std::unique_ptr<SortItem[]> items(
new SortItem[this->fields().size()]);
typedef ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::size_type size_type;
size_type n = 0;
@@ -464,7 +458,7 @@ void Struct::SerializeWithCachedSizes(
items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);
}
::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());
- ::google::protobuf::scoped_ptr<Struct_FieldsEntry_DoNotUse> entry;
+ ::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));
@@ -478,7 +472,7 @@ void Struct::SerializeWithCachedSizes(
Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]);
}
} else {
- ::google::protobuf::scoped_ptr<Struct_FieldsEntry_DoNotUse> entry;
+ ::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) {
@@ -517,7 +511,7 @@ size_t Struct::ByteSizeLong() const {
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->fields_size());
{
- ::google::protobuf::scoped_ptr<Struct_FieldsEntry_DoNotUse> entry;
+ ::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) {
@@ -534,9 +528,7 @@ size_t Struct::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -606,7 +598,6 @@ void Struct::InternalSwap(Struct* other) {
using std::swap;
fields_.Swap(&other->fields_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Struct::GetMetadata() const {
@@ -669,24 +660,22 @@ const int Value::kListValueFieldNumber;
Value::Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Value)
}
Value::Value(const Value& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
clear_has_kind();
switch (from.kind_case()) {
@@ -723,7 +712,6 @@ Value::Value(const Value& from)
void Value::SharedCtor() {
clear_has_kind();
- _cached_size_ = 0;
}
Value::~Value() {
@@ -742,12 +730,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Value::descriptor() {
::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
@@ -755,7 +741,7 @@ const ::google::protobuf::Descriptor* Value::descriptor() {
}
const Value& Value::default_instance() {
- ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
return *internal_default_instance();
}
@@ -816,7 +802,7 @@ bool Value::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Value)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -824,7 +810,7 @@ bool Value::MergePartialFromCodedStream(
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
- int value;
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -960,13 +946,13 @@ void Value::SerializeWithCachedSizes(
// .google.protobuf.Struct struct_value = 5;
if (has_struct_value()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 5, *kind_.struct_value_, output);
+ 5, this->_internal_struct_value(), output);
}
// .google.protobuf.ListValue list_value = 6;
if (has_list_value()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 6, *kind_.list_value_, output);
+ 6, this->_internal_list_value(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
@@ -1014,14 +1000,14 @@ void Value::SerializeWithCachedSizes(
if (has_struct_value()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 5, *kind_.struct_value_, deterministic, target);
+ 5, this->_internal_struct_value(), deterministic, target);
}
// .google.protobuf.ListValue list_value = 6;
if (has_list_value()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 6, *kind_.list_value_, deterministic, target);
+ 6, this->_internal_list_value(), deterministic, target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
@@ -1084,9 +1070,7 @@ size_t Value::ByteSizeLong() const {
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -1185,7 +1169,6 @@ void Value::InternalSwap(Value* other) {
swap(kind_, other->kind_);
swap(_oneof_case_[0], other->_oneof_case_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Value::GetMetadata() const {
@@ -1204,9 +1187,8 @@ const int ListValue::kValuesFieldNumber;
ListValue::ListValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.ListValue)
}
@@ -1214,7 +1196,7 @@ ListValue::ListValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
values_(arena) {
- ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.ListValue)
@@ -1222,14 +1204,12 @@ ListValue::ListValue(::google::protobuf::Arena* arena)
ListValue::ListValue(const ListValue& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- values_(from.values_),
- _cached_size_(0) {
+ values_(from.values_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.ListValue)
}
void ListValue::SharedCtor() {
- _cached_size_ = 0;
}
ListValue::~ListValue() {
@@ -1245,12 +1225,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* ListValue::descriptor() {
::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
@@ -1258,7 +1236,7 @@ const ::google::protobuf::Descriptor* ListValue::descriptor() {
}
const ListValue& ListValue::default_instance() {
- ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
return *internal_default_instance();
}
@@ -1279,7 +1257,7 @@ bool ListValue::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.ListValue)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -1381,9 +1359,7 @@ size_t ListValue::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -1453,7 +1429,6 @@ void ListValue::InternalSwap(ListValue* other) {
using std::swap;
CastToBase(&values_)->InternalSwap(CastToBase(&other->values_));
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata ListValue::GetMetadata() const {
@@ -1467,16 +1442,16 @@ void ListValue::InternalSwap(ListValue* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMessage< ::google::protobuf::Struct_FieldsEntry_DoNotUse >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::Struct >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::Value >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::ListValue >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ListValue* Arena::CreateMaybeMessage< ::google::protobuf::ListValue >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::ListValue >(arena);
}
} // namespace protobuf
diff --git a/src/google/protobuf/struct.pb.h b/src/google/protobuf/struct.pb.h
index 91aa3cf2..b2263435 100644
--- a/src/google/protobuf/struct.pb.h
+++ b/src/google/protobuf/struct.pb.h
@@ -1,19 +1,19 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/struct.proto
-#ifndef PROTOBUF_google_2fprotobuf_2fstruct_2eproto_INCLUDED
-#define PROTOBUF_google_2fprotobuf_2fstruct_2eproto_INCLUDED
+#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto
+#define PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3005000
+#if GOOGLE_PROTOBUF_VERSION < 3006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3005001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -24,6 +24,7 @@
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -34,6 +35,7 @@
#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
namespace protobuf_google_2fprotobuf_2fstruct_2eproto {
// Internal implementation detail -- do not use these members.
@@ -46,11 +48,6 @@ struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::uint32 offsets[];
};
void LIBPROTOBUF_EXPORT AddDescriptors();
-void LIBPROTOBUF_EXPORT InitDefaultsListValueImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsListValue();
-inline void LIBPROTOBUF_EXPORT InitDefaults() {
- InitDefaultsListValue();
-}
} // namespace protobuf_google_2fprotobuf_2fstruct_2eproto
namespace google {
namespace protobuf {
@@ -70,10 +67,10 @@ LIBPROTOBUF_EXPORT extern ValueDefaultTypeInternal _Value_default_instance_;
} // namespace google
namespace google {
namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::ListValue* Arena::CreateMessage< ::google::protobuf::ListValue>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct* Arena::CreateMessage< ::google::protobuf::Struct>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMessage< ::google::protobuf::Struct_FieldsEntry_DoNotUse>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Value* Arena::CreateMessage< ::google::protobuf::Value>(Arena*);
+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*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -116,7 +113,7 @@ public:
Struct_FieldsEntry_DoNotUse(::google::protobuf::Arena* arena);
void MergeFrom(const Struct_FieldsEntry_DoNotUse& other);
static const Struct_FieldsEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const Struct_FieldsEntry_DoNotUse*>(&_Struct_FieldsEntry_DoNotUse_default_instance_); }
- void MergeFrom(const ::google::protobuf::Message& other) PROTOBUF_FINAL;
+ void MergeFrom(const ::google::protobuf::Message& other) final;
::google::protobuf::Metadata GetMetadata() const;
};
@@ -148,10 +145,10 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -162,7 +159,7 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
return reinterpret_cast<const Struct*>(
&_Struct_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
1;
void UnsafeArenaSwap(Struct* other);
@@ -173,32 +170,33 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
// implements Message ----------------------------------------------
- inline Struct* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Struct>(NULL);
+ inline Struct* New() const final {
+ return CreateMaybeMessage<Struct>(NULL);
}
- Struct* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Struct>(arena);
+ Struct* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Struct>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Struct& from);
void MergeFrom(const Struct& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Struct* other);
protected:
explicit Struct(::google::protobuf::Arena* arena);
@@ -214,7 +212,7 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -243,9 +241,8 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0 > fields_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValueImpl();
};
// -------------------------------------------------------------------
@@ -275,10 +272,10 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -299,7 +296,7 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
return reinterpret_cast<const Value*>(
&_Value_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
2;
void UnsafeArenaSwap(Value* other);
@@ -310,32 +307,33 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
// implements Message ----------------------------------------------
- inline Value* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Value>(NULL);
+ inline Value* New() const final {
+ return CreateMaybeMessage<Value>(NULL);
}
- Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Value>(arena);
+ Value* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Value>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Value& from);
void MergeFrom(const Value& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Value* other);
protected:
explicit Value(::google::protobuf::Arena* arena);
@@ -351,7 +349,7 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -414,6 +412,9 @@ 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();
@@ -426,6 +427,9 @@ 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();
@@ -434,6 +438,7 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::ListValue* list_value);
::google::protobuf::ListValue* unsafe_arena_release_list_value();
+ void clear_kind();
KindCase kind_case() const;
// @@protoc_insertion_point(class_scope:google.protobuf.Value)
private:
@@ -445,7 +450,6 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
void set_has_list_value();
inline bool has_kind() const;
- void clear_kind();
inline void clear_has_kind();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
@@ -461,11 +465,10 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::Struct* struct_value_;
::google::protobuf::ListValue* list_value_;
} kind_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::uint32 _oneof_case_[1];
friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValueImpl();
};
// -------------------------------------------------------------------
@@ -495,10 +498,10 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -509,7 +512,7 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
return reinterpret_cast<const ListValue*>(
&_ListValue_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
3;
void UnsafeArenaSwap(ListValue* other);
@@ -520,32 +523,33 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
// implements Message ----------------------------------------------
- inline ListValue* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<ListValue>(NULL);
+ inline ListValue* New() const final {
+ return CreateMaybeMessage<ListValue>(NULL);
}
- ListValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<ListValue>(arena);
+ ListValue* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<ListValue>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const ListValue& from);
void MergeFrom(const ListValue& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(ListValue* other);
protected:
explicit ListValue(::google::protobuf::Arena* arena);
@@ -561,7 +565,7 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -587,9 +591,8 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Value > values_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValueImpl();
};
// ===================================================================
@@ -852,13 +855,16 @@ 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()) {
clear_has_kind();
::google::protobuf::Struct* temp = kind_.struct_value_;
if (GetArenaNoVirtual() != NULL) {
- temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
kind_.struct_value_ = NULL;
return temp;
@@ -895,7 +901,7 @@ inline ::google::protobuf::Struct* Value::mutable_struct_value() {
if (!has_struct_value()) {
clear_kind();
set_has_struct_value();
- kind_.struct_value_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::Struct >(
+ kind_.struct_value_ = CreateMaybeMessage< ::google::protobuf::Struct >(
GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Value.struct_value)
@@ -917,13 +923,16 @@ 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()) {
clear_has_kind();
::google::protobuf::ListValue* temp = kind_.list_value_;
if (GetArenaNoVirtual() != NULL) {
- temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
kind_.list_value_ = NULL;
return temp;
@@ -960,7 +969,7 @@ inline ::google::protobuf::ListValue* Value::mutable_list_value() {
if (!has_list_value()) {
clear_kind();
set_has_list_value();
- kind_.list_value_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ListValue >(
+ kind_.list_value_ = CreateMaybeMessage< ::google::protobuf::ListValue >(
GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Value.list_value)
@@ -1028,7 +1037,7 @@ ListValue::values() const {
namespace google {
namespace protobuf {
-template <> struct is_proto_enum< ::google::protobuf::NullValue> : ::google::protobuf::internal::true_type {};
+template <> struct is_proto_enum< ::google::protobuf::NullValue> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::NullValue>() {
return ::google::protobuf::NullValue_descriptor();
@@ -1039,4 +1048,4 @@ inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::NullValue>()
// @@protoc_insertion_point(global_scope)
-#endif // PROTOBUF_google_2fprotobuf_2fstruct_2eproto_INCLUDED
+#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto
diff --git a/src/google/protobuf/stubs/atomic_sequence_num.h b/src/google/protobuf/stubs/atomic_sequence_num.h
deleted file mode 100644
index bb20942f..00000000
--- a/src/google/protobuf/stubs/atomic_sequence_num.h
+++ /dev/null
@@ -1,54 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2014 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_ATOMIC_SEQUENCE_NUM_H_
-#define GOOGLE_PROTOBUF_ATOMIC_SEQUENCE_NUM_H_
-
-#include <google/protobuf/stubs/atomicops.h>
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-class SequenceNumber {
- public:
- SequenceNumber() : word_(0) {}
-
- AtomicWord GetNext() {
- return NoBarrier_AtomicIncrement(&word_, 1) - 1;
- }
- private:
- AtomicWord word_;
-};
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#endif // GOOGLE_PROTOBUF_ATOMIC_SEQUENCE_NUM_H_
diff --git a/src/google/protobuf/stubs/atomicops.h b/src/google/protobuf/stubs/atomicops.h
deleted file mode 100644
index cb4553b1..00000000
--- a/src/google/protobuf/stubs/atomicops.h
+++ /dev/null
@@ -1,237 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2012 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// The routines exported by this module are subtle. If you use them, even if
-// you get the code right, it will depend on careful reasoning about atomicity
-// and memory ordering; it will be less readable, and harder to maintain. If
-// you plan to use these routines, you should have a good reason, such as solid
-// evidence that performance would otherwise suffer, or there being no
-// alternative. You should assume only properties explicitly guaranteed by the
-// specifications in this file. You are almost certainly _not_ writing code
-// just for the x86; if you assume x86 semantics, x86 hardware bugs and
-// implementations on other archtectures will cause your code to break. If you
-// do not know what you are doing, avoid these routines, and use a Mutex.
-//
-// It is incorrect to make direct assignments to/from an atomic variable.
-// You should use one of the Load or Store routines. The NoBarrier
-// versions are provided when no barriers are needed:
-// NoBarrier_Store()
-// NoBarrier_Load()
-// Although there are currently no compiler enforcement, you are encouraged
-// to use these.
-
-// This header and the implementations for each platform (located in
-// atomicops_internals_*) must be kept in sync with the upstream code (V8).
-
-#ifndef GOOGLE_PROTOBUF_ATOMICOPS_H_
-#define GOOGLE_PROTOBUF_ATOMICOPS_H_
-
-// Don't include this file for people not concerned about thread safety.
-#ifndef GOOGLE_PROTOBUF_NO_THREAD_SAFETY
-
-#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/platform_macros.h>
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-#ifdef GOOGLE_PROTOBUF_ARCH_32_BIT
- typedef intptr_t Atomic32;
- typedef int64 Atomic64;
-#else
- // We need to be able to go between Atomic64 and AtomicWord implicitly. This
- // means Atomic64 and AtomicWord should be the same type on 64-bit.
- #if defined(__ILP32__) || defined(GOOGLE_PROTOBUF_OS_NACL)
- // NaCl's intptr_t is not actually 64-bits on 64-bit!
- // http://code.google.com/p/nativeclient/issues/detail?id=1162
- // sparcv9's pointer type is 32bits
- typedef intptr_t Atomic32;
- typedef int64 Atomic64;
- #else
- typedef int32 Atomic32;
- typedef intptr_t Atomic64;
- #endif
-#endif
-
-// Use AtomicWord for a machine-sized pointer. It will use the Atomic32 or
-// Atomic64 routines below, depending on your architecture.
-typedef intptr_t AtomicWord;
-
-// Atomically execute:
-// result = *ptr;
-// if (*ptr == old_value)
-// *ptr = new_value;
-// return result;
-//
-// I.e., replace "*ptr" with "new_value" if "*ptr" used to be "old_value".
-// Always return the old value of "*ptr"
-//
-// This routine implies no memory barriers.
-Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value);
-
-// Atomically store new_value into *ptr, returning the previous value held in
-// *ptr. This routine implies no memory barriers.
-Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, Atomic32 new_value);
-
-// Atomically increment *ptr by "increment". Returns the new value of
-// *ptr with the increment applied. This routine implies no memory barriers.
-Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment);
-
-Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment);
-
-// These following lower-level operations are typically useful only to people
-// implementing higher-level synchronization operations like spinlocks,
-// mutexes, and condition-variables. They combine CompareAndSwap(), a load, or
-// a store with appropriate memory-ordering instructions. "Acquire" operations
-// ensure that no later memory access can be reordered ahead of the operation.
-// "Release" operations ensure that no previous memory access can be reordered
-// after the operation. "Barrier" operations have both "Acquire" and "Release"
-// semantics. A MemoryBarrierInternal() has "Barrier" semantics, but does no
-// memory access.
-Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value);
-Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value);
-
-// This function was renamed from MemoryBarrier to MemoryBarrierInternal
-// because MemoryBarrier is a define in Windows ARM builds and we do not
-// undefine it because we call it from this function.
-void MemoryBarrierInternal();
-void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value);
-void Acquire_Store(volatile Atomic32* ptr, Atomic32 value);
-void Release_Store(volatile Atomic32* ptr, Atomic32 value);
-
-Atomic32 NoBarrier_Load(volatile const Atomic32* ptr);
-Atomic32 Acquire_Load(volatile const Atomic32* ptr);
-Atomic32 Release_Load(volatile const Atomic32* ptr);
-
-// 64-bit atomic operations (only available on 64-bit processors).
-#ifdef GOOGLE_PROTOBUF_ARCH_64_BIT
-Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value);
-Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, Atomic64 new_value);
-Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment);
-Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment);
-
-Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value);
-Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value);
-void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value);
-void Acquire_Store(volatile Atomic64* ptr, Atomic64 value);
-void Release_Store(volatile Atomic64* ptr, Atomic64 value);
-Atomic64 NoBarrier_Load(volatile const Atomic64* ptr);
-Atomic64 Acquire_Load(volatile const Atomic64* ptr);
-Atomic64 Release_Load(volatile const Atomic64* ptr);
-#endif // GOOGLE_PROTOBUF_ARCH_64_BIT
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-// Include our platform specific implementation.
-#define GOOGLE_PROTOBUF_ATOMICOPS_ERROR \
-"Atomic operations are not supported on your platform"
-
-// ThreadSanitizer, http://clang.llvm.org/docs/ThreadSanitizer.html.
-#if defined(THREAD_SANITIZER)
-#include <google/protobuf/stubs/atomicops_internals_tsan.h>
-// MSVC.
-#elif defined(_MSC_VER)
-#if defined(GOOGLE_PROTOBUF_ARCH_IA32) || defined(GOOGLE_PROTOBUF_ARCH_X64) || defined(GOOGLE_PROTOBUF_ARCH_ARM)
-#include <google/protobuf/stubs/atomicops_internals_x86_msvc.h>
-#else
-#error GOOGLE_PROTOBUF_ATOMICOPS_ERROR
-#endif
-
-// Solaris
-#elif defined(GOOGLE_PROTOBUF_OS_SOLARIS)
-#include <google/protobuf/stubs/atomicops_internals_solaris.h>
-
-// AIX
-#elif defined(GOOGLE_PROTOBUF_OS_AIX)
-#include <google/protobuf/stubs/atomicops_internals_power.h>
-
-// GCC.
-#elif defined(__GNUC__)
-#if defined(GOOGLE_PROTOBUF_ARCH_IA32) || defined(GOOGLE_PROTOBUF_ARCH_X64)
-#include <google/protobuf/stubs/atomicops_internals_x86_gcc.h>
-#elif defined(GOOGLE_PROTOBUF_ARCH_ARM) && defined(__linux__)
-#if (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4))
-#include <google/protobuf/stubs/atomicops_internals_generic_gcc.h>
-#else
-#include <google/protobuf/stubs/atomicops_internals_arm_gcc.h>
-#endif
-#elif defined(GOOGLE_PROTOBUF_ARCH_AARCH64)
-#include <google/protobuf/stubs/atomicops_internals_arm64_gcc.h>
-#elif defined(GOOGLE_PROTOBUF_ARCH_ARM_QNX)
-#include <google/protobuf/stubs/atomicops_internals_arm_qnx.h>
-#elif defined(GOOGLE_PROTOBUF_ARCH_MIPS) || defined(GOOGLE_PROTOBUF_ARCH_MIPS64)
-#include <google/protobuf/stubs/atomicops_internals_mips_gcc.h>
-#elif defined(GOOGLE_PROTOBUF_ARCH_POWER)
-#include <google/protobuf/stubs/atomicops_internals_power.h>
-#elif defined(__native_client__)
-// The static_asserts in the C++11 atomics implementation cause it to fail
-// with certain compilers, e.g. nvcc on macOS. Don't use elsewhere unless
-// the TODO in that file is addressed.
-#include <google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h>
-#elif defined(GOOGLE_PROTOBUF_ARCH_PPC)
-#include <google/protobuf/stubs/atomicops_internals_ppc_gcc.h>
-#elif (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4))
-#include <google/protobuf/stubs/atomicops_internals_generic_gcc.h>
-#elif defined(__clang__)
-#if __has_extension(c_atomic)
-#include <google/protobuf/stubs/atomicops_internals_generic_gcc.h>
-#else
-#error GOOGLE_PROTOBUF_ATOMICOPS_ERROR
-#endif
-#else
-#error GOOGLE_PROTOBUF_ATOMICOPS_ERROR
-#endif
-
-// Unknown.
-#else
-#error GOOGLE_PROTOBUF_ATOMICOPS_ERROR
-#endif
-
-#undef GOOGLE_PROTOBUF_ATOMICOPS_ERROR
-
-#endif // GOOGLE_PROTOBUF_NO_THREAD_SAFETY
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_H_
diff --git a/src/google/protobuf/stubs/atomicops_internals_arm64_gcc.h b/src/google/protobuf/stubs/atomicops_internals_arm64_gcc.h
deleted file mode 100644
index 9a69d21a..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_arm64_gcc.h
+++ /dev/null
@@ -1,325 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2012 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This file is an internal atomic implementation, use atomicops.h instead.
-
-#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM64_GCC_H_
-#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM64_GCC_H_
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-inline void MemoryBarrierInternal() {
- __asm__ __volatile__ ("dmb ish" ::: "memory"); // NOLINT
-}
-
-// NoBarrier versions of the operation include "memory" in the clobber list.
-// This is not required for direct usage of the NoBarrier versions of the
-// operations. However this is required for correctness when they are used as
-// part of the Acquire or Release versions, to ensure that nothing from outside
-// the call is reordered between the operation and the memory barrier. This does
-// not change the code generated, so has no or minimal impact on the
-// NoBarrier operations.
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 prev;
- int32_t temp;
-
- __asm__ __volatile__ ( // NOLINT
- "0: \n\t"
- "ldxr %w[prev], %[ptr] \n\t" // Load the previous value.
- "cmp %w[prev], %w[old_value] \n\t"
- "bne 1f \n\t"
- "stxr %w[temp], %w[new_value], %[ptr] \n\t" // Try to store the new value.
- "cbnz %w[temp], 0b \n\t" // Retry if it did not work.
- "1: \n\t"
- : [prev]"=&r" (prev),
- [temp]"=&r" (temp),
- [ptr]"+Q" (*ptr)
- : [old_value]"IJr" (old_value),
- [new_value]"r" (new_value)
- : "cc", "memory"
- ); // NOLINT
-
- return prev;
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
- Atomic32 new_value) {
- Atomic32 result;
- int32_t temp;
-
- __asm__ __volatile__ ( // NOLINT
- "0: \n\t"
- "ldxr %w[result], %[ptr] \n\t" // Load the previous value.
- "stxr %w[temp], %w[new_value], %[ptr] \n\t" // Try to store the new value.
- "cbnz %w[temp], 0b \n\t" // Retry if it did not work.
- : [result]"=&r" (result),
- [temp]"=&r" (temp),
- [ptr]"+Q" (*ptr)
- : [new_value]"r" (new_value)
- : "memory"
- ); // NOLINT
-
- return result;
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- Atomic32 result;
- int32_t temp;
-
- __asm__ __volatile__ ( // NOLINT
- "0: \n\t"
- "ldxr %w[result], %[ptr] \n\t" // Load the previous value.
- "add %w[result], %w[result], %w[increment]\n\t"
- "stxr %w[temp], %w[result], %[ptr] \n\t" // Try to store the result.
- "cbnz %w[temp], 0b \n\t" // Retry on failure.
- : [result]"=&r" (result),
- [temp]"=&r" (temp),
- [ptr]"+Q" (*ptr)
- : [increment]"IJr" (increment)
- : "memory"
- ); // NOLINT
-
- return result;
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- MemoryBarrierInternal();
- Atomic32 result = NoBarrier_AtomicIncrement(ptr, increment);
- MemoryBarrierInternal();
-
- return result;
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 prev = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
- MemoryBarrierInternal();
-
- return prev;
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- MemoryBarrierInternal();
- Atomic32 prev = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-
- return prev;
-}
-
-inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
- MemoryBarrierInternal();
-}
-
-inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
- __asm__ __volatile__ ( // NOLINT
- "stlr %w[value], %[ptr] \n\t"
- : [ptr]"=Q" (*ptr)
- : [value]"r" (value)
- : "memory"
- ); // NOLINT
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
- return *ptr;
-}
-
-inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
- Atomic32 value;
-
- __asm__ __volatile__ ( // NOLINT
- "ldar %w[value], %[ptr] \n\t"
- : [value]"=r" (value)
- : [ptr]"Q" (*ptr)
- : "memory"
- ); // NOLINT
-
- return value;
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
- MemoryBarrierInternal();
- return *ptr;
-}
-
-// 64-bit versions of the operations.
-// See the 32-bit versions for comments.
-
-inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- Atomic64 prev;
- int32_t temp;
-
- __asm__ __volatile__ ( // NOLINT
- "0: \n\t"
- "ldxr %[prev], %[ptr] \n\t"
- "cmp %[prev], %[old_value] \n\t"
- "bne 1f \n\t"
- "stxr %w[temp], %[new_value], %[ptr] \n\t"
- "cbnz %w[temp], 0b \n\t"
- "1: \n\t"
- : [prev]"=&r" (prev),
- [temp]"=&r" (temp),
- [ptr]"+Q" (*ptr)
- : [old_value]"IJr" (old_value),
- [new_value]"r" (new_value)
- : "cc", "memory"
- ); // NOLINT
-
- return prev;
-}
-
-inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr,
- Atomic64 new_value) {
- Atomic64 result;
- int32_t temp;
-
- __asm__ __volatile__ ( // NOLINT
- "0: \n\t"
- "ldxr %[result], %[ptr] \n\t"
- "stxr %w[temp], %[new_value], %[ptr] \n\t"
- "cbnz %w[temp], 0b \n\t"
- : [result]"=&r" (result),
- [temp]"=&r" (temp),
- [ptr]"+Q" (*ptr)
- : [new_value]"r" (new_value)
- : "memory"
- ); // NOLINT
-
- return result;
-}
-
-inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- Atomic64 result;
- int32_t temp;
-
- __asm__ __volatile__ ( // NOLINT
- "0: \n\t"
- "ldxr %[result], %[ptr] \n\t"
- "add %[result], %[result], %[increment] \n\t"
- "stxr %w[temp], %[result], %[ptr] \n\t"
- "cbnz %w[temp], 0b \n\t"
- : [result]"=&r" (result),
- [temp]"=&r" (temp),
- [ptr]"+Q" (*ptr)
- : [increment]"IJr" (increment)
- : "memory"
- ); // NOLINT
-
- return result;
-}
-
-inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- MemoryBarrierInternal();
- Atomic64 result = NoBarrier_AtomicIncrement(ptr, increment);
- MemoryBarrierInternal();
-
- return result;
-}
-
-inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- Atomic64 prev = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
- MemoryBarrierInternal();
-
- return prev;
-}
-
-inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- MemoryBarrierInternal();
- Atomic64 prev = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-
- return prev;
-}
-
-inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
- *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) {
- *ptr = value;
- MemoryBarrierInternal();
-}
-
-inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) {
- __asm__ __volatile__ ( // NOLINT
- "stlr %x[value], %[ptr] \n\t"
- : [ptr]"=Q" (*ptr)
- : [value]"r" (value)
- : "memory"
- ); // NOLINT
-}
-
-inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) {
- return *ptr;
-}
-
-inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) {
- Atomic64 value;
-
- __asm__ __volatile__ ( // NOLINT
- "ldar %x[value], %[ptr] \n\t"
- : [value]"=r" (value)
- : [ptr]"Q" (*ptr)
- : "memory"
- ); // NOLINT
-
- return value;
-}
-
-inline Atomic64 Release_Load(volatile const Atomic64* ptr) {
- MemoryBarrierInternal();
- return *ptr;
-}
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM64_GCC_H_
diff --git a/src/google/protobuf/stubs/atomicops_internals_arm_gcc.h b/src/google/protobuf/stubs/atomicops_internals_arm_gcc.h
deleted file mode 100644
index 6e2de67f..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_arm_gcc.h
+++ /dev/null
@@ -1,151 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2012 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This file is an internal atomic implementation, use atomicops.h instead.
-//
-// LinuxKernelCmpxchg and Barrier_AtomicIncrement are from Google Gears.
-
-#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_GCC_H_
-#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_GCC_H_
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-// 0xffff0fc0 is the hard coded address of a function provided by
-// the kernel which implements an atomic compare-exchange. On older
-// ARM architecture revisions (pre-v6) this may be implemented using
-// a syscall. This address is stable, and in active use (hard coded)
-// by at least glibc-2.7 and the Android C library.
-typedef Atomic32 (*LinuxKernelCmpxchgFunc)(Atomic32 old_value,
- Atomic32 new_value,
- volatile Atomic32* ptr);
-LinuxKernelCmpxchgFunc pLinuxKernelCmpxchg __attribute__((weak)) =
- (LinuxKernelCmpxchgFunc) 0xffff0fc0;
-
-typedef void (*LinuxKernelMemoryBarrierFunc)(void);
-LinuxKernelMemoryBarrierFunc pLinuxKernelMemoryBarrier __attribute__((weak)) =
- (LinuxKernelMemoryBarrierFunc) 0xffff0fa0;
-
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 prev_value = *ptr;
- do {
- if (!pLinuxKernelCmpxchg(old_value, new_value,
- const_cast<Atomic32*>(ptr))) {
- return old_value;
- }
- prev_value = *ptr;
- } while (prev_value == old_value);
- return prev_value;
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
- Atomic32 new_value) {
- Atomic32 old_value;
- do {
- old_value = *ptr;
- } while (pLinuxKernelCmpxchg(old_value, new_value,
- const_cast<Atomic32*>(ptr)));
- return old_value;
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- return Barrier_AtomicIncrement(ptr, increment);
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- for (;;) {
- // Atomic exchange the old value with an incremented one.
- Atomic32 old_value = *ptr;
- Atomic32 new_value = old_value + increment;
- if (pLinuxKernelCmpxchg(old_value, new_value,
- const_cast<Atomic32*>(ptr)) == 0) {
- // The exchange took place as expected.
- return new_value;
- }
- // Otherwise, *ptr changed mid-loop and we need to retry.
- }
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
-}
-
-inline void MemoryBarrierInternal() {
- pLinuxKernelMemoryBarrier();
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
- MemoryBarrierInternal();
-}
-
-inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
- MemoryBarrierInternal();
- *ptr = value;
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
- return *ptr;
-}
-
-inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
- Atomic32 value = *ptr;
- MemoryBarrierInternal();
- return value;
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
- MemoryBarrierInternal();
- return *ptr;
-}
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_GCC_H_
diff --git a/src/google/protobuf/stubs/atomicops_internals_arm_qnx.h b/src/google/protobuf/stubs/atomicops_internals_arm_qnx.h
deleted file mode 100644
index cd97e0c9..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_arm_qnx.h
+++ /dev/null
@@ -1,146 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2012 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This file is an internal atomic implementation, use atomicops.h instead.
-
-#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_QNX_H_
-#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_QNX_H_
-
-// For _smp_cmpxchg()
-#include <pthread.h>
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-inline Atomic32 QNXCmpxchg(Atomic32 old_value,
- Atomic32 new_value,
- volatile Atomic32* ptr) {
- return static_cast<Atomic32>(
- _smp_cmpxchg((volatile unsigned *)ptr,
- (unsigned)old_value,
- (unsigned)new_value));
-}
-
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 prev_value = *ptr;
- do {
- if (!QNXCmpxchg(old_value, new_value,
- const_cast<Atomic32*>(ptr))) {
- return old_value;
- }
- prev_value = *ptr;
- } while (prev_value == old_value);
- return prev_value;
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
- Atomic32 new_value) {
- Atomic32 old_value;
- do {
- old_value = *ptr;
- } while (QNXCmpxchg(old_value, new_value,
- const_cast<Atomic32*>(ptr)));
- return old_value;
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- return Barrier_AtomicIncrement(ptr, increment);
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- for (;;) {
- // Atomic exchange the old value with an incremented one.
- Atomic32 old_value = *ptr;
- Atomic32 new_value = old_value + increment;
- if (QNXCmpxchg(old_value, new_value,
- const_cast<Atomic32*>(ptr)) == 0) {
- // The exchange took place as expected.
- return new_value;
- }
- // Otherwise, *ptr changed mid-loop and we need to retry.
- }
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
-}
-
-inline void MemoryBarrierInternal() {
- __sync_synchronize();
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
- MemoryBarrierInternal();
-}
-
-inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
- MemoryBarrierInternal();
- *ptr = value;
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
- return *ptr;
-}
-
-inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
- Atomic32 value = *ptr;
- MemoryBarrierInternal();
- return value;
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
- MemoryBarrierInternal();
- return *ptr;
-}
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_QNX_H_
diff --git a/src/google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h b/src/google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h
deleted file mode 100644
index 44ef9c9e..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h
+++ /dev/null
@@ -1,231 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2012 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This file is an internal atomic implementation, use atomicops.h instead.
-
-#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_C11_ATOMIC_H_
-#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_C11_ATOMIC_H_
-
-#include <atomic>
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-// This implementation is transitional and maintains the original API for
-// atomicops.h. This requires casting memory locations to the atomic types, and
-// assumes that the API and the C++11 implementation are layout-compatible,
-// which isn't true for all implementations or hardware platforms. The static
-// assertion should detect this issue, were it to fire then this header
-// shouldn't be used.
-//
-// TODO(jfb) If this header manages to stay committed then the API should be
-// modified, and all call sites updated.
-typedef volatile std::atomic<Atomic32>* AtomicLocation32;
-static_assert(sizeof(*(AtomicLocation32) nullptr) == sizeof(Atomic32),
- "incompatible 32-bit atomic layout");
-
-inline void MemoryBarrierInternal() {
-#if defined(__GLIBCXX__)
- // Work around libstdc++ bug 51038 where atomic_thread_fence was declared but
- // not defined, leading to the linker complaining about undefined references.
- __atomic_thread_fence(std::memory_order_seq_cst);
-#else
- std::atomic_thread_fence(std::memory_order_seq_cst);
-#endif
-}
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- ((AtomicLocation32)ptr)
- ->compare_exchange_strong(old_value,
- new_value,
- std::memory_order_relaxed,
- std::memory_order_relaxed);
- return old_value;
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
- Atomic32 new_value) {
- return ((AtomicLocation32)ptr)
- ->exchange(new_value, std::memory_order_relaxed);
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- return increment +
- ((AtomicLocation32)ptr)
- ->fetch_add(increment, std::memory_order_relaxed);
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- return increment + ((AtomicLocation32)ptr)->fetch_add(increment);
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- ((AtomicLocation32)ptr)
- ->compare_exchange_strong(old_value,
- new_value,
- std::memory_order_acquire,
- std::memory_order_acquire);
- return old_value;
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- ((AtomicLocation32)ptr)
- ->compare_exchange_strong(old_value,
- new_value,
- std::memory_order_release,
- std::memory_order_relaxed);
- return old_value;
-}
-
-inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
- ((AtomicLocation32)ptr)->store(value, std::memory_order_relaxed);
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
- ((AtomicLocation32)ptr)->store(value, std::memory_order_relaxed);
- MemoryBarrierInternal();
-}
-
-inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
- ((AtomicLocation32)ptr)->store(value, std::memory_order_release);
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
- return ((AtomicLocation32)ptr)->load(std::memory_order_relaxed);
-}
-
-inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
- return ((AtomicLocation32)ptr)->load(std::memory_order_acquire);
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
- MemoryBarrierInternal();
- return ((AtomicLocation32)ptr)->load(std::memory_order_relaxed);
-}
-
-#if defined(GOOGLE_PROTOBUF_ARCH_64_BIT)
-
-typedef volatile std::atomic<Atomic64>* AtomicLocation64;
-static_assert(sizeof(*(AtomicLocation64) nullptr) == sizeof(Atomic64),
- "incompatible 64-bit atomic layout");
-
-inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- ((AtomicLocation64)ptr)
- ->compare_exchange_strong(old_value,
- new_value,
- std::memory_order_relaxed,
- std::memory_order_relaxed);
- return old_value;
-}
-
-inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr,
- Atomic64 new_value) {
- return ((AtomicLocation64)ptr)
- ->exchange(new_value, std::memory_order_relaxed);
-}
-
-inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- return increment +
- ((AtomicLocation64)ptr)
- ->fetch_add(increment, std::memory_order_relaxed);
-}
-
-inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- return increment + ((AtomicLocation64)ptr)->fetch_add(increment);
-}
-
-inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- ((AtomicLocation64)ptr)
- ->compare_exchange_strong(old_value,
- new_value,
- std::memory_order_acquire,
- std::memory_order_acquire);
- return old_value;
-}
-
-inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- ((AtomicLocation64)ptr)
- ->compare_exchange_strong(old_value,
- new_value,
- std::memory_order_release,
- std::memory_order_relaxed);
- return old_value;
-}
-
-inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
- ((AtomicLocation64)ptr)->store(value, std::memory_order_relaxed);
-}
-
-inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) {
- ((AtomicLocation64)ptr)->store(value, std::memory_order_relaxed);
- MemoryBarrierInternal();
-}
-
-inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) {
- ((AtomicLocation64)ptr)->store(value, std::memory_order_release);
-}
-
-inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) {
- return ((AtomicLocation64)ptr)->load(std::memory_order_relaxed);
-}
-
-inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) {
- return ((AtomicLocation64)ptr)->load(std::memory_order_acquire);
-}
-
-inline Atomic64 Release_Load(volatile const Atomic64* ptr) {
- MemoryBarrierInternal();
- return ((AtomicLocation64)ptr)->load(std::memory_order_relaxed);
-}
-
-#endif // defined(GOOGLE_PROTOBUF_ARCH_64_BIT)
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_C11_ATOMIC_H_
diff --git a/src/google/protobuf/stubs/atomicops_internals_generic_gcc.h b/src/google/protobuf/stubs/atomicops_internals_generic_gcc.h
deleted file mode 100644
index 075c406a..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_generic_gcc.h
+++ /dev/null
@@ -1,163 +0,0 @@
-// Copyright 2013 Red Hat Inc. All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Red Hat Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This file is an internal atomic implementation, use atomicops.h instead.
-
-#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_GCC_H_
-#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_GCC_H_
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- __atomic_compare_exchange_n(ptr, &old_value, new_value, false,
- __ATOMIC_RELAXED, __ATOMIC_RELAXED);
- return old_value;
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
- Atomic32 new_value) {
- return __atomic_exchange_n(ptr, new_value, __ATOMIC_RELAXED);
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- return __atomic_add_fetch(ptr, increment, __ATOMIC_RELAXED);
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- return __atomic_add_fetch(ptr, increment, __ATOMIC_SEQ_CST);
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- __atomic_compare_exchange_n(ptr, &old_value, new_value, false,
- __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE);
- return old_value;
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- __atomic_compare_exchange_n(ptr, &old_value, new_value, false,
- __ATOMIC_RELEASE, __ATOMIC_ACQUIRE);
- return old_value;
-}
-
-inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
- __atomic_store_n(ptr, value, __ATOMIC_RELAXED);
-}
-
-inline void MemoryBarrierInternal() {
- __sync_synchronize();
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
- __atomic_store_n(ptr, value, __ATOMIC_SEQ_CST);
-}
-
-inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
- __atomic_store_n(ptr, value, __ATOMIC_RELEASE);
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
- return __atomic_load_n(ptr, __ATOMIC_RELAXED);
-}
-
-inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
- return __atomic_load_n(ptr, __ATOMIC_ACQUIRE);
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
- return __atomic_load_n(ptr, __ATOMIC_SEQ_CST);
-}
-
-#ifdef __LP64__
-
-inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) {
- __atomic_store_n(ptr, value, __ATOMIC_RELEASE);
-}
-
-inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) {
- return __atomic_load_n(ptr, __ATOMIC_ACQUIRE);
-}
-
-inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- __atomic_compare_exchange_n(ptr, &old_value, new_value, false,
- __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE);
- return old_value;
-}
-
-inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- __atomic_compare_exchange_n(ptr, &old_value, new_value, false,
- __ATOMIC_RELAXED, __ATOMIC_RELAXED);
- return old_value;
-}
-
-inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- return __atomic_add_fetch(ptr, increment, __ATOMIC_RELAXED);
-}
-
-inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
- __atomic_store_n(ptr, value, __ATOMIC_RELAXED);
-}
-
-inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr,
- Atomic64 new_value) {
- return __atomic_exchange_n(ptr, new_value, __ATOMIC_RELAXED);
-}
-
-inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) {
- return __atomic_load_n(ptr, __ATOMIC_RELAXED);
-}
-
-inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- __atomic_compare_exchange_n(ptr, &old_value, new_value, false,
- __ATOMIC_RELEASE, __ATOMIC_ACQUIRE);
- return old_value;
-}
-
-#endif // defined(__LP64__)
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_GCC_H_
diff --git a/src/google/protobuf/stubs/atomicops_internals_mips_gcc.h b/src/google/protobuf/stubs/atomicops_internals_mips_gcc.h
deleted file mode 100644
index 6ce6820e..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_mips_gcc.h
+++ /dev/null
@@ -1,313 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2012 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This file is an internal atomic implementation, use atomicops.h instead.
-
-#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_MIPS_GCC_H_
-#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_MIPS_GCC_H_
-
-#define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory")
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-// Atomically execute:
-// result = *ptr;
-// if (*ptr == old_value)
-// *ptr = new_value;
-// return result;
-//
-// I.e., replace "*ptr" with "new_value" if "*ptr" used to be "old_value".
-// Always return the old value of "*ptr"
-//
-// This routine implies no memory barriers.
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 prev, tmp;
- __asm__ __volatile__(".set push\n"
- ".set noreorder\n"
- "1:\n"
- "ll %0, %5\n" // prev = *ptr
- "bne %0, %3, 2f\n" // if (prev != old_value) goto 2
- "move %2, %4\n" // tmp = new_value
- "sc %2, %1\n" // *ptr = tmp (with atomic check)
- "beqz %2, 1b\n" // start again on atomic error
- "nop\n" // delay slot nop
- "2:\n"
- ".set pop\n"
- : "=&r" (prev), "=m" (*ptr), "=&r" (tmp)
- : "r" (old_value), "r" (new_value), "m" (*ptr)
- : "memory");
- return prev;
-}
-
-// Atomically store new_value into *ptr, returning the previous value held in
-// *ptr. This routine implies no memory barriers.
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
- Atomic32 new_value) {
- Atomic32 temp, old;
- __asm__ __volatile__(".set push\n"
- ".set noreorder\n"
- "1:\n"
- "ll %1, %4\n" // old = *ptr
- "move %0, %3\n" // temp = new_value
- "sc %0, %2\n" // *ptr = temp (with atomic check)
- "beqz %0, 1b\n" // start again on atomic error
- "nop\n" // delay slot nop
- ".set pop\n"
- : "=&r" (temp), "=&r" (old), "=m" (*ptr)
- : "r" (new_value), "m" (*ptr)
- : "memory");
-
- return old;
-}
-
-// Atomically increment *ptr by "increment". Returns the new value of
-// *ptr with the increment applied. This routine implies no memory barriers.
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- Atomic32 temp, temp2;
-
- __asm__ __volatile__(".set push\n"
- ".set noreorder\n"
- "1:\n"
- "ll %0, %4\n" // temp = *ptr
- "addu %1, %0, %3\n" // temp2 = temp + increment
- "sc %1, %2\n" // *ptr = temp2 (with atomic check)
- "beqz %1, 1b\n" // start again on atomic error
- "addu %1, %0, %3\n" // temp2 = temp + increment
- ".set pop\n"
- : "=&r" (temp), "=&r" (temp2), "=m" (*ptr)
- : "Ir" (increment), "m" (*ptr)
- : "memory");
- // temp2 now holds the final value.
- return temp2;
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- ATOMICOPS_COMPILER_BARRIER();
- Atomic32 res = NoBarrier_AtomicIncrement(ptr, increment);
- ATOMICOPS_COMPILER_BARRIER();
- return res;
-}
-
-// "Acquire" operations
-// ensure that no later memory access can be reordered ahead of the operation.
-// "Release" operations ensure that no previous memory access can be reordered
-// after the operation. "Barrier" operations have both "Acquire" and "Release"
-// semantics. A MemoryBarrierInternal() has "Barrier" semantics, but does no
-// memory access.
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- ATOMICOPS_COMPILER_BARRIER();
- Atomic32 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
- ATOMICOPS_COMPILER_BARRIER();
- return res;
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- ATOMICOPS_COMPILER_BARRIER();
- Atomic32 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
- ATOMICOPS_COMPILER_BARRIER();
- return res;
-}
-
-inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
-}
-
-inline void MemoryBarrierInternal() {
- __asm__ __volatile__("sync" : : : "memory");
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
- MemoryBarrierInternal();
-}
-
-inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
- MemoryBarrierInternal();
- *ptr = value;
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
- return *ptr;
-}
-
-inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
- Atomic32 value = *ptr;
- MemoryBarrierInternal();
- return value;
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
- MemoryBarrierInternal();
- return *ptr;
-}
-
-#if defined(__LP64__)
-// 64-bit versions of the atomic ops.
-
-inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- Atomic64 prev, tmp;
- __asm__ __volatile__(".set push\n"
- ".set noreorder\n"
- "1:\n"
- "lld %0, %5\n" // prev = *ptr
- "bne %0, %3, 2f\n" // if (prev != old_value) goto 2
- "move %2, %4\n" // tmp = new_value
- "scd %2, %1\n" // *ptr = tmp (with atomic check)
- "beqz %2, 1b\n" // start again on atomic error
- "nop\n" // delay slot nop
- "2:\n"
- ".set pop\n"
- : "=&r" (prev), "=m" (*ptr), "=&r" (tmp)
- : "r" (old_value), "r" (new_value), "m" (*ptr)
- : "memory");
- return prev;
-}
-
-// Atomically store new_value into *ptr, returning the previous value held in
-// *ptr. This routine implies no memory barriers.
-inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr,
- Atomic64 new_value) {
- Atomic64 temp, old;
- __asm__ __volatile__(".set push\n"
- ".set noreorder\n"
- "1:\n"
- "lld %1, %4\n" // old = *ptr
- "move %0, %3\n" // temp = new_value
- "scd %0, %2\n" // *ptr = temp (with atomic check)
- "beqz %0, 1b\n" // start again on atomic error
- "nop\n" // delay slot nop
- ".set pop\n"
- : "=&r" (temp), "=&r" (old), "=m" (*ptr)
- : "r" (new_value), "m" (*ptr)
- : "memory");
-
- return old;
-}
-
-// Atomically increment *ptr by "increment". Returns the new value of
-// *ptr with the increment applied. This routine implies no memory barriers.
-inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- Atomic64 temp, temp2;
-
- __asm__ __volatile__(".set push\n"
- ".set noreorder\n"
- "1:\n"
- "lld %0, %4\n" // temp = *ptr
- "daddu %1, %0, %3\n" // temp2 = temp + increment
- "scd %1, %2\n" // *ptr = temp2 (with atomic check)
- "beqz %1, 1b\n" // start again on atomic error
- "daddu %1, %0, %3\n" // temp2 = temp + increment
- ".set pop\n"
- : "=&r" (temp), "=&r" (temp2), "=m" (*ptr)
- : "Ir" (increment), "m" (*ptr)
- : "memory");
- // temp2 now holds the final value.
- return temp2;
-}
-
-inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- MemoryBarrierInternal();
- Atomic64 res = NoBarrier_AtomicIncrement(ptr, increment);
- MemoryBarrierInternal();
- return res;
-}
-
-// "Acquire" operations
-// ensure that no later memory access can be reordered ahead of the operation.
-// "Release" operations ensure that no previous memory access can be reordered
-// after the operation. "Barrier" operations have both "Acquire" and "Release"
-// semantics. A MemoryBarrierInternal() has "Barrier" semantics, but does no
-// memory access.
-inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- Atomic64 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
- MemoryBarrierInternal();
- return res;
-}
-
-inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- MemoryBarrierInternal();
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
- *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) {
- *ptr = value;
- MemoryBarrierInternal();
-}
-
-inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) {
- MemoryBarrierInternal();
- *ptr = value;
-}
-
-inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) {
- return *ptr;
-}
-
-inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) {
- Atomic64 value = *ptr;
- MemoryBarrierInternal();
- return value;
-}
-
-inline Atomic64 Release_Load(volatile const Atomic64* ptr) {
- MemoryBarrierInternal();
- return *ptr;
-}
-#endif
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#undef ATOMICOPS_COMPILER_BARRIER
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_MIPS_GCC_H_
diff --git a/src/google/protobuf/stubs/atomicops_internals_power.h b/src/google/protobuf/stubs/atomicops_internals_power.h
deleted file mode 100644
index cad9f1e3..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_power.h
+++ /dev/null
@@ -1,440 +0,0 @@
-// Copyright 2014 Bloomberg Finance LP. All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Bloomberg Finance LP. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This file is an internal atomic implementation, use atomicops.h instead.
-
-#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_AIX_H_
-#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_AIX_H_
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 result;
-
- asm volatile (
- "1: lwarx %[res], %[zero], %[obj] \n\t" // load and reserve
- " cmpw %[cmp], %[res] \n\t" // compare values
- " bne- 2f \n\t"
- " stwcx. %[val], %[zero], %[obj] \n\t" // store new value
- " bne- 1b \n\t"
- "2: \n\t"
- : [res] "=&b" (result)
- : [obj] "b" (ptr),
- [cmp] "b" (old_value),
- [val] "b" (new_value),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
- Atomic32 new_value) {
- Atomic32 result;
-
- asm volatile (
- "1: lwarx %[res], %[zero], %[obj] \n\t"
- " stwcx. %[val], %[zero], %[obj] \n\t"
- " bne- 1b \n\t"
- : [res] "=&b" (result)
- : [obj] "b" (ptr),
- [val] "b" (new_value),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- Atomic32 result;
-
- asm volatile (
- "1: lwarx %[res], %[zero], %[obj] \n\t" // load and reserve
- " add %[res], %[val], %[res] \n\t" // add the operand
- " stwcx. %[res], %[zero], %[obj] \n\t" // store old value
- // if still reserved
- " bne- 1b \n\t"
- : [res] "=&b" (result)
- : [obj] "b" (ptr),
- [val] "b" (increment),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-
-inline void MemoryBarrierInternal(void) {
- asm volatile (
- " lwsync \n\t"
- " isync \n\t"
- :
- :
- : "memory");
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- Atomic32 result;
-
- asm volatile (
- " lwsync \n\t"
-
- "1: lwarx %[res], %[zero], %[obj] \n\t" // load and reserve
- " add %[res], %[val], %[res] \n\t" // add the operand
- " stwcx. %[res], %[zero], %[obj] \n\t" // store old value
- // if still reserved
- " bne- 1b \n\t"
- " isync \n\t"
- : [res] "=&b" (result)
- : [obj] "b" (ptr),
- [val] "b" (increment),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 result;
-
- asm volatile (
- "1: lwarx %[res], %[zero], %[obj] \n\t" // load and reserve
- " cmpw %[cmp], %[res] \n\t" // compare values
- " bne- 2f \n\t"
- " stwcx. %[val], %[zero], %[obj] \n\t" // store new value
- " bne- 1b \n\t"
-
- " isync \n\t"
- "2: \n\t"
- : [res] "=&b" (result)
- : [obj] "b" (ptr),
- [cmp] "b" (old_value),
- [val] "b" (new_value),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 result;
-
- asm volatile (
- " lwsync \n\t"
-
- "1: lwarx %[res], %[zero], %[obj] \n\t" // load and reserve
- " cmpw %[cmp], %[res] \n\t" // compare values
- " bne- 2f \n\t"
- " stwcx. %[val], %[zero], %[obj] \n\t" // store new value
- " bne- 1b \n\t"
-
- "2: \n\t"
- : [res] "=&b" (result)
- : [obj] "b" (ptr),
- [cmp] "b" (old_value),
- [val] "b" (new_value),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-
-inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
- asm volatile (
- " stw %[val], %[obj] \n\t"
- " isync \n\t"
- : [obj] "=m" (*ptr)
- : [val] "b" (value));
-}
-
-inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
- asm volatile (
- " lwsync \n\t"
- " stw %[val], %[obj] \n\t"
- : [obj] "=m" (*ptr)
- : [val] "b" (value));
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
- return *ptr;
-}
-
-inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
- Atomic32 result;
-
- asm volatile (
- "1: lwz %[res], %[obj] \n\t"
- " cmpw %[res], %[res] \n\t" // create data
- // dependency for
- // load/load ordering
- " bne- 1b \n\t" // never taken
-
- " isync \n\t"
- : [res] "=b" (result)
- : [obj] "m" (*ptr),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
- Atomic32 result;
-
- asm volatile (
- " lwsync \n\t"
-
- "1: lwz %[res], %[obj] \n\t"
- " cmpw %[res], %[res] \n\t" // create data
- // dependency for
- // load/load ordering
- " bne- 1b \n\t" // never taken
- : [res] "=b" (result)
- : [obj] "m" (*ptr),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-
-#ifdef GOOGLE_PROTOBUF_ARCH_64_BIT
-inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- Atomic64 result;
-
- asm volatile (
- "1: ldarx %[res], %[zero], %[obj] \n\t" // load and reserve
- " cmpd %[cmp], %[res] \n\t" // compare values
- " bne- 2f \n\t"
-
- " stdcx. %[val], %[zero], %[obj] \n\t" // store the new value
- " bne- 1b \n\t"
- "2: \n\t"
- : [res] "=&b" (result)
- : [obj] "b" (ptr),
- [cmp] "b" (old_value),
- [val] "b" (new_value),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-
-inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr,
- Atomic64 new_value) {
- Atomic64 result;
-
- asm volatile (
- "1: ldarx %[res], %[zero], %[obj] \n\t"
- " stdcx. %[val], %[zero], %[obj] \n\t"
- " bne- 1b \n\t"
- : [res] "=&b" (result)
- : [obj] "b" (ptr),
- [val] "b" (new_value),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-
-inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- Atomic64 result;
-
- asm volatile (
- "1: ldarx %[res], %[zero], %[obj] \n\t" // load and reserve
- " add %[res], %[res], %[val] \n\t" // add the operand
- " stdcx. %[res], %[zero], %[obj] \n\t" // store old value if
- // still reserved
-
- " bne- 1b \n\t"
- : [res] "=&b" (result)
- : [obj] "b" (ptr),
- [val] "b" (increment),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-
-inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
-
- Atomic64 result;
-
- asm volatile (
- " lwsync \n\t"
-
- "1: ldarx %[res], %[zero], %[obj] \n\t" // load and reserve
- " add %[res], %[res], %[val] \n\t" // add the operand
- " stdcx. %[res], %[zero], %[obj] \n\t" // store old value if
- // still reserved
-
- " bne- 1b \n\t"
-
- " isync \n\t"
- : [res] "=&b" (result)
- : [obj] "b" (ptr),
- [val] "b" (increment),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-
-inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- Atomic64 result;
-
- asm volatile (
- "1: ldarx %[res], %[zero], %[obj] \n\t" // load and reserve
- " cmpd %[cmp], %[res] \n\t" // compare values
- " bne- 2f \n\t"
-
- " stdcx. %[val], %[zero], %[obj] \n\t" // store the new value
- " bne- 1b \n\t"
- " isync \n\t"
- "2: \n\t"
- : [res] "=&b" (result)
- : [obj] "b" (ptr),
- [cmp] "b" (old_value),
- [val] "b" (new_value),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-
-inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- Atomic64 result;
-
- asm volatile (
- " lwsync \n\t"
-
- "1: ldarx %[res], %[zero], %[obj] \n\t" // load and reserve
- " cmpd %[cmp], %[res] \n\t" // compare values
- " bne- 2f \n\t"
-
- " stdcx. %[val], %[zero], %[obj] \n\t" // store the new value
- " bne- 1b \n\t"
- "2: \n\t"
- : [res] "=&b" (result)
- : [obj] "b" (ptr),
- [cmp] "b" (old_value),
- [val] "b" (new_value),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-
-inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
- *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) {
- asm volatile (
- " std %[val], %[obj] \n\t"
- " isync \n\t"
- : [obj] "=m" (*ptr)
- : [val] "b" (value));
-}
-
-inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) {
- asm volatile (
- " lwsync \n\t"
- " std %[val], %[obj] \n\t"
- : [obj] "=m" (*ptr)
- : [val] "b" (value));
-}
-
-inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) {
- return *ptr;
-}
-
-inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) {
- Atomic64 result;
-
- asm volatile (
- "1: ld %[res], %[obj] \n\t"
- " cmpd %[res], %[res] \n\t" // create data
- // dependency for
- // load/load ordering
- " bne- 1b \n\t" // never taken
-
- " isync \n\t"
- : [res] "=b" (result)
- : [obj] "m" (*ptr),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-
-inline Atomic64 Release_Load(volatile const Atomic64* ptr) {
- Atomic64 result;
-
- asm volatile (
- " lwsync \n\t"
-
- "1: ld %[res], %[obj] \n\t"
- " cmpd %[res], %[res] \n\t" // create data
- // dependency for
- // load/load ordering
- " bne- 1b \n\t" // never taken
- : [res] "=b" (result)
- : [obj] "m" (*ptr),
- [zero] "i" (0)
- : "cr0", "ctr");
-
- return result;
-}
-#endif
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_SPARC_GCC_H_
diff --git a/src/google/protobuf/stubs/atomicops_internals_ppc_gcc.h b/src/google/protobuf/stubs/atomicops_internals_ppc_gcc.h
deleted file mode 100644
index d477dc6d..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_ppc_gcc.h
+++ /dev/null
@@ -1,155 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2015 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: ogabbay@advaoptical.com (Oded Gabbay)
-// Cleaned up by: bsilver16384@gmail.com (Brian Silverman)
-//
-// This file is an internal atomic implementation, use atomicops.h instead.
-
-#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_PPC_GCC_H_
-#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_PPC_GCC_H_
-
-#define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory")
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32 *ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 prev;
-
- __asm__ __volatile__(
- "0: \n\t"
- "lwarx %[prev],0,%[ptr] \n\t"
- "cmpw 0,%[prev],%[old_value] \n\t"
- "bne- 1f \n\t"
- "stwcx. %[new_value],0,%[ptr] \n\t"
- "bne- 0b \n\t"
- "1: \n\t"
- : [prev] "=&r"(prev), "+m"(*ptr)
- : [ptr] "r"(ptr), [old_value] "r"(old_value), [new_value] "r"(new_value)
- : "cc", "memory");
-
- return prev;
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32 *ptr,
- Atomic32 new_value) {
- Atomic32 old;
-
- __asm__ __volatile__(
- "0: \n\t"
- "lwarx %[old],0,%[ptr] \n\t"
- "stwcx. %[new_value],0,%[ptr] \n\t"
- "bne- 0b \n\t"
- : [old] "=&r"(old), "+m"(*ptr)
- : [ptr] "r"(ptr), [new_value] "r"(new_value)
- : "cc", "memory");
-
- return old;
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32 *ptr,
- Atomic32 increment) {
- Atomic32 temp;
-
- __asm__ __volatile__(
- "0: \n\t"
- "lwarx %[temp],0,%[ptr] \n\t"
- "add %[temp],%[increment],%[temp] \n\t"
- "stwcx. %[temp],0,%[ptr] \n\t"
- "bne- 0b \n\t"
- : [temp] "=&r"(temp)
- : [increment] "r"(increment), [ptr] "r"(ptr)
- : "cc", "memory");
-
- return temp;
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32 *ptr,
- Atomic32 increment) {
- MemoryBarrierInternal();
- Atomic32 res = NoBarrier_AtomicIncrement(ptr, increment);
- MemoryBarrierInternal();
- return res;
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32 *ptr,
- Atomic32 old_value, Atomic32 new_value) {
- Atomic32 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
- MemoryBarrierInternal();
- return res;
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32 *ptr,
- Atomic32 old_value, Atomic32 new_value) {
- MemoryBarrierInternal();
- Atomic32 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
- return res;
-}
-
-inline void NoBarrier_Store(volatile Atomic32 *ptr, Atomic32 value) {
- *ptr = value;
-}
-
-inline void MemoryBarrierInternal() { __asm__ __volatile__("sync" : : : "memory"); }
-
-inline void Acquire_Store(volatile Atomic32 *ptr, Atomic32 value) {
- *ptr = value;
- MemoryBarrierInternal();
-}
-
-inline void Release_Store(volatile Atomic32 *ptr, Atomic32 value) {
- MemoryBarrierInternal();
- *ptr = value;
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32 *ptr) { return *ptr; }
-
-inline Atomic32 Acquire_Load(volatile const Atomic32 *ptr) {
- Atomic32 value = *ptr;
- MemoryBarrierInternal();
- return value;
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32 *ptr) {
- MemoryBarrierInternal();
- return *ptr;
-}
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#undef ATOMICOPS_COMPILER_BARRIER
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_PPC_GCC_H_
diff --git a/src/google/protobuf/stubs/atomicops_internals_solaris.h b/src/google/protobuf/stubs/atomicops_internals_solaris.h
deleted file mode 100644
index baecb993..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_solaris.h
+++ /dev/null
@@ -1,188 +0,0 @@
-// Copyright 2014 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This file is an internal atomic implementation, use atomicops.h instead.
-
-#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_SPARC_GCC_H_
-#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_SPARC_GCC_H_
-
-#include <atomic.h>
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- return (Atomic32)atomic_cas_32((volatile uint32_t*)ptr, (uint32_t)old_value, (uint32_t)new_value);
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
- Atomic32 new_value) {
- return (Atomic32)atomic_swap_32((volatile uint32_t*)ptr, (uint32_t)new_value);
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- return (Atomic32)atomic_add_32_nv((volatile uint32_t*)ptr, (uint32_t)increment);
-}
-
-inline void MemoryBarrierInternal(void) {
- membar_producer();
- membar_consumer();
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- MemoryBarrierInternal();
- Atomic32 ret = NoBarrier_AtomicIncrement(ptr, increment);
- MemoryBarrierInternal();
-
- return ret;
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 ret = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
- MemoryBarrierInternal();
-
- return ret;
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- MemoryBarrierInternal();
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
- membar_producer();
-}
-
-inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
- membar_consumer();
- *ptr = value;
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
- return *ptr;
-}
-
-inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
- Atomic32 val = *ptr;
- membar_consumer();
- return val;
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
- membar_producer();
- return *ptr;
-}
-
-#ifdef GOOGLE_PROTOBUF_ARCH_64_BIT
-inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- return atomic_cas_64((volatile uint64_t*)ptr, (uint64_t)old_value, (uint64_t)new_value);
-}
-
-inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, Atomic64 new_value) {
- return atomic_swap_64((volatile uint64_t*)ptr, (uint64_t)new_value);
-}
-
-inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment) {
- return atomic_add_64_nv((volatile uint64_t*)ptr, increment);
-}
-
-inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment) {
- MemoryBarrierInternal();
- Atomic64 ret = atomic_add_64_nv((volatile uint64_t*)ptr, increment);
- MemoryBarrierInternal();
- return ret;
-}
-
-inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- Atomic64 ret = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
- MemoryBarrierInternal();
- return ret;
-}
-
-inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- MemoryBarrierInternal();
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
- *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) {
- *ptr = value;
- membar_producer();
-}
-
-inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) {
- membar_consumer();
- *ptr = value;
-}
-
-inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) {
- return *ptr;
-}
-
-inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) {
- Atomic64 ret = *ptr;
- membar_consumer();
- return ret;
-}
-
-inline Atomic64 Release_Load(volatile const Atomic64* ptr) {
- membar_producer();
- return *ptr;
-}
-#endif
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_SPARC_GCC_H_
-
diff --git a/src/google/protobuf/stubs/atomicops_internals_tsan.h b/src/google/protobuf/stubs/atomicops_internals_tsan.h
deleted file mode 100644
index 676380b1..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_tsan.h
+++ /dev/null
@@ -1,219 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2013 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This file is an internal atomic implementation for compiler-based
-// ThreadSanitizer (http://clang.llvm.org/docs/ThreadSanitizer.html).
-// Use atomicops.h instead.
-
-#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_TSAN_H_
-#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_TSAN_H_
-
-#define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory")
-
-#include <sanitizer/tsan_interface_atomic.h>
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32 *ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 cmp = old_value;
- __tsan_atomic32_compare_exchange_strong(ptr, &cmp, new_value,
- __tsan_memory_order_relaxed, __tsan_memory_order_relaxed);
- return cmp;
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32 *ptr,
- Atomic32 new_value) {
- return __tsan_atomic32_exchange(ptr, new_value,
- __tsan_memory_order_relaxed);
-}
-
-inline Atomic32 Acquire_AtomicExchange(volatile Atomic32 *ptr,
- Atomic32 new_value) {
- return __tsan_atomic32_exchange(ptr, new_value,
- __tsan_memory_order_acquire);
-}
-
-inline Atomic32 Release_AtomicExchange(volatile Atomic32 *ptr,
- Atomic32 new_value) {
- return __tsan_atomic32_exchange(ptr, new_value,
- __tsan_memory_order_release);
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32 *ptr,
- Atomic32 increment) {
- return increment + __tsan_atomic32_fetch_add(ptr, increment,
- __tsan_memory_order_relaxed);
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32 *ptr,
- Atomic32 increment) {
- return increment + __tsan_atomic32_fetch_add(ptr, increment,
- __tsan_memory_order_acq_rel);
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32 *ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 cmp = old_value;
- __tsan_atomic32_compare_exchange_strong(ptr, &cmp, new_value,
- __tsan_memory_order_acquire, __tsan_memory_order_acquire);
- return cmp;
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32 *ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 cmp = old_value;
- __tsan_atomic32_compare_exchange_strong(ptr, &cmp, new_value,
- __tsan_memory_order_release, __tsan_memory_order_relaxed);
- return cmp;
-}
-
-inline void NoBarrier_Store(volatile Atomic32 *ptr, Atomic32 value) {
- __tsan_atomic32_store(ptr, value, __tsan_memory_order_relaxed);
-}
-
-inline void Acquire_Store(volatile Atomic32 *ptr, Atomic32 value) {
- __tsan_atomic32_store(ptr, value, __tsan_memory_order_relaxed);
- __tsan_atomic_thread_fence(__tsan_memory_order_seq_cst);
-}
-
-inline void Release_Store(volatile Atomic32 *ptr, Atomic32 value) {
- __tsan_atomic32_store(ptr, value, __tsan_memory_order_release);
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32 *ptr) {
- return __tsan_atomic32_load(ptr, __tsan_memory_order_relaxed);
-}
-
-inline Atomic32 Acquire_Load(volatile const Atomic32 *ptr) {
- return __tsan_atomic32_load(ptr, __tsan_memory_order_acquire);
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32 *ptr) {
- __tsan_atomic_thread_fence(__tsan_memory_order_seq_cst);
- return __tsan_atomic32_load(ptr, __tsan_memory_order_relaxed);
-}
-
-inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64 *ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- Atomic64 cmp = old_value;
- __tsan_atomic64_compare_exchange_strong(ptr, &cmp, new_value,
- __tsan_memory_order_relaxed, __tsan_memory_order_relaxed);
- return cmp;
-}
-
-inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64 *ptr,
- Atomic64 new_value) {
- return __tsan_atomic64_exchange(ptr, new_value, __tsan_memory_order_relaxed);
-}
-
-inline Atomic64 Acquire_AtomicExchange(volatile Atomic64 *ptr,
- Atomic64 new_value) {
- return __tsan_atomic64_exchange(ptr, new_value, __tsan_memory_order_acquire);
-}
-
-inline Atomic64 Release_AtomicExchange(volatile Atomic64 *ptr,
- Atomic64 new_value) {
- return __tsan_atomic64_exchange(ptr, new_value, __tsan_memory_order_release);
-}
-
-inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64 *ptr,
- Atomic64 increment) {
- return increment + __tsan_atomic64_fetch_add(ptr, increment,
- __tsan_memory_order_relaxed);
-}
-
-inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64 *ptr,
- Atomic64 increment) {
- return increment + __tsan_atomic64_fetch_add(ptr, increment,
- __tsan_memory_order_acq_rel);
-}
-
-inline void NoBarrier_Store(volatile Atomic64 *ptr, Atomic64 value) {
- __tsan_atomic64_store(ptr, value, __tsan_memory_order_relaxed);
-}
-
-inline void Acquire_Store(volatile Atomic64 *ptr, Atomic64 value) {
- __tsan_atomic64_store(ptr, value, __tsan_memory_order_relaxed);
- __tsan_atomic_thread_fence(__tsan_memory_order_seq_cst);
-}
-
-inline void Release_Store(volatile Atomic64 *ptr, Atomic64 value) {
- __tsan_atomic64_store(ptr, value, __tsan_memory_order_release);
-}
-
-inline Atomic64 NoBarrier_Load(volatile const Atomic64 *ptr) {
- return __tsan_atomic64_load(ptr, __tsan_memory_order_relaxed);
-}
-
-inline Atomic64 Acquire_Load(volatile const Atomic64 *ptr) {
- return __tsan_atomic64_load(ptr, __tsan_memory_order_acquire);
-}
-
-inline Atomic64 Release_Load(volatile const Atomic64 *ptr) {
- __tsan_atomic_thread_fence(__tsan_memory_order_seq_cst);
- return __tsan_atomic64_load(ptr, __tsan_memory_order_relaxed);
-}
-
-inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64 *ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- Atomic64 cmp = old_value;
- __tsan_atomic64_compare_exchange_strong(ptr, &cmp, new_value,
- __tsan_memory_order_acquire, __tsan_memory_order_acquire);
- return cmp;
-}
-
-inline Atomic64 Release_CompareAndSwap(volatile Atomic64 *ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- Atomic64 cmp = old_value;
- __tsan_atomic64_compare_exchange_strong(ptr, &cmp, new_value,
- __tsan_memory_order_release, __tsan_memory_order_relaxed);
- return cmp;
-}
-
-inline void MemoryBarrierInternal() {
- __tsan_atomic_thread_fence(__tsan_memory_order_seq_cst);
-}
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#undef ATOMICOPS_COMPILER_BARRIER
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_TSAN_H_
diff --git a/src/google/protobuf/stubs/atomicops_internals_x86_gcc.cc b/src/google/protobuf/stubs/atomicops_internals_x86_gcc.cc
deleted file mode 100644
index 53c9eae0..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_x86_gcc.cc
+++ /dev/null
@@ -1,137 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2012 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This module gets enough CPU information to optimize the
-// atomicops module on x86.
-
-#include <cstring>
-
-#include <google/protobuf/stubs/atomicops.h>
-
-// This file only makes sense with atomicops_internals_x86_gcc.h -- it
-// depends on structs that are defined in that file. If atomicops.h
-// doesn't sub-include that file, then we aren't needed, and shouldn't
-// try to do anything.
-#ifdef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_GCC_H_
-
-// Inline cpuid instruction. In PIC compilations, %ebx contains the address
-// of the global offset table. To avoid breaking such executables, this code
-// must preserve that register's value across cpuid instructions.
-#if defined(__i386__)
-#define cpuid(a, b, c, d, inp) \
- asm("mov %%ebx, %%edi\n" \
- "cpuid\n" \
- "xchg %%edi, %%ebx\n" \
- : "=a" (a), "=D" (b), "=c" (c), "=d" (d) : "a" (inp))
-#elif defined(__x86_64__)
-#define cpuid(a, b, c, d, inp) \
- asm("mov %%rbx, %%rdi\n" \
- "cpuid\n" \
- "xchg %%rdi, %%rbx\n" \
- : "=a" (a), "=D" (b), "=c" (c), "=d" (d) : "a" (inp))
-#endif
-
-#if defined(cpuid) // initialize the struct only on x86
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-// Set the flags so that code will run correctly and conservatively, so even
-// if we haven't been initialized yet, we're probably single threaded, and our
-// default values should hopefully be pretty safe.
-struct AtomicOps_x86CPUFeatureStruct AtomicOps_Internalx86CPUFeatures = {
- false, // bug can't exist before process spawns multiple threads
- false, // no SSE2
-};
-
-namespace {
-
-// Initialize the AtomicOps_Internalx86CPUFeatures struct.
-void AtomicOps_Internalx86CPUFeaturesInit() {
- uint32_t eax;
- uint32_t ebx;
- uint32_t ecx;
- uint32_t edx;
-
- // Get vendor string (issue CPUID with eax = 0)
- cpuid(eax, ebx, ecx, edx, 0);
- char vendor[13];
- memcpy(vendor, &ebx, 4);
- memcpy(vendor + 4, &edx, 4);
- memcpy(vendor + 8, &ecx, 4);
- vendor[12] = 0;
-
- // get feature flags in ecx/edx, and family/model in eax
- cpuid(eax, ebx, ecx, edx, 1);
-
- int family = (eax >> 8) & 0xf; // family and model fields
- int model = (eax >> 4) & 0xf;
- if (family == 0xf) { // use extended family and model fields
- family += (eax >> 20) & 0xff;
- model += ((eax >> 16) & 0xf) << 4;
- }
-
- // Opteron Rev E has a bug in which on very rare occasions a locked
- // instruction doesn't act as a read-acquire barrier if followed by a
- // non-locked read-modify-write instruction. Rev F has this bug in
- // pre-release versions, but not in versions released to customers,
- // so we test only for Rev E, which is family 15, model 32..63 inclusive.
- if (strcmp(vendor, "AuthenticAMD") == 0 && // AMD
- family == 15 &&
- 32 <= model && model <= 63) {
- AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug = true;
- } else {
- AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug = false;
- }
-
- // edx bit 26 is SSE2 which we use to tell use whether we can use mfence
- AtomicOps_Internalx86CPUFeatures.has_sse2 = ((edx >> 26) & 1);
-}
-
-class AtomicOpsx86Initializer {
- public:
- AtomicOpsx86Initializer() {
- AtomicOps_Internalx86CPUFeaturesInit();
- }
-};
-
-// A global to get use initialized on startup via static initialization :/
-AtomicOpsx86Initializer g_initer;
-
-} // namespace
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#endif // __i386__
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_GCC_H_
diff --git a/src/google/protobuf/stubs/atomicops_internals_x86_gcc.h b/src/google/protobuf/stubs/atomicops_internals_x86_gcc.h
deleted file mode 100644
index e80121fd..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_x86_gcc.h
+++ /dev/null
@@ -1,293 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2012 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This file is an internal atomic implementation, use atomicops.h instead.
-
-#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_GCC_H_
-#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_GCC_H_
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-// This struct is not part of the public API of this module; clients may not
-// use it.
-// Features of this x86. Values may not be correct before main() is run,
-// but are set conservatively.
-struct AtomicOps_x86CPUFeatureStruct {
- bool has_amd_lock_mb_bug; // Processor has AMD memory-barrier bug; do lfence
- // after acquire compare-and-swap.
- bool has_sse2; // Processor has SSE2.
-};
-extern struct AtomicOps_x86CPUFeatureStruct AtomicOps_Internalx86CPUFeatures;
-
-#define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory")
-
-// 32-bit low-level operations on any platform.
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 prev;
- __asm__ __volatile__("lock; cmpxchgl %1,%2"
- : "=a" (prev)
- : "q" (new_value), "m" (*ptr), "0" (old_value)
- : "memory");
- return prev;
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
- Atomic32 new_value) {
- __asm__ __volatile__("xchgl %1,%0" // The lock prefix is implicit for xchg.
- : "=r" (new_value)
- : "m" (*ptr), "0" (new_value)
- : "memory");
- return new_value; // Now it's the previous value.
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- Atomic32 temp = increment;
- __asm__ __volatile__("lock; xaddl %0,%1"
- : "+r" (temp), "+m" (*ptr)
- : : "memory");
- // temp now holds the old value of *ptr
- return temp + increment;
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- Atomic32 temp = increment;
- __asm__ __volatile__("lock; xaddl %0,%1"
- : "+r" (temp), "+m" (*ptr)
- : : "memory");
- // temp now holds the old value of *ptr
- if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
- __asm__ __volatile__("lfence" : : : "memory");
- }
- return temp + increment;
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
- if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
- __asm__ __volatile__("lfence" : : : "memory");
- }
- return x;
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
-}
-
-#if defined(__x86_64__)
-
-// 64-bit implementations of memory barrier can be simpler, because it
-// "mfence" is guaranteed to exist.
-inline void MemoryBarrierInternal() {
- __asm__ __volatile__("mfence" : : : "memory");
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
- MemoryBarrierInternal();
-}
-
-#else
-
-inline void MemoryBarrierInternal() {
- if (AtomicOps_Internalx86CPUFeatures.has_sse2) {
- __asm__ __volatile__("mfence" : : : "memory");
- } else { // mfence is faster but not present on PIII
- Atomic32 x = 0;
- NoBarrier_AtomicExchange(&x, 0); // acts as a barrier on PIII
- }
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
- if (AtomicOps_Internalx86CPUFeatures.has_sse2) {
- *ptr = value;
- __asm__ __volatile__("mfence" : : : "memory");
- } else {
- NoBarrier_AtomicExchange(ptr, value);
- // acts as a barrier on PIII
- }
-}
-#endif
-
-inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
- ATOMICOPS_COMPILER_BARRIER();
- *ptr = value; // An x86 store acts as a release barrier.
- // See comments in Atomic64 version of Release_Store(), below.
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
- return *ptr;
-}
-
-inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
- Atomic32 value = *ptr; // An x86 load acts as a acquire barrier.
- // See comments in Atomic64 version of Release_Store(), below.
- ATOMICOPS_COMPILER_BARRIER();
- return value;
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
- MemoryBarrierInternal();
- return *ptr;
-}
-
-#if defined(__x86_64__)
-
-// 64-bit low-level operations on 64-bit platform.
-
-inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- Atomic64 prev;
- __asm__ __volatile__("lock; cmpxchgq %1,%2"
- : "=a" (prev)
- : "q" (new_value), "m" (*ptr), "0" (old_value)
- : "memory");
- return prev;
-}
-
-inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr,
- Atomic64 new_value) {
- __asm__ __volatile__("xchgq %1,%0" // The lock prefix is implicit for xchg.
- : "=r" (new_value)
- : "m" (*ptr), "0" (new_value)
- : "memory");
- return new_value; // Now it's the previous value.
-}
-
-inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- Atomic64 temp = increment;
- __asm__ __volatile__("lock; xaddq %0,%1"
- : "+r" (temp), "+m" (*ptr)
- : : "memory");
- // temp now contains the previous value of *ptr
- return temp + increment;
-}
-
-inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- Atomic64 temp = increment;
- __asm__ __volatile__("lock; xaddq %0,%1"
- : "+r" (temp), "+m" (*ptr)
- : : "memory");
- // temp now contains the previous value of *ptr
- if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
- __asm__ __volatile__("lfence" : : : "memory");
- }
- return temp + increment;
-}
-
-inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
- *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) {
- *ptr = value;
- MemoryBarrierInternal();
-}
-
-inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) {
- ATOMICOPS_COMPILER_BARRIER();
-
- *ptr = value; // An x86 store acts as a release barrier
- // for current AMD/Intel chips as of Jan 2008.
- // See also Acquire_Load(), below.
-
- // When new chips come out, check:
- // IA-32 Intel Architecture Software Developer's Manual, Volume 3:
- // System Programming Guide, Chatper 7: Multiple-processor management,
- // Section 7.2, Memory Ordering.
- // Last seen at:
- // http://developer.intel.com/design/pentium4/manuals/index_new.htm
- //
- // x86 stores/loads fail to act as barriers for a few instructions (clflush
- // maskmovdqu maskmovq movntdq movnti movntpd movntps movntq) but these are
- // not generated by the compiler, and are rare. Users of these instructions
- // need to know about cache behaviour in any case since all of these involve
- // either flushing cache lines or non-temporal cache hints.
-}
-
-inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) {
- return *ptr;
-}
-
-inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) {
- Atomic64 value = *ptr; // An x86 load acts as a acquire barrier,
- // for current AMD/Intel chips as of Jan 2008.
- // See also Release_Store(), above.
- ATOMICOPS_COMPILER_BARRIER();
- return value;
-}
-
-inline Atomic64 Release_Load(volatile const Atomic64* ptr) {
- MemoryBarrierInternal();
- return *ptr;
-}
-
-inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- Atomic64 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
- if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
- __asm__ __volatile__("lfence" : : : "memory");
- }
- return x;
-}
-
-inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-#endif // defined(__x86_64__)
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#undef ATOMICOPS_COMPILER_BARRIER
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_GCC_H_
diff --git a/src/google/protobuf/stubs/atomicops_internals_x86_msvc.cc b/src/google/protobuf/stubs/atomicops_internals_x86_msvc.cc
deleted file mode 100644
index 74a1bd4e..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_x86_msvc.cc
+++ /dev/null
@@ -1,113 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2012 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// The compilation of extension_set.cc fails when windows.h is included.
-// Therefore we move the code depending on windows.h to this separate cc file.
-
-// Don't compile this file for people not concerned about thread safety.
-#ifndef GOOGLE_PROTOBUF_NO_THREAD_SAFETY
-
-#include <google/protobuf/stubs/atomicops.h>
-
-#ifdef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_MSVC_H_
-
-#include <windows.h>
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-inline void MemoryBarrierInternal() {
- // On ARM this is a define while on x86/x64 this is
- // a function declared in WinNT.h
- MemoryBarrier();
-}
-
-Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- LONG result = InterlockedCompareExchange(
- reinterpret_cast<volatile LONG*>(ptr),
- static_cast<LONG>(new_value),
- static_cast<LONG>(old_value));
- return static_cast<Atomic32>(result);
-}
-
-Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
- Atomic32 new_value) {
- LONG result = InterlockedExchange(
- reinterpret_cast<volatile LONG*>(ptr),
- static_cast<LONG>(new_value));
- return static_cast<Atomic32>(result);
-}
-
-Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- return InterlockedExchangeAdd(
- reinterpret_cast<volatile LONG*>(ptr),
- static_cast<LONG>(increment)) + increment;
-}
-
-#if defined(_WIN64)
-
-// 64-bit low-level operations on 64-bit platform.
-
-Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- PVOID result = InterlockedCompareExchangePointer(
- reinterpret_cast<volatile PVOID*>(ptr),
- reinterpret_cast<PVOID>(new_value), reinterpret_cast<PVOID>(old_value));
- return reinterpret_cast<Atomic64>(result);
-}
-
-Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr,
- Atomic64 new_value) {
- PVOID result = InterlockedExchangePointer(
- reinterpret_cast<volatile PVOID*>(ptr),
- reinterpret_cast<PVOID>(new_value));
- return reinterpret_cast<Atomic64>(result);
-}
-
-Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- return InterlockedExchangeAdd64(
- reinterpret_cast<volatile LONGLONG*>(ptr),
- static_cast<LONGLONG>(increment)) + increment;
-}
-
-#endif // defined(_WIN64)
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_MSVC_H_
-#endif // GOOGLE_PROTOBUF_NO_THREAD_SAFETY
diff --git a/src/google/protobuf/stubs/atomicops_internals_x86_msvc.h b/src/google/protobuf/stubs/atomicops_internals_x86_msvc.h
deleted file mode 100644
index 34d60d98..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_x86_msvc.h
+++ /dev/null
@@ -1,150 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2012 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This file is an internal atomic implementation, use atomicops.h instead.
-
-#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_MSVC_H_
-#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_MSVC_H_
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- return Barrier_AtomicIncrement(ptr, increment);
-}
-
-#if !(defined(_MSC_VER) && _MSC_VER >= 1400)
-#error "We require at least vs2005 for MemoryBarrier"
-#endif
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
- NoBarrier_AtomicExchange(ptr, value);
- // acts as a barrier in this implementation
-}
-
-inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value; // works w/o barrier for current Intel chips as of June 2005
- // See comments in Atomic64 version of Release_Store() below.
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
- return *ptr;
-}
-
-inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
- Atomic32 value = *ptr;
- return value;
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
- MemoryBarrierInternal();
- return *ptr;
-}
-
-#if defined(_WIN64)
-
-// 64-bit low-level operations on 64-bit platform.
-
-inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- return Barrier_AtomicIncrement(ptr, increment);
-}
-
-inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
- *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) {
- NoBarrier_AtomicExchange(ptr, value);
- // acts as a barrier in this implementation
-}
-
-inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) {
- *ptr = value; // works w/o barrier for current Intel chips as of June 2005
-
- // When new chips come out, check:
- // IA-32 Intel Architecture Software Developer's Manual, Volume 3:
- // System Programming Guide, Chatper 7: Multiple-processor management,
- // Section 7.2, Memory Ordering.
- // Last seen at:
- // http://developer.intel.com/design/pentium4/manuals/index_new.htm
-}
-
-inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) {
- return *ptr;
-}
-
-inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) {
- Atomic64 value = *ptr;
- return value;
-}
-
-inline Atomic64 Release_Load(volatile const Atomic64* ptr) {
- MemoryBarrierInternal();
- return *ptr;
-}
-
-inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-#endif // defined(_WIN64)
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_MSVC_H_
diff --git a/src/google/protobuf/stubs/bytestream.h b/src/google/protobuf/stubs/bytestream.h
index 86510d14..cfa19f29 100644
--- a/src/google/protobuf/stubs/bytestream.h
+++ b/src/google/protobuf/stubs/bytestream.h
@@ -57,7 +57,6 @@
#include <google/protobuf/stubs/stringpiece.h>
class CordByteSink;
-class MemBlock;
namespace google {
namespace protobuf {
@@ -162,7 +161,7 @@ class LIBPROTOBUF_EXPORT ByteSource {
class LIBPROTOBUF_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.
@@ -190,7 +189,7 @@ class LIBPROTOBUF_EXPORT UncheckedArrayByteSink : public ByteSink {
class LIBPROTOBUF_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_; }
@@ -227,7 +226,7 @@ class LIBPROTOBUF_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[].
@@ -256,7 +255,7 @@ class LIBPROTOBUF_EXPORT GrowingArrayByteSink : public strings::ByteSink {
class LIBPROTOBUF_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_;
@@ -273,7 +272,7 @@ class LIBPROTOBUF_EXPORT StringByteSink : public ByteSink {
class LIBPROTOBUF_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);
@@ -296,9 +295,9 @@ class LIBPROTOBUF_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_;
@@ -328,13 +327,13 @@ class LIBPROTOBUF_EXPORT LimitByteSource : public ByteSource {
// 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_;
diff --git a/src/google/protobuf/stubs/callback.h b/src/google/protobuf/stubs/callback.h
index 9ec04979..dae972f2 100644
--- a/src/google/protobuf/stubs/callback.h
+++ b/src/google/protobuf/stubs/callback.h
@@ -1,8 +1,9 @@
#ifndef GOOGLE_PROTOBUF_STUBS_CALLBACK_H_
#define GOOGLE_PROTOBUF_STUBS_CALLBACK_H_
+#include <type_traits>
+
#include <google/protobuf/stubs/macros.h>
-#include <google/protobuf/stubs/type_traits.h>
// ===================================================================
// emulates google3/base/callback.h
@@ -124,7 +125,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;
@@ -144,7 +145,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;
@@ -167,7 +168,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;
@@ -190,7 +191,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;
@@ -214,7 +215,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;
@@ -238,7 +239,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;
@@ -261,7 +262,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;
@@ -283,7 +284,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;
@@ -305,7 +306,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;
@@ -327,7 +328,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;
@@ -342,7 +343,7 @@ class FunctionResultCallback_1_1 : public ResultCallback1<R, A1> {
template <typename T>
struct InternalConstRef {
- typedef typename remove_reference<T>::type base_type;
+ typedef typename std::remove_reference<T>::type base_type;
typedef const base_type& type;
};
@@ -386,7 +387,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;
@@ -397,11 +398,11 @@ class MethodResultCallback_5_2 : public ResultCallback2<R, A1, A2> {
T* object_;
MethodType method_;
bool self_deleting_;
- typename remove_reference<P1>::type p1_;
- typename remove_reference<P2>::type p2_;
- typename remove_reference<P3>::type p3_;
- typename remove_reference<P4>::type p4_;
- typename remove_reference<P5>::type p5_;
+ typename std::remove_reference<P1>::type p1_;
+ typename std::remove_reference<P2>::type p2_;
+ typename std::remove_reference<P3>::type p3_;
+ typename std::remove_reference<P4>::type p4_;
+ typename std::remove_reference<P5>::type p5_;
};
} // namespace internal
diff --git a/src/google/protobuf/stubs/casts.h b/src/google/protobuf/stubs/casts.h
index be652849..35e2dba0 100644
--- a/src/google/protobuf/stubs/casts.h
+++ b/src/google/protobuf/stubs/casts.h
@@ -31,8 +31,9 @@
#ifndef GOOGLE_PROTOBUF_CASTS_H__
#define GOOGLE_PROTOBUF_CASTS_H__
+#include <type_traits>
+
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/type_traits.h>
namespace google {
namespace protobuf {
@@ -95,7 +96,7 @@ inline To down_cast(From* f) { // so we only accept pointers
template<typename To, typename From> // use like this: down_cast<T&>(foo);
inline To down_cast(From& f) {
- typedef typename remove_reference<To>::type* ToAsPointer;
+ typedef typename std::remove_reference<To>::type* ToAsPointer;
// Ensures that To is a sub-type of From *. This test is here only
// for compile-time type checking, and has no overhead in an
// optimized build at run-time, as it will be optimized away
diff --git a/src/google/protobuf/stubs/common.cc b/src/google/protobuf/stubs/common.cc
index 574c7405..33d24c57 100755..100644
--- a/src/google/protobuf/stubs/common.cc
+++ b/src/google/protobuf/stubs/common.cc
@@ -314,86 +314,6 @@ namespace internal { FunctionClosure0::~FunctionClosure0() {} }
void DoNothing() {}
// ===================================================================
-// emulates google3/base/mutex.cc
-
-#ifdef _WIN32
-
-struct Mutex::Internal {
- CRITICAL_SECTION mutex;
-#ifndef NDEBUG
- // Used only to implement AssertHeld().
- DWORD thread_id;
-#endif
-};
-
-Mutex::Mutex()
- : mInternal(new Internal) {
- InitializeCriticalSection(&mInternal->mutex);
-}
-
-Mutex::~Mutex() {
- DeleteCriticalSection(&mInternal->mutex);
- delete mInternal;
-}
-
-void Mutex::Lock() {
- EnterCriticalSection(&mInternal->mutex);
-#ifndef NDEBUG
- mInternal->thread_id = GetCurrentThreadId();
-#endif
-}
-
-void Mutex::Unlock() {
-#ifndef NDEBUG
- mInternal->thread_id = 0;
-#endif
- LeaveCriticalSection(&mInternal->mutex);
-}
-
-void Mutex::AssertHeld() {
-#ifndef NDEBUG
- GOOGLE_DCHECK_EQ(mInternal->thread_id, GetCurrentThreadId());
-#endif
-}
-
-#elif defined(HAVE_PTHREAD)
-
-struct Mutex::Internal {
- pthread_mutex_t mutex;
-};
-
-Mutex::Mutex()
- : mInternal(new Internal) {
- pthread_mutex_init(&mInternal->mutex, NULL);
-}
-
-Mutex::~Mutex() {
- pthread_mutex_destroy(&mInternal->mutex);
- delete mInternal;
-}
-
-void Mutex::Lock() {
- int result = pthread_mutex_lock(&mInternal->mutex);
- if (result != 0) {
- GOOGLE_LOG(FATAL) << "pthread_mutex_lock: " << strerror(result);
- }
-}
-
-void Mutex::Unlock() {
- int result = pthread_mutex_unlock(&mInternal->mutex);
- if (result != 0) {
- GOOGLE_LOG(FATAL) << "pthread_mutex_unlock: " << strerror(result);
- }
-}
-
-void Mutex::AssertHeld() {
- // pthreads dosn't provide a way to check which thread holds the mutex.
- // TODO(kenton): Maybe keep track of locking thread ID like with WIN32?
-}
-
-#endif
-
-// ===================================================================
// emulates google3/util/endian/endian.h
//
// TODO(xiaofeng): PROTOBUF_LITTLE_ENDIAN is unfortunately defined in
diff --git a/src/google/protobuf/stubs/common.h b/src/google/protobuf/stubs/common.h
index 04660b81..5d320764 100644
--- a/src/google/protobuf/stubs/common.h
+++ b/src/google/protobuf/stubs/common.h
@@ -38,6 +38,7 @@
#include <algorithm>
#include <iostream>
#include <map>
+#include <memory>
#include <set>
#include <string>
#include <vector>
@@ -48,7 +49,6 @@
// TODO(liujisi): Remove the following includes after the include clean-up.
#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/scoped_ptr.h>
#include <google/protobuf/stubs/mutex.h>
#include <google/protobuf/stubs/callback.h>
@@ -101,27 +101,27 @@ namespace internal {
// The current version, represented as a single integer to make comparison
// easier: major * 10^6 + minor * 10^3 + micro
-#define GOOGLE_PROTOBUF_VERSION 3005001
+#define GOOGLE_PROTOBUF_VERSION 3006000
// A suffix string for alpha, beta or rc releases. Empty for stable releases.
#define GOOGLE_PROTOBUF_VERSION_SUFFIX ""
// The minimum library version which works with the current version of the
// headers.
-#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 3005000
+#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 3006000
// The minimum header version which works with the current version of
// the library. This constant should only be used by protoc's C++ code
// generator.
-static const int kMinHeaderVersionForLibrary = 3005000;
+static const int kMinHeaderVersionForLibrary = 3006000;
// The minimum protoc version which works with the current version of the
// headers.
-#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 3005000
+#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 3006000
// The minimum header version which works with the current version of
// protoc. This constant should only be used in VerifyVersion().
-static const int kMinHeaderVersionForProtoc = 3005000;
+static const int kMinHeaderVersionForProtoc = 3006000;
// Verifies that the headers and libraries are compatible. Use the macro
// below to call this.
diff --git a/src/google/protobuf/stubs/hash.h b/src/google/protobuf/stubs/hash.h
index daf8ec57..fd8ba156 100644
--- a/src/google/protobuf/stubs/hash.h
+++ b/src/google/protobuf/stubs/hash.h
@@ -93,7 +93,7 @@
# 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
+# 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
@@ -235,7 +235,8 @@ class hash_set : public std::set<Key, HashFcn> {
HashFcn hash_function() const { return HashFcn(); }
};
-#elif defined(_MSC_VER) && !defined(_STLPORT_VERSION)
+#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> {
diff --git a/src/google/protobuf/stubs/int128.cc b/src/google/protobuf/stubs/int128.cc
index a5090801..7b993e8f 100644
--- a/src/google/protobuf/stubs/int128.cc
+++ b/src/google/protobuf/stubs/int128.cc
@@ -76,52 +76,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;
diff --git a/src/google/protobuf/stubs/io_win32.cc b/src/google/protobuf/stubs/io_win32.cc
index 5ead98c8..4407facb 100644
--- a/src/google/protobuf/stubs/io_win32.cc
+++ b/src/google/protobuf/stubs/io_win32.cc
@@ -52,13 +52,13 @@
#include <errno.h>
#include <fcntl.h>
#include <io.h>
+#include <memory>
#include <sys/stat.h>
#include <sys/types.h>
#include <wctype.h>
#include <windows.h>
#include <google/protobuf/stubs/io_win32.h>
-#include <google/protobuf/stubs/scoped_ptr.h>
#include <memory>
#include <sstream>
@@ -229,7 +229,7 @@ bool as_windows_path(const char* path, wstring* result) {
if (size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
return false;
}
- scoped_array<WCHAR> wcwd(new WCHAR[size]);
+ std::unique_ptr<WCHAR[]> wcwd(new WCHAR[size]);
::GetCurrentDirectoryW(size, wcwd.get());
wpath = join_paths(wcwd.get(), wpath);
}
@@ -371,7 +371,7 @@ bool wcs_to_mbs(const WCHAR* s, string* out, bool outUtf8) {
|| usedDefaultChar) {
return false;
}
- scoped_array<CHAR> astr(new CHAR[size]);
+ std::unique_ptr<CHAR[]> astr(new CHAR[size]);
WideCharToMultiByte(
outUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, astr.get(), size, NULL, NULL);
out->assign(astr.get());
@@ -390,7 +390,7 @@ bool mbs_to_wcs(const char* s, wstring* out, bool inUtf8) {
if (size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
return false;
}
- scoped_array<WCHAR> wstr(new WCHAR[size]);
+ std::unique_ptr<WCHAR[]> wstr(new WCHAR[size]);
MultiByteToWideChar(
inUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, wstr.get(), size + 1);
out->assign(wstr.get());
diff --git a/src/google/protobuf/stubs/io_win32_unittest.cc b/src/google/protobuf/stubs/io_win32_unittest.cc
index b216aece..c933757c 100644
--- a/src/google/protobuf/stubs/io_win32_unittest.cc
+++ b/src/google/protobuf/stubs/io_win32_unittest.cc
@@ -48,7 +48,6 @@
#include <windows.h>
#include <google/protobuf/stubs/io_win32.h>
-#include <google/protobuf/stubs/scoped_ptr.h>
#include <gtest/gtest.h>
#include <memory>
@@ -115,7 +114,7 @@ void StripTrailingSlashes(string* str) {
bool GetEnvVarAsUtf8(const WCHAR* name, string* result) {
DWORD size = ::GetEnvironmentVariableW(name, NULL, 0);
if (size > 0 && GetLastError() != ERROR_ENVVAR_NOT_FOUND) {
- scoped_array<WCHAR> wcs(new WCHAR[size]);
+ std::unique_ptr<WCHAR[]> wcs(new WCHAR[size]);
::GetEnvironmentVariableW(name, wcs.get(), size);
// GetEnvironmentVariableA retrieves an Active-Code-Page-encoded text which
// we'd first need to convert to UTF-16 then to UTF-8, because there seems
@@ -131,7 +130,7 @@ bool GetEnvVarAsUtf8(const WCHAR* name, string* result) {
bool GetCwdAsUtf8(string* result) {
DWORD size = ::GetCurrentDirectoryW(0, NULL);
if (size > 0) {
- scoped_array<WCHAR> wcs(new WCHAR[size]);
+ std::unique_ptr<WCHAR[]> wcs(new WCHAR[size]);
::GetCurrentDirectoryW(size, wcs.get());
// GetCurrentDirectoryA retrieves an Active-Code-Page-encoded text which
// we'd first need to convert to UTF-16 then to UTF-8, because there seems
@@ -402,7 +401,7 @@ TEST_F(IoWin32Test, ChdirTestNonAscii) {
TEST_F(IoWin32Test, AsWindowsPathTest) {
DWORD size = GetCurrentDirectoryW(0, NULL);
- scoped_array<wchar_t> cwd_str(new wchar_t[size]);
+ 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/map_util.h b/src/google/protobuf/stubs/map_util.h
index 16cbfac4..3e6d381f 100644
--- a/src/google/protobuf/stubs/map_util.h
+++ b/src/google/protobuf/stubs/map_util.h
@@ -654,7 +654,8 @@ InsertOrReturnExisting(
// delete EraseKeyReturnValuePtr(&my_map, "abc");
//
// Use returned value:
-// scoped_ptr<MyType> value_ptr(EraseKeyReturnValuePtr(&my_map, "abc"));
+// std::unique_ptr<MyType> value_ptr(
+// EraseKeyReturnValuePtr(&my_map, "abc"));
// if (value_ptr.get())
// value_ptr->DoSomething();
//
diff --git a/src/google/protobuf/stubs/mathlimits.h b/src/google/protobuf/stubs/mathlimits.h
index 2391ac4c..9c9d0e9a 100644
--- a/src/google/protobuf/stubs/mathlimits.h
+++ b/src/google/protobuf/stubs/mathlimits.h
@@ -243,7 +243,7 @@ DECL_UNSIGNED_INT_LIMITS(unsigned long long int)
#endif
// ========================================================================= //
-#ifdef WIN32 // Lacks built-in isnan() and isinf()
+#if WIN32 && !__MINGW32__ // Lacks built-in isnan() and isinf()
#define DECL_FP_LIMIT_FUNCS \
static bool IsFinite(const Type x) { return _finite(x); } \
static bool IsNaN(const Type x) { return _isnan(x); } \
diff --git a/src/google/protobuf/stubs/mutex.h b/src/google/protobuf/stubs/mutex.h
index 174290f6..47edb7a3 100644
--- a/src/google/protobuf/stubs/mutex.h
+++ b/src/google/protobuf/stubs/mutex.h
@@ -30,46 +30,48 @@
#ifndef GOOGLE_PROTOBUF_STUBS_MUTEX_H_
#define GOOGLE_PROTOBUF_STUBS_MUTEX_H_
-#ifdef GOOGLE_PROTOBUF_NO_THREADLOCAL
-#include <pthread.h>
-#endif
+#include <mutex>
#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
+
// ===================================================================
// emulates google3/base/mutex.h
namespace google {
namespace protobuf {
namespace internal {
-// A Mutex is a non-reentrant (aka non-recursive) mutex. At most one thread T
-// may hold a mutex at a given time. If T attempts to Lock() the same Mutex
-// while holding it, T will deadlock.
-class LIBPROTOBUF_EXPORT Mutex {
- public:
- // Create a Mutex that is not held by anybody.
- Mutex();
-
- // Destructor
- ~Mutex();
-
- // Block if necessary until this Mutex is free, then acquire it exclusively.
- void Lock();
-
- // Release this Mutex. Caller must hold it exclusively.
- void Unlock();
+#define GOOGLE_PROTOBUF_LINKER_INITIALIZED
+// 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 {
+ public:
+ WrappedMutex() = default;
+ 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();
+ void AssertHeld() const {}
private:
- struct Internal;
- Internal* mInternal;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Mutex);
+ std::mutex mu_;
};
+using Mutex = WrappedMutex;
+
// MutexLock(mu) acquires mu when constructed and releases it when destroyed.
class LIBPROTOBUF_EXPORT MutexLock {
public:
@@ -133,8 +135,10 @@ using internal::ReaderMutexLock;
using internal::WriterMutexLock;
using internal::MutexLockMaybe;
-
} // namespace protobuf
} // namespace google
+#undef GOOGLE_PROTOBUF_ACQUIRE
+#undef GOOGLE_PROTOBUF_RELEASE
+
#endif // GOOGLE_PROTOBUF_STUBS_MUTEX_H_
diff --git a/src/google/protobuf/stubs/once.cc b/src/google/protobuf/stubs/once.cc
deleted file mode 100644
index 889c6476..00000000
--- a/src/google/protobuf/stubs/once.cc
+++ /dev/null
@@ -1,99 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-//
-// emulates google3/base/once.h
-//
-// This header is intended to be included only by internal .cc files and
-// generated .pb.cc files. Users should not use this directly.
-
-#include <google/protobuf/stubs/once.h>
-
-#ifndef GOOGLE_PROTOBUF_NO_THREAD_SAFETY
-
-#ifdef _WIN32
-#include <windows.h>
-#else
-#include <sched.h>
-#endif
-
-#include <google/protobuf/stubs/atomicops.h>
-
-namespace google {
-namespace protobuf {
-
-namespace {
-
-void SchedYield() {
-#ifdef _WIN32
- Sleep(0);
-#else // POSIX
- sched_yield();
-#endif
-}
-
-} // namespace
-
-void GoogleOnceInitImpl(ProtobufOnceType* once, Closure* closure) {
- internal::AtomicWord state = internal::Acquire_Load(once);
- // Fast path. The provided closure was already executed.
- if (state == ONCE_STATE_DONE) {
- return;
- }
- // The closure execution did not complete yet. The once object can be in one
- // of the two following states:
- // - UNINITIALIZED: We are the first thread calling this function.
- // - EXECUTING_CLOSURE: Another thread is already executing the closure.
- //
- // First, try to change the state from UNINITIALIZED to EXECUTING_CLOSURE
- // atomically.
- state = internal::Acquire_CompareAndSwap(
- once, ONCE_STATE_UNINITIALIZED, ONCE_STATE_EXECUTING_CLOSURE);
- if (state == ONCE_STATE_UNINITIALIZED) {
- // We are the first thread to call this function, so we have to call the
- // closure.
- closure->Run();
- internal::Release_Store(once, ONCE_STATE_DONE);
- } else {
- // Another thread has already started executing the closure. We need to
- // wait until it completes the initialization.
- while (state == ONCE_STATE_EXECUTING_CLOSURE) {
- // Note that futex() could be used here on Linux as an improvement.
- SchedYield();
- state = internal::Acquire_Load(once);
- }
- }
-}
-
-} // namespace protobuf
-} // namespace google
-
-#endif // GOOGLE_PROTOBUF_NO_THREAD_SAFETY
diff --git a/src/google/protobuf/stubs/once.h b/src/google/protobuf/stubs/once.h
index 1f082c37..f3835ccd 100644
--- a/src/google/protobuf/stubs/once.h
+++ b/src/google/protobuf/stubs/once.h
@@ -78,88 +78,51 @@
#ifndef GOOGLE_PROTOBUF_STUBS_ONCE_H__
#define GOOGLE_PROTOBUF_STUBS_ONCE_H__
-#include <google/protobuf/stubs/atomicops.h>
-#include <google/protobuf/stubs/callback.h>
-#include <google/protobuf/stubs/common.h>
+#include <mutex>
+#include <utility>
namespace google {
namespace protobuf {
+namespace internal {
-#ifdef GOOGLE_PROTOBUF_NO_THREAD_SAFETY
-
-typedef bool ProtobufOnceType;
-
-#define GOOGLE_PROTOBUF_ONCE_INIT false
-
-inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)()) {
- if (!*once) {
- *once = true;
- init_func();
- }
+using once_flag = std::once_flag;
+template <typename... Args>
+void call_once(Args&&... args ) {
+ std::call_once(std::forward<Args>(args)...);
}
-template <typename Arg>
-inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)(Arg),
- Arg arg) {
- if (!*once) {
- *once = true;
- init_func(arg);
- }
-}
+} // namespace internal
-#else
-
-enum {
- ONCE_STATE_UNINITIALIZED = 0,
- ONCE_STATE_EXECUTING_CLOSURE = 1,
- ONCE_STATE_DONE = 2
-};
-
-typedef internal::AtomicWord ProtobufOnceType;
-
-#define GOOGLE_PROTOBUF_ONCE_INIT ::google::protobuf::ONCE_STATE_UNINITIALIZED
-
-LIBPROTOBUF_EXPORT
-void GoogleOnceInitImpl(ProtobufOnceType* once, Closure* closure);
+// TODO(gerbens) remove this once third_party is fully extracted
+using ProtobufOnceType = internal::once_flag;
inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)()) {
- if (internal::Acquire_Load(once) != ONCE_STATE_DONE) {
- internal::FunctionClosure0 func(init_func, false);
- GoogleOnceInitImpl(once, &func);
- }
+ std::call_once(*once, init_func);
}
template <typename Arg>
-inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)(Arg*),
- Arg* arg) {
- if (internal::Acquire_Load(once) != ONCE_STATE_DONE) {
- internal::FunctionClosure1<Arg*> func(init_func, false, arg);
- GoogleOnceInitImpl(once, &func);
- }
+inline void GoogleOnceInitArg(ProtobufOnceType* once, void (*init_func)(Arg*),
+ Arg* arg) {
+ std::call_once(*once, init_func, arg);
}
-#endif // GOOGLE_PROTOBUF_NO_THREAD_SAFETY
-
class GoogleOnceDynamic {
public:
- GoogleOnceDynamic() : state_(GOOGLE_PROTOBUF_ONCE_INIT) { }
-
// If this->Init() has not been called before by any thread,
// execute (*func_with_arg)(arg) then return.
// Otherwise, wait until that prior invocation has finished
// executing its function, then return.
template<typename T>
void Init(void (*func_with_arg)(T*), T* arg) {
- GoogleOnceInit<T>(&this->state_,
- func_with_arg,
- arg);
+ GoogleOnceInitArg<T>(&this->state_, func_with_arg, arg);
}
private:
ProtobufOnceType state_;
};
+#define GOOGLE_PROTOBUF_ONCE_TYPE ::google::protobuf::ProtobufOnceType
#define GOOGLE_PROTOBUF_DECLARE_ONCE(NAME) \
- ::google::protobuf::ProtobufOnceType NAME = GOOGLE_PROTOBUF_ONCE_INIT
+ ::google::protobuf::ProtobufOnceType NAME
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/stubs/once_unittest.cc b/src/google/protobuf/stubs/once_unittest.cc
deleted file mode 100644
index d5f7779e..00000000
--- a/src/google/protobuf/stubs/once_unittest.cc
+++ /dev/null
@@ -1,254 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-
-#ifdef _WIN32
-#include <windows.h>
-#else
-#include <unistd.h>
-#include <pthread.h>
-#endif
-
-#include <google/protobuf/stubs/once.h>
-#include <google/protobuf/testing/googletest.h>
-#include <gtest/gtest.h>
-
-namespace google {
-namespace protobuf {
-namespace {
-
-class OnceInitTest : public testing::Test {
- protected:
- void SetUp() {
- state_ = INIT_NOT_STARTED;
- current_test_ = this;
- }
-
- // Since ProtobufOnceType is only allowed to be allocated in static storage,
- // each test must use a different pair of ProtobufOnceType objects which it
- // must declare itself.
- void SetOnces(ProtobufOnceType* once, ProtobufOnceType* recursive_once) {
- once_ = once;
- recursive_once_ = recursive_once;
- }
-
- void InitOnce() {
- GoogleOnceInit(once_, &InitStatic);
- }
- void InitRecursiveOnce() {
- GoogleOnceInit(recursive_once_, &InitRecursiveStatic);
- }
-
- void BlockInit() { init_blocker_.Lock(); }
- void UnblockInit() { init_blocker_.Unlock(); }
-
- class TestThread {
- public:
- TestThread(Closure* callback)
- : done_(false), joined_(false), callback_(callback) {
-#ifdef _WIN32
- thread_ = CreateThread(NULL, 0, &Start, this, 0, NULL);
-#else
- pthread_create(&thread_, NULL, &Start, this);
-#endif
- }
- ~TestThread() {
- if (!joined_) Join();
- }
-
- bool IsDone() {
- MutexLock lock(&done_mutex_);
- return done_;
- }
- void Join() {
- joined_ = true;
-#ifdef _WIN32
- WaitForSingleObject(thread_, INFINITE);
- CloseHandle(thread_);
-#else
- pthread_join(thread_, NULL);
-#endif
- }
-
- private:
-#ifdef _WIN32
- HANDLE thread_;
-#else
- pthread_t thread_;
-#endif
-
- Mutex done_mutex_;
- bool done_;
- bool joined_;
- Closure* callback_;
-
-#ifdef _WIN32
- static DWORD WINAPI Start(LPVOID arg) {
-#else
- static void* Start(void* arg) {
-#endif
- reinterpret_cast<TestThread*>(arg)->Run();
- return 0;
- }
-
- void Run() {
- callback_->Run();
- MutexLock lock(&done_mutex_);
- done_ = true;
- }
- };
-
- TestThread* RunInitOnceInNewThread() {
- return new TestThread(NewCallback(this, &OnceInitTest::InitOnce));
- }
- TestThread* RunInitRecursiveOnceInNewThread() {
- return new TestThread(
- NewCallback(this, &OnceInitTest::InitRecursiveOnce));
- }
-
- enum State {
- INIT_NOT_STARTED,
- INIT_STARTED,
- INIT_DONE
- };
- State CurrentState() {
- MutexLock lock(&mutex_);
- return state_;
- }
-
- void WaitABit() {
-#ifdef _WIN32
- Sleep(1000);
-#else
- sleep(1);
-#endif
- }
-
- private:
- Mutex mutex_;
- Mutex init_blocker_;
- State state_;
- ProtobufOnceType* once_;
- ProtobufOnceType* recursive_once_;
-
- void Init() {
- MutexLock lock(&mutex_);
- EXPECT_EQ(INIT_NOT_STARTED, state_);
- state_ = INIT_STARTED;
- mutex_.Unlock();
- init_blocker_.Lock();
- init_blocker_.Unlock();
- mutex_.Lock();
- state_ = INIT_DONE;
- }
-
- static OnceInitTest* current_test_;
- static void InitStatic() { current_test_->Init(); }
- static void InitRecursiveStatic() { current_test_->InitOnce(); }
-};
-
-OnceInitTest* OnceInitTest::current_test_ = NULL;
-
-GOOGLE_PROTOBUF_DECLARE_ONCE(simple_once);
-
-TEST_F(OnceInitTest, Simple) {
- SetOnces(&simple_once, NULL);
-
- EXPECT_EQ(INIT_NOT_STARTED, CurrentState());
- InitOnce();
- EXPECT_EQ(INIT_DONE, CurrentState());
-
- // Calling again has no effect.
- InitOnce();
- EXPECT_EQ(INIT_DONE, CurrentState());
-}
-
-GOOGLE_PROTOBUF_DECLARE_ONCE(recursive_once1);
-GOOGLE_PROTOBUF_DECLARE_ONCE(recursive_once2);
-
-TEST_F(OnceInitTest, Recursive) {
- SetOnces(&recursive_once1, &recursive_once2);
-
- EXPECT_EQ(INIT_NOT_STARTED, CurrentState());
- InitRecursiveOnce();
- EXPECT_EQ(INIT_DONE, CurrentState());
-}
-
-GOOGLE_PROTOBUF_DECLARE_ONCE(multiple_threads_once);
-
-TEST_F(OnceInitTest, MultipleThreads) {
- SetOnces(&multiple_threads_once, NULL);
-
- scoped_ptr<TestThread> threads[4];
- EXPECT_EQ(INIT_NOT_STARTED, CurrentState());
- for (int i = 0; i < 4; i++) {
- threads[i].reset(RunInitOnceInNewThread());
- }
- for (int i = 0; i < 4; i++) {
- threads[i]->Join();
- }
- EXPECT_EQ(INIT_DONE, CurrentState());
-}
-
-GOOGLE_PROTOBUF_DECLARE_ONCE(multiple_threads_blocked_once1);
-GOOGLE_PROTOBUF_DECLARE_ONCE(multiple_threads_blocked_once2);
-
-TEST_F(OnceInitTest, MultipleThreadsBlocked) {
- SetOnces(&multiple_threads_blocked_once1, &multiple_threads_blocked_once2);
-
- scoped_ptr<TestThread> threads[8];
- EXPECT_EQ(INIT_NOT_STARTED, CurrentState());
-
- BlockInit();
- for (int i = 0; i < 4; i++) {
- threads[i].reset(RunInitOnceInNewThread());
- }
- for (int i = 4; i < 8; i++) {
- threads[i].reset(RunInitRecursiveOnceInNewThread());
- }
-
- WaitABit();
-
- // We should now have one thread blocked inside Init(), four blocked waiting
- // for Init() to complete, and three blocked waiting for InitRecursive() to
- // complete.
- EXPECT_EQ(INIT_STARTED, CurrentState());
- UnblockInit();
-
- for (int i = 0; i < 8; i++) {
- threads[i]->Join();
- }
- EXPECT_EQ(INIT_DONE, CurrentState());
-}
-
-} // anonymous namespace
-} // namespace protobuf
-} // namespace google
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 27849298..3aa6403b 100644
--- a/src/google/protobuf/stubs/port.h
+++ b/src/google/protobuf/stubs/port.h
@@ -91,9 +91,10 @@
// 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(__CYGWIN__)
+#elif defined(__GLIBC__) || defined(__BIONIC__) || defined(__CYGWIN__)
#include <byteswap.h> // IWYU pragma: export
#endif
@@ -209,6 +210,19 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF);
#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.
@@ -227,6 +241,13 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF);
#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).
@@ -359,12 +380,16 @@ inline void GOOGLE_UNALIGNED_STORE64(void *p, uint64 v) {
#define bswap_32(x) OSSwapInt32(x)
#define bswap_64(x) OSSwapInt64(x)
-#elif !defined(__GLIBC__) && !defined(__CYGWIN__)
+#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) |
@@ -372,6 +397,9 @@ 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) |
@@ -383,6 +411,7 @@ static inline uint64 bswap_64(uint64 x) {
((x & GOOGLE_ULONGLONG(0xFF00000000000000)) >> 56));
}
#define bswap_64(x) bswap_64(x)
+#endif
#endif
@@ -394,12 +423,10 @@ class Bits {
static uint32 Log2FloorNonZero(uint32 n) {
#if defined(__GNUC__)
return 31 ^ static_cast<uint32>(__builtin_clz(n));
-#elif defined(COMPILER_MSVC) && defined(_M_IX86)
- _asm {
- bsr ebx, n
- mov n, ebx
- }
- return n;
+#elif defined(_MSC_VER)
+ unsigned long where;
+ _BitScanReverse(&where, n);
+ return where;
#else
return Log2FloorNonZero_Portable(n);
#endif
@@ -414,6 +441,10 @@ class Bits {
// implementation instead.
#if defined(__GNUC__) && !defined(GOOGLE_PROTOBUF_USE_PORTABLE_LOG2)
return 63 ^ static_cast<uint32>(__builtin_clzll(n));
+#elif defined(_MSC_VER) && defined(_M_X64)
+ unsigned long where;
+ _BitScanReverse64(&where, n);
+ return where;
#else
return Log2FloorNonZero64_Portable(n);
#endif
diff --git a/src/google/protobuf/stubs/scoped_ptr.h b/src/google/protobuf/stubs/scoped_ptr.h
deleted file mode 100644
index 4423c118..00000000
--- a/src/google/protobuf/stubs/scoped_ptr.h
+++ /dev/null
@@ -1,236 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-#ifndef GOOGLE_PROTOBUF_STUBS_SCOPED_PTR_H_
-#define GOOGLE_PROTOBUF_STUBS_SCOPED_PTR_H_
-
-#include <google/protobuf/stubs/port.h>
-
-namespace google {
-namespace protobuf {
-
-// ===================================================================
-// from google3/base/scoped_ptr.h
-
-namespace internal {
-
-// This is an implementation designed to match the anticipated future TR2
-// implementation of the scoped_ptr class, and its closely-related brethren,
-// scoped_array, scoped_ptr_malloc, and make_scoped_ptr.
-
-template <class C> class scoped_ptr;
-template <class C> class scoped_array;
-
-// A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T>
-// automatically deletes the pointer it holds (if any).
-// That is, scoped_ptr<T> owns the T object that it points to.
-// Like a T*, a scoped_ptr<T> may hold either NULL or a pointer to a T object.
-//
-// The size of a scoped_ptr is small:
-// sizeof(scoped_ptr<C>) == sizeof(C*)
-template <class C>
-class scoped_ptr {
- public:
-
- // The element type
- typedef C element_type;
-
- // Constructor. Defaults to initializing with NULL.
- // There is no way to create an uninitialized scoped_ptr.
- // The input parameter must be allocated with new.
- explicit scoped_ptr(C* p = NULL) : ptr_(p) { }
-
- // Destructor. If there is a C object, delete it.
- // We don't need to test ptr_ == NULL because C++ does that for us.
- ~scoped_ptr() {
- enum { type_must_be_complete = sizeof(C) };
- delete ptr_;
- }
-
- // Reset. Deletes the current owned object, if any.
- // Then takes ownership of a new object, if given.
- // this->reset(this->get()) works.
- void reset(C* p = NULL) {
- if (p != ptr_) {
- enum { type_must_be_complete = sizeof(C) };
- delete ptr_;
- ptr_ = p;
- }
- }
-
- // Accessors to get the owned object.
- // operator* and operator-> will assert() if there is no current object.
- C& operator*() const {
- assert(ptr_ != NULL);
- return *ptr_;
- }
- C* operator->() const {
- assert(ptr_ != NULL);
- return ptr_;
- }
- C* get() const { return ptr_; }
-
- // Comparison operators.
- // These return whether two scoped_ptr refer to the same object, not just to
- // two different but equal objects.
- bool operator==(C* p) const { return ptr_ == p; }
- bool operator!=(C* p) const { return ptr_ != p; }
-
- // Swap two scoped pointers.
- void swap(scoped_ptr& p2) {
- C* tmp = ptr_;
- ptr_ = p2.ptr_;
- p2.ptr_ = tmp;
- }
-
- // Release a pointer.
- // The return value is the current pointer held by this object.
- // If this object holds a NULL pointer, the return value is NULL.
- // After this operation, this object will hold a NULL pointer,
- // and will not own the object any more.
- C* release() {
- C* retVal = ptr_;
- ptr_ = NULL;
- return retVal;
- }
-
- private:
- C* ptr_;
-
- // Forbid comparison of scoped_ptr types. If C2 != C, it totally doesn't
- // make sense, and if C2 == C, it still doesn't make sense because you should
- // never have the same object owned by two different scoped_ptrs.
- template <class C2> bool operator==(scoped_ptr<C2> const& p2) const;
- template <class C2> bool operator!=(scoped_ptr<C2> const& p2) const;
-
- // Disallow evil constructors
- scoped_ptr(const scoped_ptr&);
- void operator=(const scoped_ptr&);
-};
-
-// scoped_array<C> is like scoped_ptr<C>, except that the caller must allocate
-// with new [] and the destructor deletes objects with delete [].
-//
-// As with scoped_ptr<C>, a scoped_array<C> either points to an object
-// or is NULL. A scoped_array<C> owns the object that it points to.
-//
-// Size: sizeof(scoped_array<C>) == sizeof(C*)
-template <class C>
-class scoped_array {
- public:
-
- // The element type
- typedef C element_type;
-
- // Constructor. Defaults to initializing with NULL.
- // There is no way to create an uninitialized scoped_array.
- // The input parameter must be allocated with new [].
- explicit scoped_array(C* p = NULL) : array_(p) { }
-
- // Destructor. If there is a C object, delete it.
- // We don't need to test ptr_ == NULL because C++ does that for us.
- ~scoped_array() {
- enum { type_must_be_complete = sizeof(C) };
- delete[] array_;
- }
-
- // Reset. Deletes the current owned object, if any.
- // Then takes ownership of a new object, if given.
- // this->reset(this->get()) works.
- void reset(C* p = NULL) {
- if (p != array_) {
- enum { type_must_be_complete = sizeof(C) };
- delete[] array_;
- array_ = p;
- }
- }
-
- // Get one element of the current object.
- // Will assert() if there is no current object, or index i is negative.
- C& operator[](std::ptrdiff_t i) const {
- assert(i >= 0);
- assert(array_ != NULL);
- return array_[i];
- }
-
- // Get a pointer to the zeroth element of the current object.
- // If there is no current object, return NULL.
- C* get() const {
- return array_;
- }
-
- // Comparison operators.
- // These return whether two scoped_array refer to the same object, not just to
- // two different but equal objects.
- bool operator==(C* p) const { return array_ == p; }
- bool operator!=(C* p) const { return array_ != p; }
-
- // Swap two scoped arrays.
- void swap(scoped_array& p2) {
- C* tmp = array_;
- array_ = p2.array_;
- p2.array_ = tmp;
- }
-
- // Release an array.
- // The return value is the current pointer held by this object.
- // If this object holds a NULL pointer, the return value is NULL.
- // After this operation, this object will hold a NULL pointer,
- // and will not own the object any more.
- C* release() {
- C* retVal = array_;
- array_ = NULL;
- return retVal;
- }
-
- private:
- C* array_;
-
- // Forbid comparison of different scoped_array types.
- template <class C2> bool operator==(scoped_array<C2> const& p2) const;
- template <class C2> bool operator!=(scoped_array<C2> const& p2) const;
-
- // Disallow evil constructors
- scoped_array(const scoped_array&);
- void operator=(const scoped_array&);
-};
-
-} // namespace internal
-
-// We made these internal so that they would show up as such in the docs,
-// but we don't want to stick "internal::" in front of them everywhere.
-using internal::scoped_ptr;
-using internal::scoped_array;
-
-
-} // namespace protobuf
-} // namespace google
-
-#endif // GOOGLE_PROTOBUF_STUBS_SCOPED_PTR_H_
diff --git a/src/google/protobuf/stubs/shared_ptr.h b/src/google/protobuf/stubs/shared_ptr.h
deleted file mode 100644
index 7da114e9..00000000
--- a/src/google/protobuf/stubs/shared_ptr.h
+++ /dev/null
@@ -1,471 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2014 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.
-
-// from google3/util/gtl/shared_ptr.h
-
-#ifndef GOOGLE_PROTOBUF_STUBS_SHARED_PTR_H__
-#define GOOGLE_PROTOBUF_STUBS_SHARED_PTR_H__
-
-#include <google/protobuf/stubs/atomicops.h>
-
-#include <algorithm> // for swap
-#include <stddef.h>
-#include <memory>
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-// Alias to std::shared_ptr for any C++11 platform,
-// and for any supported MSVC compiler.
-#if !defined(UTIL_GTL_USE_STD_SHARED_PTR) && \
- (defined(COMPILER_MSVC) || defined(LANG_CXX11))
-#define UTIL_GTL_USE_STD_SHARED_PTR 1
-#endif
-
-#if defined(UTIL_GTL_USE_STD_SHARED_PTR) && UTIL_GTL_USE_STD_SHARED_PTR
-
-// These are transitional. They will be going away soon.
-// Please just #include <memory> and just type std::shared_ptr yourself, instead
-// of relying on this file.
-//
-// Migration doc: http://go/std-shared-ptr-lsc
-using std::enable_shared_from_this;
-using std::shared_ptr;
-using std::static_pointer_cast;
-using std::weak_ptr;
-
-#else // below, UTIL_GTL_USE_STD_SHARED_PTR not set or set to 0.
-
-// For everything else there is the google3 implementation.
-inline bool RefCountDec(volatile Atomic32 *ptr) {
- return Barrier_AtomicIncrement(ptr, -1) != 0;
-}
-
-inline void RefCountInc(volatile Atomic32 *ptr) {
- NoBarrier_AtomicIncrement(ptr, 1);
-}
-
-template <typename T> class shared_ptr;
-template <typename T> class weak_ptr;
-
-// This class is an internal implementation detail for shared_ptr. If two
-// shared_ptrs point to the same object, they also share a control block.
-// An "empty" shared_pointer refers to NULL and also has a NULL control block.
-// It contains all of the state that's needed for reference counting or any
-// other kind of resource management. In this implementation the control block
-// happens to consist of two atomic words, the reference count (the number
-// of shared_ptrs that share ownership of the object) and the weak count
-// (the number of weak_ptrs that observe the object, plus 1 if the
-// refcount is nonzero).
-//
-// The "plus 1" is to prevent a race condition in the shared_ptr and
-// weak_ptr destructors. We need to make sure the control block is
-// only deleted once, so we need to make sure that at most one
-// object sees the weak count decremented from 1 to 0.
-class SharedPtrControlBlock {
- template <typename T> friend class shared_ptr;
- template <typename T> friend class weak_ptr;
- private:
- SharedPtrControlBlock() : refcount_(1), weak_count_(1) { }
- Atomic32 refcount_;
- Atomic32 weak_count_;
-};
-
-// Forward declaration. The class is defined below.
-template <typename T> class enable_shared_from_this;
-
-template <typename T>
-class shared_ptr {
- template <typename U> friend class weak_ptr;
- public:
- typedef T element_type;
-
- shared_ptr() : ptr_(NULL), control_block_(NULL) {}
-
- explicit shared_ptr(T* ptr)
- : ptr_(ptr),
- control_block_(ptr != NULL ? new SharedPtrControlBlock : NULL) {
- // If p is non-null and T inherits from enable_shared_from_this, we
- // set up the data that shared_from_this needs.
- MaybeSetupWeakThis(ptr);
- }
-
- // Copy constructor: makes this object a copy of ptr, and increments
- // the reference count.
- template <typename U>
- shared_ptr(const shared_ptr<U>& ptr)
- : ptr_(NULL),
- control_block_(NULL) {
- Initialize(ptr);
- }
- // Need non-templated version to prevent the compiler-generated default
- shared_ptr(const shared_ptr<T>& ptr)
- : ptr_(NULL),
- control_block_(NULL) {
- Initialize(ptr);
- }
-
- // Assignment operator. Replaces the existing shared_ptr with ptr.
- // Increment ptr's reference count and decrement the one being replaced.
- template <typename U>
- shared_ptr<T>& operator=(const shared_ptr<U>& ptr) {
- if (ptr_ != ptr.ptr_) {
- shared_ptr<T> me(ptr); // will hold our previous state to be destroyed.
- swap(me);
- }
- return *this;
- }
-
- // Need non-templated version to prevent the compiler-generated default
- shared_ptr<T>& operator=(const shared_ptr<T>& ptr) {
- if (ptr_ != ptr.ptr_) {
- shared_ptr<T> me(ptr); // will hold our previous state to be destroyed.
- swap(me);
- }
- return *this;
- }
-
- // TODO(austern): Consider providing this constructor. The draft C++ standard
- // (20.8.10.2.1) includes it. However, it says that this constructor throws
- // a bad_weak_ptr exception when ptr is expired. Is it better to provide this
- // constructor and make it do something else, like fail with a CHECK, or to
- // leave this constructor out entirely?
- //
- // template <typename U>
- // shared_ptr(const weak_ptr<U>& ptr);
-
- ~shared_ptr() {
- if (ptr_ != NULL) {
- if (!RefCountDec(&control_block_->refcount_)) {
- delete ptr_;
-
- // weak_count_ is defined as the number of weak_ptrs that observe
- // ptr_, plus 1 if refcount_ is nonzero.
- if (!RefCountDec(&control_block_->weak_count_)) {
- delete control_block_;
- }
- }
- }
- }
-
- // Replaces underlying raw pointer with the one passed in. The reference
- // count is set to one (or zero if the pointer is NULL) for the pointer
- // being passed in and decremented for the one being replaced.
- //
- // If you have a compilation error with this code, make sure you aren't
- // passing NULL, nullptr, or 0 to this function. Call reset without an
- // argument to reset to a null ptr.
- template <typename Y>
- void reset(Y* p) {
- if (p != ptr_) {
- shared_ptr<T> tmp(p);
- tmp.swap(*this);
- }
- }
-
- void reset() {
- reset(static_cast<T*>(NULL));
- }
-
- // Exchanges the contents of this with the contents of r. This function
- // supports more efficient swapping since it eliminates the need for a
- // temporary shared_ptr object.
- void swap(shared_ptr<T>& r) {
- using std::swap; // http://go/using-std-swap
- swap(ptr_, r.ptr_);
- swap(control_block_, r.control_block_);
- }
-
- // The following function is useful for gaining access to the underlying
- // pointer when a shared_ptr remains in scope so the reference-count is
- // known to be > 0 (e.g. for parameter passing).
- T* get() const {
- return ptr_;
- }
-
- T& operator*() const {
- return *ptr_;
- }
-
- T* operator->() const {
- return ptr_;
- }
-
- long use_count() const {
- return control_block_ ? control_block_->refcount_ : 1;
- }
-
- bool unique() const {
- return use_count() == 1;
- }
-
- private:
- // If r is non-empty, initialize *this to share ownership with r,
- // increasing the underlying reference count.
- // If r is empty, *this remains empty.
- // Requires: this is empty, namely this->ptr_ == NULL.
- template <typename U>
- void Initialize(const shared_ptr<U>& r) {
- // This performs a static_cast on r.ptr_ to U*, which is a no-op since it
- // is already a U*. So initialization here requires that r.ptr_ is
- // implicitly convertible to T*.
- InitializeWithStaticCast<U>(r);
- }
-
- // Initializes *this as described in Initialize, but additionally performs a
- // static_cast from r.ptr_ (V*) to U*.
- // NOTE(gfc): We'd need a more general form to support const_pointer_cast and
- // dynamic_pointer_cast, but those operations are sufficiently discouraged
- // that supporting static_pointer_cast is sufficient.
- template <typename U, typename V>
- void InitializeWithStaticCast(const shared_ptr<V>& r) {
- if (r.control_block_ != NULL) {
- RefCountInc(&r.control_block_->refcount_);
-
- ptr_ = static_cast<U*>(r.ptr_);
- control_block_ = r.control_block_;
- }
- }
-
- // Helper function for the constructor that takes a raw pointer. If T
- // doesn't inherit from enable_shared_from_this<T> then we have nothing to
- // do, so this function is trivial and inline. The other version is declared
- // out of line, after the class definition of enable_shared_from_this.
- void MaybeSetupWeakThis(enable_shared_from_this<T>* ptr);
- void MaybeSetupWeakThis(...) { }
-
- T* ptr_;
- SharedPtrControlBlock* control_block_;
-
-#ifndef SWIG
- template <typename U>
- friend class shared_ptr;
-
- template <typename U, typename V>
- friend shared_ptr<U> static_pointer_cast(const shared_ptr<V>& rhs);
-#endif
-};
-
-// Matches the interface of std::swap as an aid to generic programming.
-template <typename T> void swap(shared_ptr<T>& r, shared_ptr<T>& s) {
- r.swap(s);
-}
-
-template <typename T, typename U>
-shared_ptr<T> static_pointer_cast(const shared_ptr<U>& rhs) {
- shared_ptr<T> lhs;
- lhs.template InitializeWithStaticCast<T>(rhs);
- return lhs;
-}
-
-// See comments at the top of the file for a description of why this
-// class exists, and the draft C++ standard (as of July 2009 the
-// latest draft is N2914) for the detailed specification.
-template <typename T>
-class weak_ptr {
- template <typename U> friend class weak_ptr;
- public:
- typedef T element_type;
-
- // Create an empty (i.e. already expired) weak_ptr.
- weak_ptr() : ptr_(NULL), control_block_(NULL) { }
-
- // Create a weak_ptr that observes the same object that ptr points
- // to. Note that there is no race condition here: we know that the
- // control block can't disappear while we're looking at it because
- // it is owned by at least one shared_ptr, ptr.
- template <typename U> weak_ptr(const shared_ptr<U>& ptr) {
- CopyFrom(ptr.ptr_, ptr.control_block_);
- }
-
- // Copy a weak_ptr. The object it points to might disappear, but we
- // don't care: we're only working with the control block, and it can't
- // disappear while we're looking at because it's owned by at least one
- // weak_ptr, ptr.
- template <typename U> weak_ptr(const weak_ptr<U>& ptr) {
- CopyFrom(ptr.ptr_, ptr.control_block_);
- }
-
- // Need non-templated version to prevent default copy constructor
- weak_ptr(const weak_ptr& ptr) {
- CopyFrom(ptr.ptr_, ptr.control_block_);
- }
-
- // Destroy the weak_ptr. If no shared_ptr owns the control block, and if
- // we are the last weak_ptr to own it, then it can be deleted. Note that
- // weak_count_ is defined as the number of weak_ptrs sharing this control
- // block, plus 1 if there are any shared_ptrs. We therefore know that it's
- // safe to delete the control block when weak_count_ reaches 0, without
- // having to perform any additional tests.
- ~weak_ptr() {
- if (control_block_ != NULL &&
- !RefCountDec(&control_block_->weak_count_)) {
- delete control_block_;
- }
- }
-
- weak_ptr& operator=(const weak_ptr& ptr) {
- if (&ptr != this) {
- weak_ptr tmp(ptr);
- tmp.swap(*this);
- }
- return *this;
- }
- template <typename U> weak_ptr& operator=(const weak_ptr<U>& ptr) {
- weak_ptr tmp(ptr);
- tmp.swap(*this);
- return *this;
- }
- template <typename U> weak_ptr& operator=(const shared_ptr<U>& ptr) {
- weak_ptr tmp(ptr);
- tmp.swap(*this);
- return *this;
- }
-
- void swap(weak_ptr& ptr) {
- using std::swap; // http://go/using-std-swap
- swap(ptr_, ptr.ptr_);
- swap(control_block_, ptr.control_block_);
- }
-
- void reset() {
- weak_ptr tmp;
- tmp.swap(*this);
- }
-
- // Return the number of shared_ptrs that own the object we are observing.
- // Note that this number can be 0 (if this pointer has expired).
- long use_count() const {
- return control_block_ != NULL ? control_block_->refcount_ : 0;
- }
-
- bool expired() const { return use_count() == 0; }
-
- // Return a shared_ptr that owns the object we are observing. If we
- // have expired, the shared_ptr will be empty. We have to be careful
- // about concurrency, though, since some other thread might be
- // destroying the last owning shared_ptr while we're in this
- // function. We want to increment the refcount only if it's nonzero
- // and get the new value, and we want that whole operation to be
- // atomic.
- shared_ptr<T> lock() const {
- shared_ptr<T> result;
- if (control_block_ != NULL) {
- Atomic32 old_refcount;
- do {
- old_refcount = control_block_->refcount_;
- if (old_refcount == 0)
- break;
- } while (old_refcount !=
- NoBarrier_CompareAndSwap(
- &control_block_->refcount_, old_refcount,
- old_refcount + 1));
- if (old_refcount > 0) {
- result.ptr_ = ptr_;
- result.control_block_ = control_block_;
- }
- }
-
- return result;
- }
-
- private:
- void CopyFrom(T* ptr, SharedPtrControlBlock* control_block) {
- ptr_ = ptr;
- control_block_ = control_block;
- if (control_block_ != NULL)
- RefCountInc(&control_block_->weak_count_);
- }
-
- private:
- element_type* ptr_;
- SharedPtrControlBlock* control_block_;
-};
-
-template <typename T> void swap(weak_ptr<T>& r, weak_ptr<T>& s) {
- r.swap(s);
-}
-
-// See comments at the top of the file for a description of why this class
-// exists, and section 20.8.10.5 of the draft C++ standard (as of July 2009
-// the latest draft is N2914) for the detailed specification.
-template <typename T>
-class enable_shared_from_this {
- friend class shared_ptr<T>;
- public:
- // Precondition: there must be a shared_ptr that owns *this and that was
- // created, directly or indirectly, from a raw pointer of type T*. (The
- // latter part of the condition is technical but not quite redundant; it
- // rules out some complicated uses involving inheritance hierarchies.)
- shared_ptr<T> shared_from_this() {
- // Behavior is undefined if the precondition isn't satisfied; we choose
- // to die with a CHECK failure.
- GOOGLE_CHECK(!weak_this_.expired()) << "No shared_ptr owns this object";
- return weak_this_.lock();
- }
- shared_ptr<const T> shared_from_this() const {
- GOOGLE_CHECK(!weak_this_.expired()) << "No shared_ptr owns this object";
- return weak_this_.lock();
- }
-
- protected:
- enable_shared_from_this() { }
- enable_shared_from_this(const enable_shared_from_this& other) { }
- enable_shared_from_this& operator=(const enable_shared_from_this& other) {
- return *this;
- }
- ~enable_shared_from_this() { }
-
- private:
- weak_ptr<T> weak_this_;
-};
-
-// This is a helper function called by shared_ptr's constructor from a raw
-// pointer. If T inherits from enable_shared_from_this<T>, it sets up
-// weak_this_ so that shared_from_this works correctly. If T does not inherit
-// from weak_this we get a different overload, defined inline, which does
-// nothing.
-template<typename T>
-void shared_ptr<T>::MaybeSetupWeakThis(enable_shared_from_this<T>* ptr) {
- if (ptr) {
- GOOGLE_CHECK(ptr->weak_this_.expired())
- << "Object already owned by a shared_ptr";
- ptr->weak_this_ = *this;
- }
-}
-
-#endif // UTIL_GTL_USE_STD_SHARED_PTR
-
-} // internal
-} // namespace protobuf
-} // namespace google
-
-#endif // GOOGLE_PROTOBUF_STUBS_SHARED_PTR_H__
diff --git a/src/google/protobuf/stubs/singleton.h b/src/google/protobuf/stubs/singleton.h
index 9301f549..2e6ccbdb 100644
--- a/src/google/protobuf/stubs/singleton.h
+++ b/src/google/protobuf/stubs/singleton.h
@@ -30,7 +30,6 @@
#ifndef GOOGLE_PROTOBUF_STUBS_SINGLETON_H__
#define GOOGLE_PROTOBUF_STUBS_SINGLETON_H__
-#include <google/protobuf/stubs/atomicops.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/once.h>
diff --git a/src/google/protobuf/stubs/strutil.cc b/src/google/protobuf/stubs/strutil.cc
index 28bcd3b2..552d416f 100644
--- a/src/google/protobuf/stubs/strutil.cc
+++ b/src/google/protobuf/stubs/strutil.cc
@@ -469,7 +469,7 @@ int UnescapeCEscapeString(const string& src, string* dest) {
int UnescapeCEscapeString(const string& src, string* dest,
std::vector<string> *errors) {
- scoped_array<char> unescaped(new char[src.size() + 1]);
+ std::unique_ptr<char[]> unescaped(new char[src.size() + 1]);
int len = UnescapeCEscapeSequences(src.c_str(), unescaped.get(), errors);
GOOGLE_CHECK(dest);
dest->assign(unescaped.get(), len);
@@ -477,7 +477,7 @@ int UnescapeCEscapeString(const string& src, string* dest,
}
string UnescapeCEscapeString(const string& src) {
- scoped_array<char> unescaped(new char[src.size() + 1]);
+ std::unique_ptr<char[]> unescaped(new char[src.size() + 1]);
int len = UnescapeCEscapeSequences(src.c_str(), unescaped.get(), NULL);
return string(unescaped.get(), len);
}
@@ -620,7 +620,7 @@ namespace strings {
string Utf8SafeCEscape(const string& src) {
const int dest_length = src.size() * 4 + 1; // Maximum possible expansion
- scoped_array<char> dest(new char[dest_length]);
+ std::unique_ptr<char[]> dest(new char[dest_length]);
const int len = CEscapeInternal(src.data(), src.size(),
dest.get(), dest_length, false, true);
GOOGLE_DCHECK_GE(len, 0);
@@ -629,7 +629,7 @@ string Utf8SafeCEscape(const string& src) {
string CHexEscape(const string& src) {
const int dest_length = src.size() * 4 + 1; // Maximum possible expansion
- scoped_array<char> dest(new char[dest_length]);
+ std::unique_ptr<char[]> dest(new char[dest_length]);
const int len = CEscapeInternal(src.data(), src.size(),
dest.get(), dest_length, true, false);
GOOGLE_DCHECK_GE(len, 0);
diff --git a/src/google/protobuf/stubs/type_traits.h b/src/google/protobuf/stubs/type_traits.h
deleted file mode 100644
index 3ab5ea7d..00000000
--- a/src/google/protobuf/stubs/type_traits.h
+++ /dev/null
@@ -1,364 +0,0 @@
-// Copyright (c) 2006, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (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: Matt Austern
-//
-// This code is compiled directly on many platforms, including client
-// platforms like Windows, Mac, and embedded systems. Before making
-// any changes here, make sure that you're not breaking any platforms.
-//
-// Define a small subset of tr1 type traits. The traits we define are:
-// enable_if
-// is_integral
-// is_floating_point
-// is_pointer
-// is_enum
-// is_reference
-// is_pod
-// has_trivial_constructor
-// has_trivial_copy
-// has_trivial_assign
-// has_trivial_destructor
-// remove_const
-// remove_volatile
-// remove_cv
-// remove_reference
-// add_reference
-// remove_pointer
-// is_same
-// is_convertible
-// We can add more type traits as required.
-
-#ifndef GOOGLE_PROTOBUF_TYPE_TRAITS_H_
-#define GOOGLE_PROTOBUF_TYPE_TRAITS_H_
-
-#include <cstddef> // for NULL
-#include <utility> // For pair
-
-#include <google/protobuf/stubs/template_util.h> // For true_type and false_type
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-template<typename B, typename D>
-struct is_base_of {
- typedef char (&yes)[1];
- typedef char (&no)[2];
-
- // BEGIN GOOGLE LOCAL MODIFICATION -- check is a #define on Mac.
- #undef check
- // END GOOGLE LOCAL MODIFICATION
-
- static yes check(const B*);
- static no check(const void*);
-
- enum {
- value = sizeof(check(static_cast<const D*>(NULL))) == sizeof(yes),
- };
-};
-
-template <bool cond, class T = void> struct enable_if;
-template <class T> struct is_integral;
-template <class T> struct is_floating_point;
-template <class T> struct is_pointer;
-// MSVC can't compile this correctly, and neither can gcc 3.3.5 (at least)
-#if !defined(_MSC_VER) && !(defined(__GNUC__) && __GNUC__ <= 3)
-// is_enum uses is_convertible, which is not available on MSVC.
-template <class T> struct is_enum;
-#endif
-template <class T> struct is_reference;
-template <class T> struct is_pod;
-template <class T> struct has_trivial_constructor;
-template <class T> struct has_trivial_copy;
-template <class T> struct has_trivial_assign;
-template <class T> struct has_trivial_destructor;
-template <class T> struct remove_const;
-template <class T> struct remove_volatile;
-template <class T> struct remove_cv;
-template <class T> struct remove_reference;
-template <class T> struct add_reference;
-template <class T> struct remove_pointer;
-template <class T, class U> struct is_same;
-#if !(defined(__GNUC__) && __GNUC__ <= 3)
-template <class From, class To> struct is_convertible;
-#endif
-
-// enable_if, equivalent semantics to c++11 std::enable_if, specifically:
-// "If B is true, the member typedef type shall equal T; otherwise, there
-// shall be no member typedef type."
-// Specified by 20.9.7.6 [Other transformations]
-
-template<bool cond, class T> struct enable_if { typedef T type; };
-template<class T> struct enable_if<false, T> {};
-// is_integral is false except for the built-in integer types. A
-// cv-qualified type is integral if and only if the underlying type is.
-template <class T> struct is_integral : false_type { };
-template<> struct is_integral<bool> : true_type { };
-template<> struct is_integral<char> : true_type { };
-template<> struct is_integral<unsigned char> : true_type { };
-template<> struct is_integral<signed char> : true_type { };
-#if defined(_MSC_VER)
-// wchar_t is not by default a distinct type from unsigned short in
-// Microsoft C.
-// See http://msdn2.microsoft.com/en-us/library/dh8che7s(VS.80).aspx
-template<> struct is_integral<__wchar_t> : true_type { };
-#else
-template<> struct is_integral<wchar_t> : true_type { };
-#endif
-template<> struct is_integral<short> : true_type { };
-template<> struct is_integral<unsigned short> : true_type { };
-template<> struct is_integral<int> : true_type { };
-template<> struct is_integral<unsigned int> : true_type { };
-template<> struct is_integral<long> : true_type { };
-template<> struct is_integral<unsigned long> : true_type { };
-#if defined(HAVE_LONG_LONG) || defined(_MSC_VER)
-template<> struct is_integral<long long> : true_type { };
-template<> struct is_integral<unsigned long long> : true_type { };
-#endif
-template <class T> struct is_integral<const T> : is_integral<T> { };
-template <class T> struct is_integral<volatile T> : is_integral<T> { };
-template <class T> struct is_integral<const volatile T> : is_integral<T> { };
-
-// is_floating_point is false except for the built-in floating-point types.
-// A cv-qualified type is integral if and only if the underlying type is.
-template <class T> struct is_floating_point : false_type { };
-template<> struct is_floating_point<float> : true_type { };
-template<> struct is_floating_point<double> : true_type { };
-template<> struct is_floating_point<long double> : true_type { };
-template <class T> struct is_floating_point<const T>
- : is_floating_point<T> { };
-template <class T> struct is_floating_point<volatile T>
- : is_floating_point<T> { };
-template <class T> struct is_floating_point<const volatile T>
- : is_floating_point<T> { };
-
-// is_pointer is false except for pointer types. A cv-qualified type (e.g.
-// "int* const", as opposed to "int const*") is cv-qualified if and only if
-// the underlying type is.
-template <class T> struct is_pointer : false_type { };
-template <class T> struct is_pointer<T*> : true_type { };
-template <class T> struct is_pointer<const T> : is_pointer<T> { };
-template <class T> struct is_pointer<volatile T> : is_pointer<T> { };
-template <class T> struct is_pointer<const volatile T> : is_pointer<T> { };
-
-#if !defined(_MSC_VER) && !(defined(__GNUC__) && __GNUC__ <= 3)
-
-namespace type_traits_internal {
-
-template <class T> struct is_class_or_union {
- template <class U> static small_ tester(void (U::*)());
- template <class U> static big_ tester(...);
- static const bool value = sizeof(tester<T>(0)) == sizeof(small_);
-};
-
-// is_convertible chokes if the first argument is an array. That's why
-// we use add_reference here.
-template <bool NotUnum, class T> struct is_enum_impl
- : is_convertible<typename add_reference<T>::type, int> { };
-
-template <class T> struct is_enum_impl<true, T> : false_type { };
-
-} // namespace type_traits_internal
-
-// Specified by TR1 [4.5.1] primary type categories.
-
-// Implementation note:
-//
-// Each type is either void, integral, floating point, array, pointer,
-// reference, member object pointer, member function pointer, enum,
-// union or class. Out of these, only integral, floating point, reference,
-// class and enum types are potentially convertible to int. Therefore,
-// if a type is not a reference, integral, floating point or class and
-// is convertible to int, it's a enum. Adding cv-qualification to a type
-// does not change whether it's an enum.
-//
-// Is-convertible-to-int check is done only if all other checks pass,
-// because it can't be used with some types (e.g. void or classes with
-// inaccessible conversion operators).
-template <class T> struct is_enum
- : type_traits_internal::is_enum_impl<
- is_same<T, void>::value ||
- is_integral<T>::value ||
- is_floating_point<T>::value ||
- is_reference<T>::value ||
- type_traits_internal::is_class_or_union<T>::value,
- T> { };
-
-template <class T> struct is_enum<const T> : is_enum<T> { };
-template <class T> struct is_enum<volatile T> : is_enum<T> { };
-template <class T> struct is_enum<const volatile T> : is_enum<T> { };
-
-#endif
-
-// is_reference is false except for reference types.
-template<typename T> struct is_reference : false_type {};
-template<typename T> struct is_reference<T&> : true_type {};
-
-
-// We can't get is_pod right without compiler help, so fail conservatively.
-// We will assume it's false except for arithmetic types, enumerations,
-// pointers and cv-qualified versions thereof. Note that std::pair<T,U>
-// is not a POD even if T and U are PODs.
-template <class T> struct is_pod
- : integral_constant<bool, (is_integral<T>::value ||
- is_floating_point<T>::value ||
-#if !defined(_MSC_VER) && !(defined(__GNUC__) && __GNUC__ <= 3)
- // is_enum is not available on MSVC.
- is_enum<T>::value ||
-#endif
- is_pointer<T>::value)> { };
-template <class T> struct is_pod<const T> : is_pod<T> { };
-template <class T> struct is_pod<volatile T> : is_pod<T> { };
-template <class T> struct is_pod<const volatile T> : is_pod<T> { };
-
-
-// We can't get has_trivial_constructor right without compiler help, so
-// fail conservatively. We will assume it's false except for: (1) types
-// for which is_pod is true. (2) std::pair of types with trivial
-// constructors. (3) array of a type with a trivial constructor.
-// (4) const versions thereof.
-template <class T> struct has_trivial_constructor : is_pod<T> { };
-template <class T, class U> struct has_trivial_constructor<std::pair<T, U> >
- : integral_constant<bool,
- (has_trivial_constructor<T>::value &&
- has_trivial_constructor<U>::value)> { };
-template <class A, int N> struct has_trivial_constructor<A[N]>
- : has_trivial_constructor<A> { };
-template <class T> struct has_trivial_constructor<const T>
- : has_trivial_constructor<T> { };
-
-// We can't get has_trivial_copy right without compiler help, so fail
-// conservatively. We will assume it's false except for: (1) types
-// for which is_pod is true. (2) std::pair of types with trivial copy
-// constructors. (3) array of a type with a trivial copy constructor.
-// (4) const versions thereof.
-template <class T> struct has_trivial_copy : is_pod<T> { };
-template <class T, class U> struct has_trivial_copy<std::pair<T, U> >
- : integral_constant<bool,
- (has_trivial_copy<T>::value &&
- has_trivial_copy<U>::value)> { };
-template <class A, int N> struct has_trivial_copy<A[N]>
- : has_trivial_copy<A> { };
-template <class T> struct has_trivial_copy<const T> : has_trivial_copy<T> { };
-
-// We can't get has_trivial_assign right without compiler help, so fail
-// conservatively. We will assume it's false except for: (1) types
-// for which is_pod is true. (2) std::pair of types with trivial copy
-// constructors. (3) array of a type with a trivial assign constructor.
-template <class T> struct has_trivial_assign : is_pod<T> { };
-template <class T, class U> struct has_trivial_assign<std::pair<T, U> >
- : integral_constant<bool,
- (has_trivial_assign<T>::value &&
- has_trivial_assign<U>::value)> { };
-template <class A, int N> struct has_trivial_assign<A[N]>
- : has_trivial_assign<A> { };
-
-// We can't get has_trivial_destructor right without compiler help, so
-// fail conservatively. We will assume it's false except for: (1) types
-// for which is_pod is true. (2) std::pair of types with trivial
-// destructors. (3) array of a type with a trivial destructor.
-// (4) const versions thereof.
-template <class T> struct has_trivial_destructor : is_pod<T> { };
-template <class T, class U> struct has_trivial_destructor<std::pair<T, U> >
- : integral_constant<bool,
- (has_trivial_destructor<T>::value &&
- has_trivial_destructor<U>::value)> { };
-template <class A, int N> struct has_trivial_destructor<A[N]>
- : has_trivial_destructor<A> { };
-template <class T> struct has_trivial_destructor<const T>
- : has_trivial_destructor<T> { };
-
-// Specified by TR1 [4.7.1]
-template<typename T> struct remove_const { typedef T type; };
-template<typename T> struct remove_const<T const> { typedef T type; };
-template<typename T> struct remove_volatile { typedef T type; };
-template<typename T> struct remove_volatile<T volatile> { typedef T type; };
-template<typename T> struct remove_cv {
- typedef typename remove_const<typename remove_volatile<T>::type>::type type;
-};
-
-
-// Specified by TR1 [4.7.2] Reference modifications.
-template<typename T> struct remove_reference { typedef T type; };
-template<typename T> struct remove_reference<T&> { typedef T type; };
-
-template <typename T> struct add_reference { typedef T& type; };
-template <typename T> struct add_reference<T&> { typedef T& type; };
-
-// Specified by TR1 [4.7.4] Pointer modifications.
-template<typename T> struct remove_pointer { typedef T type; };
-template<typename T> struct remove_pointer<T*> { typedef T type; };
-template<typename T> struct remove_pointer<T* const> { typedef T type; };
-template<typename T> struct remove_pointer<T* volatile> { typedef T type; };
-template<typename T> struct remove_pointer<T* const volatile> {
- typedef T type; };
-
-// Specified by TR1 [4.6] Relationships between types
-template<typename T, typename U> struct is_same : public false_type { };
-template<typename T> struct is_same<T, T> : public true_type { };
-
-// Specified by TR1 [4.6] Relationships between types
-#if !(defined(__GNUC__) && __GNUC__ <= 3)
-namespace type_traits_internal {
-
-// This class is an implementation detail for is_convertible, and you
-// don't need to know how it works to use is_convertible. For those
-// who care: we declare two different functions, one whose argument is
-// of type To and one with a variadic argument list. We give them
-// return types of different size, so we can use sizeof to trick the
-// compiler into telling us which function it would have chosen if we
-// had called it with an argument of type From. See Alexandrescu's
-// _Modern C++ Design_ for more details on this sort of trick.
-
-template <typename From, typename To>
-struct ConvertHelper {
- static small_ Test(To);
- static big_ Test(...);
- static From Create();
- enum {
- value = sizeof(Test(Create())) == sizeof(small_)
- };
-};
-} // namespace type_traits_internal
-
-// Inherits from true_type if From is convertible to To, false_type otherwise.
-template <typename From, typename To>
-struct is_convertible
- : integral_constant<bool,
- type_traits_internal::ConvertHelper<From, To>::value> {
-};
-#endif
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#endif // GOOGLE_PROTOBUF_TYPE_TRAITS_H_
diff --git a/src/google/protobuf/stubs/type_traits_unittest.cc b/src/google/protobuf/stubs/type_traits_unittest.cc
deleted file mode 100644
index 0e54b952..00000000
--- a/src/google/protobuf/stubs/type_traits_unittest.cc
+++ /dev/null
@@ -1,631 +0,0 @@
-// Copyright (c) 2006, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (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: Matt Austern
-
-#include <google/protobuf/stubs/type_traits.h>
-
-#include <stdlib.h> // for exit()
-#include <stdio.h>
-#include <string>
-#include <vector>
-
-#include <google/protobuf/testing/googletest.h>
-#include <gtest/gtest.h>
-
-typedef int int32;
-// IBM AIX typedefs `int64` in `sys/inttypes.h`, included transitively above.
-#ifndef _AIX
-typedef long int64;
-#endif
-
-using std::string;
-using std::vector;
-using std::pair;
-
-
-// This assertion produces errors like "error: invalid use of
-// incomplete type 'struct <unnamed>::AssertTypesEq<const int, int>'"
-// when it fails.
-template<typename T, typename U> struct AssertTypesEq;
-template<typename T> struct AssertTypesEq<T, T> {};
-#define COMPILE_ASSERT_TYPES_EQ(T, U) static_cast<void>(AssertTypesEq<T, U>())
-
-// A user-defined POD type.
-struct A {
- int n_;
-};
-
-// A user-defined non-POD type with a trivial copy constructor.
-class B {
- public:
- explicit B(int n) : n_(n) { }
- private:
- int n_;
-};
-
-// Another user-defined non-POD type with a trivial copy constructor.
-// We will explicitly declare C to have a trivial copy constructor
-// by specializing has_trivial_copy.
-class C {
- public:
- explicit C(int n) : n_(n) { }
- private:
- int n_;
-};
-
-namespace google {
-namespace protobuf {
-namespace internal {
-template<> struct has_trivial_copy<C> : true_type { };
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-// Another user-defined non-POD type with a trivial assignment operator.
-// We will explicitly declare C to have a trivial assignment operator
-// by specializing has_trivial_assign.
-class D {
- public:
- explicit D(int n) : n_(n) { }
- private:
- int n_;
-};
-
-namespace google {
-namespace protobuf {
-namespace internal {
-template<> struct has_trivial_assign<D> : true_type { };
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-// Another user-defined non-POD type with a trivial constructor.
-// We will explicitly declare E to have a trivial constructor
-// by specializing has_trivial_constructor.
-class E {
- public:
- int n_;
-};
-
-namespace google {
-namespace protobuf {
-namespace internal {
-template<> struct has_trivial_constructor<E> : true_type { };
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-// Another user-defined non-POD type with a trivial destructor.
-// We will explicitly declare E to have a trivial destructor
-// by specializing has_trivial_destructor.
-class F {
- public:
- explicit F(int n) : n_(n) { }
- private:
- int n_;
-};
-
-namespace google {
-namespace protobuf {
-namespace internal {
-template<> struct has_trivial_destructor<F> : true_type { };
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-enum G {};
-
-union H {};
-
-class I {
- public:
- operator int() const;
-};
-
-class J {
- private:
- operator int() const;
-};
-
-namespace google {
-namespace protobuf {
-namespace internal {
-namespace {
-
-// A base class and a derived class that inherits from it, used for
-// testing conversion type traits.
-class Base {
- public:
- virtual ~Base() { }
-};
-
-class Derived : public Base {
-};
-
-TEST(TypeTraitsTest, TestIsInteger) {
- // Verify that is_integral is true for all integer types.
- EXPECT_TRUE(is_integral<bool>::value);
- EXPECT_TRUE(is_integral<char>::value);
- EXPECT_TRUE(is_integral<unsigned char>::value);
- EXPECT_TRUE(is_integral<signed char>::value);
- EXPECT_TRUE(is_integral<wchar_t>::value);
- EXPECT_TRUE(is_integral<int>::value);
- EXPECT_TRUE(is_integral<unsigned int>::value);
- EXPECT_TRUE(is_integral<short>::value);
- EXPECT_TRUE(is_integral<unsigned short>::value);
- EXPECT_TRUE(is_integral<long>::value);
- EXPECT_TRUE(is_integral<unsigned long>::value);
-
- // Verify that is_integral is false for a few non-integer types.
- EXPECT_FALSE(is_integral<void>::value);
- EXPECT_FALSE(is_integral<float>::value);
- EXPECT_FALSE(is_integral<string>::value);
- EXPECT_FALSE(is_integral<int*>::value);
- EXPECT_FALSE(is_integral<A>::value);
- EXPECT_FALSE((is_integral<pair<int, int> >::value));
-
- // Verify that cv-qualified integral types are still integral, and
- // cv-qualified non-integral types are still non-integral.
- EXPECT_TRUE(is_integral<const char>::value);
- EXPECT_TRUE(is_integral<volatile bool>::value);
- EXPECT_TRUE(is_integral<const volatile unsigned int>::value);
- EXPECT_FALSE(is_integral<const float>::value);
- EXPECT_FALSE(is_integral<int* volatile>::value);
- EXPECT_FALSE(is_integral<const volatile string>::value);
-}
-
-TEST(TypeTraitsTest, TestIsFloating) {
- // Verify that is_floating_point is true for all floating-point types.
- EXPECT_TRUE(is_floating_point<float>::value);
- EXPECT_TRUE(is_floating_point<double>::value);
- EXPECT_TRUE(is_floating_point<long double>::value);
-
- // Verify that is_floating_point is false for a few non-float types.
- EXPECT_FALSE(is_floating_point<void>::value);
- EXPECT_FALSE(is_floating_point<long>::value);
- EXPECT_FALSE(is_floating_point<string>::value);
- EXPECT_FALSE(is_floating_point<float*>::value);
- EXPECT_FALSE(is_floating_point<A>::value);
- EXPECT_FALSE((is_floating_point<pair<int, int> >::value));
-
- // Verify that cv-qualified floating point types are still floating, and
- // cv-qualified non-floating types are still non-floating.
- EXPECT_TRUE(is_floating_point<const float>::value);
- EXPECT_TRUE(is_floating_point<volatile double>::value);
- EXPECT_TRUE(is_floating_point<const volatile long double>::value);
- EXPECT_FALSE(is_floating_point<const int>::value);
- EXPECT_FALSE(is_floating_point<volatile string>::value);
- EXPECT_FALSE(is_floating_point<const volatile char>::value);
-}
-
-TEST(TypeTraitsTest, TestIsPointer) {
- // Verify that is_pointer is true for some pointer types.
- EXPECT_TRUE(is_pointer<int*>::value);
- EXPECT_TRUE(is_pointer<void*>::value);
- EXPECT_TRUE(is_pointer<string*>::value);
- EXPECT_TRUE(is_pointer<const void*>::value);
- EXPECT_TRUE(is_pointer<volatile float* const*>::value);
-
- // Verify that is_pointer is false for some non-pointer types.
- EXPECT_FALSE(is_pointer<void>::value);
- EXPECT_FALSE(is_pointer<float&>::value);
- EXPECT_FALSE(is_pointer<long>::value);
- EXPECT_FALSE(is_pointer<vector<int*> >::value);
- EXPECT_FALSE(is_pointer<int[5]>::value);
-
- // A function pointer is a pointer, but a function type, or a function
- // reference type, is not.
- EXPECT_TRUE(is_pointer<int (*)(int x)>::value);
- EXPECT_FALSE(is_pointer<void(char x)>::value);
- EXPECT_FALSE(is_pointer<double (&)(string x)>::value);
-
- // Verify that is_pointer<T> is true for some cv-qualified pointer types,
- // and false for some cv-qualified non-pointer types.
- EXPECT_TRUE(is_pointer<int* const>::value);
- EXPECT_TRUE(is_pointer<const void* volatile>::value);
- EXPECT_TRUE(is_pointer<char** const volatile>::value);
- EXPECT_FALSE(is_pointer<const int>::value);
- EXPECT_FALSE(is_pointer<volatile std::vector<int*> >::value);
- EXPECT_FALSE(is_pointer<const volatile double>::value);
-}
-
-TEST(TypeTraitsTest, TestIsEnum) {
-// is_enum isn't supported on MSVC or gcc 3.x
-#if !defined(_MSC_VER) && !(defined(__GNUC__) && __GNUC__ <= 3)
- // Verify that is_enum is true for enum types.
- EXPECT_TRUE(is_enum<G>::value);
- EXPECT_TRUE(is_enum<const G>::value);
- EXPECT_TRUE(is_enum<volatile G>::value);
- EXPECT_TRUE(is_enum<const volatile G>::value);
-
- // Verify that is_enum is false for a few non-enum types.
- EXPECT_FALSE(is_enum<void>::value);
- EXPECT_FALSE(is_enum<G&>::value);
- EXPECT_FALSE(is_enum<G[1]>::value);
- EXPECT_FALSE(is_enum<const G[1]>::value);
- EXPECT_FALSE(is_enum<G[]>::value);
- EXPECT_FALSE(is_enum<int>::value);
- EXPECT_FALSE(is_enum<float>::value);
- EXPECT_FALSE(is_enum<A>::value);
- EXPECT_FALSE(is_enum<A*>::value);
- EXPECT_FALSE(is_enum<const A>::value);
- EXPECT_FALSE(is_enum<H>::value);
- EXPECT_FALSE(is_enum<I>::value);
- EXPECT_FALSE(is_enum<J>::value);
- EXPECT_FALSE(is_enum<void()>::value);
- EXPECT_FALSE(is_enum<void(*)()>::value);
- EXPECT_FALSE(is_enum<int A::*>::value);
- EXPECT_FALSE(is_enum<void (A::*)()>::value);
-#endif
-}
-
-TEST(TypeTraitsTest, TestIsReference) {
- // Verifies that is_reference is true for all reference types.
- typedef float& RefFloat;
- EXPECT_TRUE(is_reference<float&>::value);
- EXPECT_TRUE(is_reference<const int&>::value);
- EXPECT_TRUE(is_reference<const int*&>::value);
- EXPECT_TRUE(is_reference<int (&)(bool)>::value);
- EXPECT_TRUE(is_reference<RefFloat>::value);
- EXPECT_TRUE(is_reference<const RefFloat>::value);
- EXPECT_TRUE(is_reference<volatile RefFloat>::value);
- EXPECT_TRUE(is_reference<const volatile RefFloat>::value);
-
-
- // Verifies that is_reference is false for all non-reference types.
- EXPECT_FALSE(is_reference<float>::value);
- EXPECT_FALSE(is_reference<const float>::value);
- EXPECT_FALSE(is_reference<volatile float>::value);
- EXPECT_FALSE(is_reference<const volatile float>::value);
- EXPECT_FALSE(is_reference<const int*>::value);
- EXPECT_FALSE(is_reference<int()>::value);
- EXPECT_FALSE(is_reference<void(*)(const char&)>::value);
-}
-
-TEST(TypeTraitsTest, TestAddReference) {
- COMPILE_ASSERT_TYPES_EQ(int&, add_reference<int>::type);
- COMPILE_ASSERT_TYPES_EQ(const int&, add_reference<const int>::type);
- COMPILE_ASSERT_TYPES_EQ(volatile int&,
- add_reference<volatile int>::type);
- COMPILE_ASSERT_TYPES_EQ(const volatile int&,
- add_reference<const volatile int>::type);
- COMPILE_ASSERT_TYPES_EQ(int&, add_reference<int&>::type);
- COMPILE_ASSERT_TYPES_EQ(const int&, add_reference<const int&>::type);
- COMPILE_ASSERT_TYPES_EQ(volatile int&,
- add_reference<volatile int&>::type);
- COMPILE_ASSERT_TYPES_EQ(const volatile int&,
- add_reference<const volatile int&>::type);
-}
-
-TEST(TypeTraitsTest, TestIsPod) {
- // Verify that arithmetic types and pointers are marked as PODs.
- EXPECT_TRUE(is_pod<bool>::value);
- EXPECT_TRUE(is_pod<char>::value);
- EXPECT_TRUE(is_pod<unsigned char>::value);
- EXPECT_TRUE(is_pod<signed char>::value);
- EXPECT_TRUE(is_pod<wchar_t>::value);
- EXPECT_TRUE(is_pod<int>::value);
- EXPECT_TRUE(is_pod<unsigned int>::value);
- EXPECT_TRUE(is_pod<short>::value);
- EXPECT_TRUE(is_pod<unsigned short>::value);
- EXPECT_TRUE(is_pod<long>::value);
- EXPECT_TRUE(is_pod<unsigned long>::value);
- EXPECT_TRUE(is_pod<float>::value);
- EXPECT_TRUE(is_pod<double>::value);
- EXPECT_TRUE(is_pod<long double>::value);
- EXPECT_TRUE(is_pod<string*>::value);
- EXPECT_TRUE(is_pod<A*>::value);
- EXPECT_TRUE(is_pod<const B*>::value);
- EXPECT_TRUE(is_pod<C**>::value);
- EXPECT_TRUE(is_pod<const int>::value);
- EXPECT_TRUE(is_pod<char* volatile>::value);
- EXPECT_TRUE(is_pod<const volatile double>::value);
-#if !defined(_MSC_VER) && !(defined(__GNUC__) && __GNUC__ <= 3)
- EXPECT_TRUE(is_pod<G>::value);
- EXPECT_TRUE(is_pod<const G>::value);
- EXPECT_TRUE(is_pod<volatile G>::value);
- EXPECT_TRUE(is_pod<const volatile G>::value);
-#endif
-
- // Verify that some non-POD types are not marked as PODs.
- EXPECT_FALSE(is_pod<void>::value);
- EXPECT_FALSE(is_pod<string>::value);
- EXPECT_FALSE((is_pod<pair<int, int> >::value));
- EXPECT_FALSE(is_pod<A>::value);
- EXPECT_FALSE(is_pod<B>::value);
- EXPECT_FALSE(is_pod<C>::value);
- EXPECT_FALSE(is_pod<const string>::value);
- EXPECT_FALSE(is_pod<volatile A>::value);
- EXPECT_FALSE(is_pod<const volatile B>::value);
-}
-
-TEST(TypeTraitsTest, TestHasTrivialConstructor) {
- // Verify that arithmetic types and pointers have trivial constructors.
- EXPECT_TRUE(has_trivial_constructor<bool>::value);
- EXPECT_TRUE(has_trivial_constructor<char>::value);
- EXPECT_TRUE(has_trivial_constructor<unsigned char>::value);
- EXPECT_TRUE(has_trivial_constructor<signed char>::value);
- EXPECT_TRUE(has_trivial_constructor<wchar_t>::value);
- EXPECT_TRUE(has_trivial_constructor<int>::value);
- EXPECT_TRUE(has_trivial_constructor<unsigned int>::value);
- EXPECT_TRUE(has_trivial_constructor<short>::value);
- EXPECT_TRUE(has_trivial_constructor<unsigned short>::value);
- EXPECT_TRUE(has_trivial_constructor<long>::value);
- EXPECT_TRUE(has_trivial_constructor<unsigned long>::value);
- EXPECT_TRUE(has_trivial_constructor<float>::value);
- EXPECT_TRUE(has_trivial_constructor<double>::value);
- EXPECT_TRUE(has_trivial_constructor<long double>::value);
- EXPECT_TRUE(has_trivial_constructor<string*>::value);
- EXPECT_TRUE(has_trivial_constructor<A*>::value);
- EXPECT_TRUE(has_trivial_constructor<const B*>::value);
- EXPECT_TRUE(has_trivial_constructor<C**>::value);
-
- // Verify that pairs and arrays of such types have trivial
- // constructors.
- typedef int int10[10];
- EXPECT_TRUE((has_trivial_constructor<pair<int, char*> >::value));
- EXPECT_TRUE(has_trivial_constructor<int10>::value);
-
- // Verify that pairs of types without trivial constructors
- // are not marked as trivial.
- EXPECT_FALSE((has_trivial_constructor<pair<int, string> >::value));
- EXPECT_FALSE((has_trivial_constructor<pair<string, int> >::value));
-
- // Verify that types without trivial constructors are
- // correctly marked as such.
- EXPECT_FALSE(has_trivial_constructor<string>::value);
- EXPECT_FALSE(has_trivial_constructor<vector<int> >::value);
-
- // Verify that E, which we have declared to have a trivial
- // constructor, is correctly marked as such.
- EXPECT_TRUE(has_trivial_constructor<E>::value);
-}
-
-TEST(TypeTraitsTest, TestHasTrivialCopy) {
- // Verify that arithmetic types and pointers have trivial copy
- // constructors.
- EXPECT_TRUE(has_trivial_copy<bool>::value);
- EXPECT_TRUE(has_trivial_copy<char>::value);
- EXPECT_TRUE(has_trivial_copy<unsigned char>::value);
- EXPECT_TRUE(has_trivial_copy<signed char>::value);
- EXPECT_TRUE(has_trivial_copy<wchar_t>::value);
- EXPECT_TRUE(has_trivial_copy<int>::value);
- EXPECT_TRUE(has_trivial_copy<unsigned int>::value);
- EXPECT_TRUE(has_trivial_copy<short>::value);
- EXPECT_TRUE(has_trivial_copy<unsigned short>::value);
- EXPECT_TRUE(has_trivial_copy<long>::value);
- EXPECT_TRUE(has_trivial_copy<unsigned long>::value);
- EXPECT_TRUE(has_trivial_copy<float>::value);
- EXPECT_TRUE(has_trivial_copy<double>::value);
- EXPECT_TRUE(has_trivial_copy<long double>::value);
- EXPECT_TRUE(has_trivial_copy<string*>::value);
- EXPECT_TRUE(has_trivial_copy<A*>::value);
- EXPECT_TRUE(has_trivial_copy<const B*>::value);
- EXPECT_TRUE(has_trivial_copy<C**>::value);
-
- // Verify that pairs and arrays of such types have trivial
- // copy constructors.
- typedef int int10[10];
- EXPECT_TRUE((has_trivial_copy<pair<int, char*> >::value));
- EXPECT_TRUE(has_trivial_copy<int10>::value);
-
- // Verify that pairs of types without trivial copy constructors
- // are not marked as trivial.
- EXPECT_FALSE((has_trivial_copy<pair<int, string> >::value));
- EXPECT_FALSE((has_trivial_copy<pair<string, int> >::value));
-
- // Verify that types without trivial copy constructors are
- // correctly marked as such.
- EXPECT_FALSE(has_trivial_copy<string>::value);
- EXPECT_FALSE(has_trivial_copy<vector<int> >::value);
-
- // Verify that C, which we have declared to have a trivial
- // copy constructor, is correctly marked as such.
- EXPECT_TRUE(has_trivial_copy<C>::value);
-}
-
-TEST(TypeTraitsTest, TestHasTrivialAssign) {
- // Verify that arithmetic types and pointers have trivial assignment
- // operators.
- EXPECT_TRUE(has_trivial_assign<bool>::value);
- EXPECT_TRUE(has_trivial_assign<char>::value);
- EXPECT_TRUE(has_trivial_assign<unsigned char>::value);
- EXPECT_TRUE(has_trivial_assign<signed char>::value);
- EXPECT_TRUE(has_trivial_assign<wchar_t>::value);
- EXPECT_TRUE(has_trivial_assign<int>::value);
- EXPECT_TRUE(has_trivial_assign<unsigned int>::value);
- EXPECT_TRUE(has_trivial_assign<short>::value);
- EXPECT_TRUE(has_trivial_assign<unsigned short>::value);
- EXPECT_TRUE(has_trivial_assign<long>::value);
- EXPECT_TRUE(has_trivial_assign<unsigned long>::value);
- EXPECT_TRUE(has_trivial_assign<float>::value);
- EXPECT_TRUE(has_trivial_assign<double>::value);
- EXPECT_TRUE(has_trivial_assign<long double>::value);
- EXPECT_TRUE(has_trivial_assign<string*>::value);
- EXPECT_TRUE(has_trivial_assign<A*>::value);
- EXPECT_TRUE(has_trivial_assign<const B*>::value);
- EXPECT_TRUE(has_trivial_assign<C**>::value);
-
- // Verify that pairs and arrays of such types have trivial
- // assignment operators.
- typedef int int10[10];
- EXPECT_TRUE((has_trivial_assign<pair<int, char*> >::value));
- EXPECT_TRUE(has_trivial_assign<int10>::value);
-
- // Verify that pairs of types without trivial assignment operators
- // are not marked as trivial.
- EXPECT_FALSE((has_trivial_assign<pair<int, string> >::value));
- EXPECT_FALSE((has_trivial_assign<pair<string, int> >::value));
-
- // Verify that types without trivial assignment operators are
- // correctly marked as such.
- EXPECT_FALSE(has_trivial_assign<string>::value);
- EXPECT_FALSE(has_trivial_assign<vector<int> >::value);
-
- // Verify that D, which we have declared to have a trivial
- // assignment operator, is correctly marked as such.
- EXPECT_TRUE(has_trivial_assign<D>::value);
-}
-
-TEST(TypeTraitsTest, TestHasTrivialDestructor) {
- // Verify that arithmetic types and pointers have trivial destructors.
- EXPECT_TRUE(has_trivial_destructor<bool>::value);
- EXPECT_TRUE(has_trivial_destructor<char>::value);
- EXPECT_TRUE(has_trivial_destructor<unsigned char>::value);
- EXPECT_TRUE(has_trivial_destructor<signed char>::value);
- EXPECT_TRUE(has_trivial_destructor<wchar_t>::value);
- EXPECT_TRUE(has_trivial_destructor<int>::value);
- EXPECT_TRUE(has_trivial_destructor<unsigned int>::value);
- EXPECT_TRUE(has_trivial_destructor<short>::value);
- EXPECT_TRUE(has_trivial_destructor<unsigned short>::value);
- EXPECT_TRUE(has_trivial_destructor<long>::value);
- EXPECT_TRUE(has_trivial_destructor<unsigned long>::value);
- EXPECT_TRUE(has_trivial_destructor<float>::value);
- EXPECT_TRUE(has_trivial_destructor<double>::value);
- EXPECT_TRUE(has_trivial_destructor<long double>::value);
- EXPECT_TRUE(has_trivial_destructor<string*>::value);
- EXPECT_TRUE(has_trivial_destructor<A*>::value);
- EXPECT_TRUE(has_trivial_destructor<const B*>::value);
- EXPECT_TRUE(has_trivial_destructor<C**>::value);
-
- // Verify that pairs and arrays of such types have trivial
- // destructors.
- typedef int int10[10];
- EXPECT_TRUE((has_trivial_destructor<pair<int, char*> >::value));
- EXPECT_TRUE(has_trivial_destructor<int10>::value);
-
- // Verify that pairs of types without trivial destructors
- // are not marked as trivial.
- EXPECT_FALSE((has_trivial_destructor<pair<int, string> >::value));
- EXPECT_FALSE((has_trivial_destructor<pair<string, int> >::value));
-
- // Verify that types without trivial destructors are
- // correctly marked as such.
- EXPECT_FALSE(has_trivial_destructor<string>::value);
- EXPECT_FALSE(has_trivial_destructor<vector<int> >::value);
-
- // Verify that F, which we have declared to have a trivial
- // destructor, is correctly marked as such.
- EXPECT_TRUE(has_trivial_destructor<F>::value);
-}
-
-// Tests remove_pointer.
-TEST(TypeTraitsTest, TestRemovePointer) {
- COMPILE_ASSERT_TYPES_EQ(int, remove_pointer<int>::type);
- COMPILE_ASSERT_TYPES_EQ(int, remove_pointer<int*>::type);
- COMPILE_ASSERT_TYPES_EQ(const int, remove_pointer<const int*>::type);
- COMPILE_ASSERT_TYPES_EQ(int, remove_pointer<int* const>::type);
- COMPILE_ASSERT_TYPES_EQ(int, remove_pointer<int* volatile>::type);
-}
-
-TEST(TypeTraitsTest, TestRemoveConst) {
- COMPILE_ASSERT_TYPES_EQ(int, remove_const<int>::type);
- COMPILE_ASSERT_TYPES_EQ(int, remove_const<const int>::type);
- COMPILE_ASSERT_TYPES_EQ(int *, remove_const<int * const>::type);
- // TR1 examples.
- COMPILE_ASSERT_TYPES_EQ(const int *, remove_const<const int *>::type);
- COMPILE_ASSERT_TYPES_EQ(volatile int,
- remove_const<const volatile int>::type);
-}
-
-TEST(TypeTraitsTest, TestRemoveVolatile) {
- COMPILE_ASSERT_TYPES_EQ(int, remove_volatile<int>::type);
- COMPILE_ASSERT_TYPES_EQ(int, remove_volatile<volatile int>::type);
- COMPILE_ASSERT_TYPES_EQ(int *, remove_volatile<int * volatile>::type);
- // TR1 examples.
- COMPILE_ASSERT_TYPES_EQ(volatile int *,
- remove_volatile<volatile int *>::type);
- COMPILE_ASSERT_TYPES_EQ(const int,
- remove_volatile<const volatile int>::type);
-}
-
-TEST(TypeTraitsTest, TestRemoveCV) {
- COMPILE_ASSERT_TYPES_EQ(int, remove_cv<int>::type);
- COMPILE_ASSERT_TYPES_EQ(int, remove_cv<volatile int>::type);
- COMPILE_ASSERT_TYPES_EQ(int, remove_cv<const int>::type);
- COMPILE_ASSERT_TYPES_EQ(int *, remove_cv<int * const volatile>::type);
- // TR1 examples.
- COMPILE_ASSERT_TYPES_EQ(const volatile int *,
- remove_cv<const volatile int *>::type);
- COMPILE_ASSERT_TYPES_EQ(int,
- remove_cv<const volatile int>::type);
-}
-
-TEST(TypeTraitsTest, TestRemoveReference) {
- COMPILE_ASSERT_TYPES_EQ(int, remove_reference<int>::type);
- COMPILE_ASSERT_TYPES_EQ(int, remove_reference<int&>::type);
- COMPILE_ASSERT_TYPES_EQ(const int, remove_reference<const int&>::type);
- COMPILE_ASSERT_TYPES_EQ(int*, remove_reference<int * &>::type);
-}
-
-TEST(TypeTraitsTest, TestIsSame) {
- EXPECT_TRUE((is_same<int32, int32>::value));
- EXPECT_FALSE((is_same<int32, int64>::value));
- EXPECT_FALSE((is_same<int64, int32>::value));
- EXPECT_FALSE((is_same<int, const int>::value));
-
- EXPECT_TRUE((is_same<void, void>::value));
- EXPECT_FALSE((is_same<void, int>::value));
- EXPECT_FALSE((is_same<int, void>::value));
-
- EXPECT_TRUE((is_same<int*, int*>::value));
- EXPECT_TRUE((is_same<void*, void*>::value));
- EXPECT_FALSE((is_same<int*, void*>::value));
- EXPECT_FALSE((is_same<void*, int*>::value));
- EXPECT_FALSE((is_same<void*, const void*>::value));
- EXPECT_FALSE((is_same<void*, void* const>::value));
-
- EXPECT_TRUE((is_same<Base*, Base*>::value));
- EXPECT_TRUE((is_same<Derived*, Derived*>::value));
- EXPECT_FALSE((is_same<Base*, Derived*>::value));
- EXPECT_FALSE((is_same<Derived*, Base*>::value));
-}
-
-TEST(TypeTraitsTest, TestConvertible) {
-#if !(defined(__GNUC__) && __GNUC__ <= 3)
- EXPECT_TRUE((is_convertible<int, int>::value));
- EXPECT_TRUE((is_convertible<int, long>::value));
- EXPECT_TRUE((is_convertible<long, int>::value));
-
- EXPECT_TRUE((is_convertible<int*, void*>::value));
- EXPECT_FALSE((is_convertible<void*, int*>::value));
-
- EXPECT_TRUE((is_convertible<Derived*, Base*>::value));
- EXPECT_FALSE((is_convertible<Base*, Derived*>::value));
- EXPECT_TRUE((is_convertible<Derived*, const Base*>::value));
- EXPECT_FALSE((is_convertible<const Derived*, Base*>::value));
-#endif
-}
-
-} // anonymous namespace
-} // namespace internal
-} // namespace protobuf
-} // namespace google
diff --git a/src/google/protobuf/test_util.cc b/src/google/protobuf/test_util.cc
index 4e02a85d..795cb6ae 100644
--- a/src/google/protobuf/test_util.cc
+++ b/src/google/protobuf/test_util.cc
@@ -39,3312 +39,9 @@
#endif
#include <google/protobuf/test_util.h>
-#include <google/protobuf/descriptor.h>
-#include <google/protobuf/message.h>
-
-#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/testing/googletest.h>
-#include <gtest/gtest.h>
namespace google {
namespace protobuf {
-void TestUtil::SetAllFields(unittest::TestAllTypes* message) {
- SetOptionalFields(message);
- AddRepeatedFields1(message);
- AddRepeatedFields2(message);
- SetDefaultFields(message);
- SetOneofFields(message);
-}
-
-void TestUtil::SetOptionalFields(unittest::TestAllTypes* message) {
- message->set_optional_int32 (101);
- message->set_optional_int64 (102);
- message->set_optional_uint32 (103);
- message->set_optional_uint64 (104);
- message->set_optional_sint32 (105);
- message->set_optional_sint64 (106);
- message->set_optional_fixed32 (107);
- message->set_optional_fixed64 (108);
- message->set_optional_sfixed32(109);
- message->set_optional_sfixed64(110);
- message->set_optional_float (111);
- message->set_optional_double (112);
- message->set_optional_bool (true);
- message->set_optional_string ("115");
- message->set_optional_bytes ("116");
-
- message->mutable_optionalgroup ()->set_a(117);
- message->mutable_optional_nested_message ()->set_bb(118);
- message->mutable_optional_foreign_message ()->set_c(119);
- message->mutable_optional_import_message ()->set_d(120);
- message->mutable_optional_public_import_message()->set_e(126);
- message->mutable_optional_lazy_message ()->set_bb(127);
-
- message->set_optional_nested_enum (unittest::TestAllTypes::BAZ);
- message->set_optional_foreign_enum(unittest::FOREIGN_BAZ );
- message->set_optional_import_enum (unittest_import::IMPORT_BAZ);
-
- // StringPiece and Cord fields are only accessible via reflection in the
- // open source release; see comments in compiler/cpp/string_field.cc.
-#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
- message->GetReflection()->SetString(
- message,
- message->GetDescriptor()->FindFieldByName("optional_string_piece"),
- "124");
- message->GetReflection()->SetString(
- message,
- message->GetDescriptor()->FindFieldByName("optional_cord"),
- "125");
-#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::AddRepeatedFields1(unittest::TestAllTypes* message) {
- message->add_repeated_int32 (201);
- message->add_repeated_int64 (202);
- message->add_repeated_uint32 (203);
- message->add_repeated_uint64 (204);
- message->add_repeated_sint32 (205);
- message->add_repeated_sint64 (206);
- message->add_repeated_fixed32 (207);
- message->add_repeated_fixed64 (208);
- message->add_repeated_sfixed32(209);
- message->add_repeated_sfixed64(210);
- message->add_repeated_float (211);
- message->add_repeated_double (212);
- message->add_repeated_bool (true);
- message->add_repeated_string ("215");
- message->add_repeated_bytes ("216");
-
- message->add_repeatedgroup ()->set_a(217);
- message->add_repeated_nested_message ()->set_bb(218);
- message->add_repeated_foreign_message()->set_c(219);
- message->add_repeated_import_message ()->set_d(220);
- message->add_repeated_lazy_message ()->set_bb(227);
-
- message->add_repeated_nested_enum (unittest::TestAllTypes::BAR);
- message->add_repeated_foreign_enum(unittest::FOREIGN_BAR );
- message->add_repeated_import_enum (unittest_import::IMPORT_BAR);
-
-#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
- message->GetReflection()->AddString(
- message,
- message->GetDescriptor()->FindFieldByName("repeated_string_piece"),
- "224");
- message->GetReflection()->AddString(
- message,
- message->GetDescriptor()->FindFieldByName("repeated_cord"),
- "225");
-#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
-}
-
-void TestUtil::AddRepeatedFields2(unittest::TestAllTypes* message) {
- // Add a second one of each field.
- message->add_repeated_int32 (301);
- message->add_repeated_int64 (302);
- message->add_repeated_uint32 (303);
- message->add_repeated_uint64 (304);
- message->add_repeated_sint32 (305);
- message->add_repeated_sint64 (306);
- message->add_repeated_fixed32 (307);
- message->add_repeated_fixed64 (308);
- message->add_repeated_sfixed32(309);
- message->add_repeated_sfixed64(310);
- message->add_repeated_float (311);
- message->add_repeated_double (312);
- message->add_repeated_bool (false);
- message->add_repeated_string ("315");
- message->add_repeated_bytes ("316");
-
- message->add_repeatedgroup ()->set_a(317);
- message->add_repeated_nested_message ()->set_bb(318);
- message->add_repeated_foreign_message()->set_c(319);
- message->add_repeated_import_message ()->set_d(320);
- message->add_repeated_lazy_message ()->set_bb(327);
-
- message->add_repeated_nested_enum (unittest::TestAllTypes::BAZ);
- message->add_repeated_foreign_enum(unittest::FOREIGN_BAZ );
- message->add_repeated_import_enum (unittest_import::IMPORT_BAZ);
-
-#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
- message->GetReflection()->AddString(
- message,
- message->GetDescriptor()->FindFieldByName("repeated_string_piece"),
- "324");
- message->GetReflection()->AddString(
- message,
- message->GetDescriptor()->FindFieldByName("repeated_cord"),
- "325");
-#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::SetDefaultFields(unittest::TestAllTypes* message) {
- message->set_default_int32 (401);
- message->set_default_int64 (402);
- message->set_default_uint32 (403);
- message->set_default_uint64 (404);
- message->set_default_sint32 (405);
- message->set_default_sint64 (406);
- message->set_default_fixed32 (407);
- message->set_default_fixed64 (408);
- message->set_default_sfixed32(409);
- message->set_default_sfixed64(410);
- message->set_default_float (411);
- message->set_default_double (412);
- message->set_default_bool (false);
- message->set_default_string ("415");
- message->set_default_bytes ("416");
-
- message->set_default_nested_enum (unittest::TestAllTypes::FOO);
- message->set_default_foreign_enum(unittest::FOREIGN_FOO );
- message->set_default_import_enum (unittest_import::IMPORT_FOO);
-
-#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
- message->GetReflection()->SetString(
- message,
- message->GetDescriptor()->FindFieldByName("default_string_piece"),
- "424");
- message->GetReflection()->SetString(
- message,
- message->GetDescriptor()->FindFieldByName("default_cord"),
- "425");
-#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ModifyRepeatedFields(unittest::TestAllTypes* message) {
- message->set_repeated_int32 (1, 501);
- message->set_repeated_int64 (1, 502);
- message->set_repeated_uint32 (1, 503);
- message->set_repeated_uint64 (1, 504);
- message->set_repeated_sint32 (1, 505);
- message->set_repeated_sint64 (1, 506);
- message->set_repeated_fixed32 (1, 507);
- message->set_repeated_fixed64 (1, 508);
- message->set_repeated_sfixed32(1, 509);
- message->set_repeated_sfixed64(1, 510);
- message->set_repeated_float (1, 511);
- message->set_repeated_double (1, 512);
- message->set_repeated_bool (1, true);
- message->set_repeated_string (1, "515");
- message->set_repeated_bytes (1, "516");
-
- message->mutable_repeatedgroup (1)->set_a(517);
- message->mutable_repeated_nested_message (1)->set_bb(518);
- message->mutable_repeated_foreign_message(1)->set_c(519);
- message->mutable_repeated_import_message (1)->set_d(520);
- message->mutable_repeated_lazy_message (1)->set_bb(527);
-
- message->set_repeated_nested_enum (1, unittest::TestAllTypes::FOO);
- message->set_repeated_foreign_enum(1, unittest::FOREIGN_FOO );
- message->set_repeated_import_enum (1, unittest_import::IMPORT_FOO);
-
-#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
- message->GetReflection()->SetRepeatedString(
- message,
- message->GetDescriptor()->FindFieldByName("repeated_string_piece"),
- 1, "524");
- message->GetReflection()->SetRepeatedString(
- message,
- message->GetDescriptor()->FindFieldByName("repeated_cord"),
- 1, "525");
-#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
-}
-
-// ------------------------------------------------------------------
-void TestUtil::SetOneofFields(unittest::TestAllTypes* message) {
- message->set_oneof_uint32(601);
- message->mutable_oneof_nested_message()->set_bb(602);
- message->set_oneof_string("603");
- message->set_oneof_bytes("604");
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ExpectAllFieldsSet(const unittest::TestAllTypes& message) {
- EXPECT_TRUE(message.has_optional_int32 ());
- EXPECT_TRUE(message.has_optional_int64 ());
- EXPECT_TRUE(message.has_optional_uint32 ());
- EXPECT_TRUE(message.has_optional_uint64 ());
- EXPECT_TRUE(message.has_optional_sint32 ());
- EXPECT_TRUE(message.has_optional_sint64 ());
- EXPECT_TRUE(message.has_optional_fixed32 ());
- EXPECT_TRUE(message.has_optional_fixed64 ());
- EXPECT_TRUE(message.has_optional_sfixed32());
- EXPECT_TRUE(message.has_optional_sfixed64());
- EXPECT_TRUE(message.has_optional_float ());
- EXPECT_TRUE(message.has_optional_double ());
- EXPECT_TRUE(message.has_optional_bool ());
- EXPECT_TRUE(message.has_optional_string ());
- EXPECT_TRUE(message.has_optional_bytes ());
-
- EXPECT_TRUE(message.has_optionalgroup ());
- EXPECT_TRUE(message.has_optional_nested_message ());
- EXPECT_TRUE(message.has_optional_foreign_message ());
- EXPECT_TRUE(message.has_optional_import_message ());
- EXPECT_TRUE(message.has_optional_public_import_message());
- EXPECT_TRUE(message.has_optional_lazy_message ());
-
- EXPECT_TRUE(message.optionalgroup ().has_a());
- EXPECT_TRUE(message.optional_nested_message ().has_bb());
- EXPECT_TRUE(message.optional_foreign_message ().has_c());
- EXPECT_TRUE(message.optional_import_message ().has_d());
- EXPECT_TRUE(message.optional_public_import_message().has_e());
- EXPECT_TRUE(message.optional_lazy_message ().has_bb());
-
- EXPECT_TRUE(message.has_optional_nested_enum ());
- EXPECT_TRUE(message.has_optional_foreign_enum());
- EXPECT_TRUE(message.has_optional_import_enum ());
-
-#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
- EXPECT_TRUE(message.has_optional_string_piece());
- EXPECT_TRUE(message.has_optional_cord());
-#endif
-
- EXPECT_EQ(101 , message.optional_int32 ());
- EXPECT_EQ(102 , message.optional_int64 ());
- EXPECT_EQ(103 , message.optional_uint32 ());
- EXPECT_EQ(104 , message.optional_uint64 ());
- EXPECT_EQ(105 , message.optional_sint32 ());
- EXPECT_EQ(106 , message.optional_sint64 ());
- EXPECT_EQ(107 , message.optional_fixed32 ());
- EXPECT_EQ(108 , message.optional_fixed64 ());
- EXPECT_EQ(109 , message.optional_sfixed32());
- EXPECT_EQ(110 , message.optional_sfixed64());
- EXPECT_EQ(111 , message.optional_float ());
- EXPECT_EQ(112 , message.optional_double ());
- EXPECT_TRUE( message.optional_bool ());
- EXPECT_EQ("115", message.optional_string ());
- EXPECT_EQ("116", message.optional_bytes ());
-
- EXPECT_EQ(117, message.optionalgroup ().a());
- EXPECT_EQ(118, message.optional_nested_message ().bb());
- EXPECT_EQ(119, message.optional_foreign_message ().c());
- EXPECT_EQ(120, message.optional_import_message ().d());
- EXPECT_EQ(126, message.optional_public_import_message ().e());
- EXPECT_EQ(127, message.optional_lazy_message ().bb());
-
- EXPECT_EQ(unittest::TestAllTypes::BAZ, message.optional_nested_enum ());
- EXPECT_EQ(unittest::FOREIGN_BAZ , message.optional_foreign_enum());
- EXPECT_EQ(unittest_import::IMPORT_BAZ, message.optional_import_enum ());
-
-
- // -----------------------------------------------------------------
-
- ASSERT_EQ(2, message.repeated_int32_size ());
- ASSERT_EQ(2, message.repeated_int64_size ());
- ASSERT_EQ(2, message.repeated_uint32_size ());
- ASSERT_EQ(2, message.repeated_uint64_size ());
- ASSERT_EQ(2, message.repeated_sint32_size ());
- ASSERT_EQ(2, message.repeated_sint64_size ());
- ASSERT_EQ(2, message.repeated_fixed32_size ());
- ASSERT_EQ(2, message.repeated_fixed64_size ());
- ASSERT_EQ(2, message.repeated_sfixed32_size());
- ASSERT_EQ(2, message.repeated_sfixed64_size());
- ASSERT_EQ(2, message.repeated_float_size ());
- ASSERT_EQ(2, message.repeated_double_size ());
- ASSERT_EQ(2, message.repeated_bool_size ());
- ASSERT_EQ(2, message.repeated_string_size ());
- ASSERT_EQ(2, message.repeated_bytes_size ());
-
- ASSERT_EQ(2, message.repeatedgroup_size ());
- ASSERT_EQ(2, message.repeated_nested_message_size ());
- ASSERT_EQ(2, message.repeated_foreign_message_size());
- ASSERT_EQ(2, message.repeated_import_message_size ());
- ASSERT_EQ(2, message.repeated_lazy_message_size ());
- ASSERT_EQ(2, message.repeated_nested_enum_size ());
- ASSERT_EQ(2, message.repeated_foreign_enum_size ());
- ASSERT_EQ(2, message.repeated_import_enum_size ());
-
-#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
- ASSERT_EQ(2, message.repeated_string_piece_size());
- ASSERT_EQ(2, message.repeated_cord_size());
-#endif
-
- EXPECT_EQ(201 , message.repeated_int32 (0));
- EXPECT_EQ(202 , message.repeated_int64 (0));
- EXPECT_EQ(203 , message.repeated_uint32 (0));
- EXPECT_EQ(204 , message.repeated_uint64 (0));
- EXPECT_EQ(205 , message.repeated_sint32 (0));
- EXPECT_EQ(206 , message.repeated_sint64 (0));
- EXPECT_EQ(207 , message.repeated_fixed32 (0));
- EXPECT_EQ(208 , message.repeated_fixed64 (0));
- EXPECT_EQ(209 , message.repeated_sfixed32(0));
- EXPECT_EQ(210 , message.repeated_sfixed64(0));
- EXPECT_EQ(211 , message.repeated_float (0));
- EXPECT_EQ(212 , message.repeated_double (0));
- EXPECT_TRUE( message.repeated_bool (0));
- EXPECT_EQ("215", message.repeated_string (0));
- EXPECT_EQ("216", message.repeated_bytes (0));
-
- EXPECT_EQ(217, message.repeatedgroup (0).a());
- EXPECT_EQ(218, message.repeated_nested_message (0).bb());
- EXPECT_EQ(219, message.repeated_foreign_message(0).c());
- EXPECT_EQ(220, message.repeated_import_message (0).d());
- EXPECT_EQ(227, message.repeated_lazy_message (0).bb());
-
-
- EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (0));
- EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(0));
- EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (0));
-
- EXPECT_EQ(301 , message.repeated_int32 (1));
- EXPECT_EQ(302 , message.repeated_int64 (1));
- EXPECT_EQ(303 , message.repeated_uint32 (1));
- EXPECT_EQ(304 , message.repeated_uint64 (1));
- EXPECT_EQ(305 , message.repeated_sint32 (1));
- EXPECT_EQ(306 , message.repeated_sint64 (1));
- EXPECT_EQ(307 , message.repeated_fixed32 (1));
- EXPECT_EQ(308 , message.repeated_fixed64 (1));
- EXPECT_EQ(309 , message.repeated_sfixed32(1));
- EXPECT_EQ(310 , message.repeated_sfixed64(1));
- EXPECT_EQ(311 , message.repeated_float (1));
- EXPECT_EQ(312 , message.repeated_double (1));
- EXPECT_FALSE( message.repeated_bool (1));
- EXPECT_EQ("315", message.repeated_string (1));
- EXPECT_EQ("316", message.repeated_bytes (1));
-
- EXPECT_EQ(317, message.repeatedgroup (1).a());
- EXPECT_EQ(318, message.repeated_nested_message (1).bb());
- EXPECT_EQ(319, message.repeated_foreign_message(1).c());
- EXPECT_EQ(320, message.repeated_import_message (1).d());
- EXPECT_EQ(327, message.repeated_lazy_message (1).bb());
-
- EXPECT_EQ(unittest::TestAllTypes::BAZ, message.repeated_nested_enum (1));
- EXPECT_EQ(unittest::FOREIGN_BAZ , message.repeated_foreign_enum(1));
- EXPECT_EQ(unittest_import::IMPORT_BAZ, message.repeated_import_enum (1));
-
-
- // -----------------------------------------------------------------
-
- EXPECT_TRUE(message.has_default_int32 ());
- EXPECT_TRUE(message.has_default_int64 ());
- EXPECT_TRUE(message.has_default_uint32 ());
- EXPECT_TRUE(message.has_default_uint64 ());
- EXPECT_TRUE(message.has_default_sint32 ());
- EXPECT_TRUE(message.has_default_sint64 ());
- EXPECT_TRUE(message.has_default_fixed32 ());
- EXPECT_TRUE(message.has_default_fixed64 ());
- EXPECT_TRUE(message.has_default_sfixed32());
- EXPECT_TRUE(message.has_default_sfixed64());
- EXPECT_TRUE(message.has_default_float ());
- EXPECT_TRUE(message.has_default_double ());
- EXPECT_TRUE(message.has_default_bool ());
- EXPECT_TRUE(message.has_default_string ());
- EXPECT_TRUE(message.has_default_bytes ());
-
- EXPECT_TRUE(message.has_default_nested_enum ());
- EXPECT_TRUE(message.has_default_foreign_enum());
- EXPECT_TRUE(message.has_default_import_enum ());
-
-
- EXPECT_EQ(401 , message.default_int32 ());
- EXPECT_EQ(402 , message.default_int64 ());
- EXPECT_EQ(403 , message.default_uint32 ());
- EXPECT_EQ(404 , message.default_uint64 ());
- EXPECT_EQ(405 , message.default_sint32 ());
- EXPECT_EQ(406 , message.default_sint64 ());
- EXPECT_EQ(407 , message.default_fixed32 ());
- EXPECT_EQ(408 , message.default_fixed64 ());
- EXPECT_EQ(409 , message.default_sfixed32());
- EXPECT_EQ(410 , message.default_sfixed64());
- EXPECT_EQ(411 , message.default_float ());
- EXPECT_EQ(412 , message.default_double ());
- EXPECT_FALSE( message.default_bool ());
- EXPECT_EQ("415", message.default_string ());
- EXPECT_EQ("416", message.default_bytes ());
-
- EXPECT_EQ(unittest::TestAllTypes::FOO, message.default_nested_enum ());
- EXPECT_EQ(unittest::FOREIGN_FOO , message.default_foreign_enum());
- EXPECT_EQ(unittest_import::IMPORT_FOO, message.default_import_enum ());
-
-
- EXPECT_FALSE(message.has_oneof_uint32 ());
- EXPECT_FALSE(message.has_oneof_nested_message());
- EXPECT_FALSE(message.has_oneof_string ());
- EXPECT_TRUE(message.has_oneof_bytes ());
-
- EXPECT_EQ("604", message.oneof_bytes());
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ExpectClear(const unittest::TestAllTypes& message) {
- // has_blah() should initially be false for all optional fields.
- EXPECT_FALSE(message.has_optional_int32 ());
- EXPECT_FALSE(message.has_optional_int64 ());
- EXPECT_FALSE(message.has_optional_uint32 ());
- EXPECT_FALSE(message.has_optional_uint64 ());
- EXPECT_FALSE(message.has_optional_sint32 ());
- EXPECT_FALSE(message.has_optional_sint64 ());
- EXPECT_FALSE(message.has_optional_fixed32 ());
- EXPECT_FALSE(message.has_optional_fixed64 ());
- EXPECT_FALSE(message.has_optional_sfixed32());
- EXPECT_FALSE(message.has_optional_sfixed64());
- EXPECT_FALSE(message.has_optional_float ());
- EXPECT_FALSE(message.has_optional_double ());
- EXPECT_FALSE(message.has_optional_bool ());
- EXPECT_FALSE(message.has_optional_string ());
- EXPECT_FALSE(message.has_optional_bytes ());
-
- EXPECT_FALSE(message.has_optionalgroup ());
- EXPECT_FALSE(message.has_optional_nested_message ());
- EXPECT_FALSE(message.has_optional_foreign_message ());
- EXPECT_FALSE(message.has_optional_import_message ());
- EXPECT_FALSE(message.has_optional_public_import_message());
- EXPECT_FALSE(message.has_optional_lazy_message ());
-
- EXPECT_FALSE(message.has_optional_nested_enum ());
- EXPECT_FALSE(message.has_optional_foreign_enum());
- EXPECT_FALSE(message.has_optional_import_enum ());
-
- EXPECT_FALSE(message.has_optional_string_piece());
- EXPECT_FALSE(message.has_optional_cord());
-
- // Optional fields without defaults are set to zero or something like it.
- EXPECT_EQ(0 , message.optional_int32 ());
- EXPECT_EQ(0 , message.optional_int64 ());
- EXPECT_EQ(0 , message.optional_uint32 ());
- EXPECT_EQ(0 , message.optional_uint64 ());
- EXPECT_EQ(0 , message.optional_sint32 ());
- EXPECT_EQ(0 , message.optional_sint64 ());
- EXPECT_EQ(0 , message.optional_fixed32 ());
- EXPECT_EQ(0 , message.optional_fixed64 ());
- EXPECT_EQ(0 , message.optional_sfixed32());
- EXPECT_EQ(0 , message.optional_sfixed64());
- EXPECT_EQ(0 , message.optional_float ());
- EXPECT_EQ(0 , message.optional_double ());
- EXPECT_FALSE( message.optional_bool ());
- EXPECT_EQ("" , message.optional_string ());
- EXPECT_EQ("" , message.optional_bytes ());
-
- // Embedded messages should also be clear.
- EXPECT_FALSE(message.optionalgroup ().has_a());
- EXPECT_FALSE(message.optional_nested_message ().has_bb());
- EXPECT_FALSE(message.optional_foreign_message ().has_c());
- EXPECT_FALSE(message.optional_import_message ().has_d());
- EXPECT_FALSE(message.optional_public_import_message().has_e());
- EXPECT_FALSE(message.optional_lazy_message ().has_bb());
-
- EXPECT_EQ(0, message.optionalgroup ().a());
- EXPECT_EQ(0, message.optional_nested_message ().bb());
- EXPECT_EQ(0, message.optional_foreign_message ().c());
- EXPECT_EQ(0, message.optional_import_message ().d());
- EXPECT_EQ(0, message.optional_public_import_message().e());
- EXPECT_EQ(0, message.optional_lazy_message ().bb());
-
- // Enums without defaults are set to the first value in the enum.
- EXPECT_EQ(unittest::TestAllTypes::FOO, message.optional_nested_enum ());
- EXPECT_EQ(unittest::FOREIGN_FOO , message.optional_foreign_enum());
- EXPECT_EQ(unittest_import::IMPORT_FOO, message.optional_import_enum ());
-
-
- // Repeated fields are empty.
- EXPECT_EQ(0, message.repeated_int32_size ());
- EXPECT_EQ(0, message.repeated_int64_size ());
- EXPECT_EQ(0, message.repeated_uint32_size ());
- EXPECT_EQ(0, message.repeated_uint64_size ());
- EXPECT_EQ(0, message.repeated_sint32_size ());
- EXPECT_EQ(0, message.repeated_sint64_size ());
- EXPECT_EQ(0, message.repeated_fixed32_size ());
- EXPECT_EQ(0, message.repeated_fixed64_size ());
- EXPECT_EQ(0, message.repeated_sfixed32_size());
- EXPECT_EQ(0, message.repeated_sfixed64_size());
- EXPECT_EQ(0, message.repeated_float_size ());
- EXPECT_EQ(0, message.repeated_double_size ());
- EXPECT_EQ(0, message.repeated_bool_size ());
- EXPECT_EQ(0, message.repeated_string_size ());
- EXPECT_EQ(0, message.repeated_bytes_size ());
-
- EXPECT_EQ(0, message.repeatedgroup_size ());
- EXPECT_EQ(0, message.repeated_nested_message_size ());
- EXPECT_EQ(0, message.repeated_foreign_message_size());
- EXPECT_EQ(0, message.repeated_import_message_size ());
- EXPECT_EQ(0, message.repeated_lazy_message_size ());
- EXPECT_EQ(0, message.repeated_nested_enum_size ());
- EXPECT_EQ(0, message.repeated_foreign_enum_size ());
- EXPECT_EQ(0, message.repeated_import_enum_size ());
-
- EXPECT_EQ(0, message.repeated_string_piece_size());
- EXPECT_EQ(0, message.repeated_cord_size());
-
- // has_blah() should also be false for all default fields.
- EXPECT_FALSE(message.has_default_int32 ());
- EXPECT_FALSE(message.has_default_int64 ());
- EXPECT_FALSE(message.has_default_uint32 ());
- EXPECT_FALSE(message.has_default_uint64 ());
- EXPECT_FALSE(message.has_default_sint32 ());
- EXPECT_FALSE(message.has_default_sint64 ());
- EXPECT_FALSE(message.has_default_fixed32 ());
- EXPECT_FALSE(message.has_default_fixed64 ());
- EXPECT_FALSE(message.has_default_sfixed32());
- EXPECT_FALSE(message.has_default_sfixed64());
- EXPECT_FALSE(message.has_default_float ());
- EXPECT_FALSE(message.has_default_double ());
- EXPECT_FALSE(message.has_default_bool ());
- EXPECT_FALSE(message.has_default_string ());
- EXPECT_FALSE(message.has_default_bytes ());
-
- EXPECT_FALSE(message.has_default_nested_enum ());
- EXPECT_FALSE(message.has_default_foreign_enum());
- EXPECT_FALSE(message.has_default_import_enum ());
-
-
- // Fields with defaults have their default values (duh).
- EXPECT_EQ( 41 , message.default_int32 ());
- EXPECT_EQ( 42 , message.default_int64 ());
- EXPECT_EQ( 43 , message.default_uint32 ());
- EXPECT_EQ( 44 , message.default_uint64 ());
- EXPECT_EQ(-45 , message.default_sint32 ());
- EXPECT_EQ( 46 , message.default_sint64 ());
- EXPECT_EQ( 47 , message.default_fixed32 ());
- EXPECT_EQ( 48 , message.default_fixed64 ());
- EXPECT_EQ( 49 , message.default_sfixed32());
- EXPECT_EQ(-50 , message.default_sfixed64());
- EXPECT_EQ( 51.5 , message.default_float ());
- EXPECT_EQ( 52e3 , message.default_double ());
- EXPECT_TRUE( message.default_bool ());
- EXPECT_EQ("hello", message.default_string ());
- EXPECT_EQ("world", message.default_bytes ());
-
- EXPECT_EQ(unittest::TestAllTypes::BAR, message.default_nested_enum ());
- EXPECT_EQ(unittest::FOREIGN_BAR , message.default_foreign_enum());
- EXPECT_EQ(unittest_import::IMPORT_BAR, message.default_import_enum ());
-
-
- EXPECT_FALSE(message.has_oneof_uint32 ());
- EXPECT_FALSE(message.has_oneof_nested_message());
- EXPECT_FALSE(message.has_oneof_string ());
- EXPECT_FALSE(message.has_oneof_bytes ());
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ExpectRepeatedFieldsModified(
- const unittest::TestAllTypes& 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_EQ(2, message.repeated_int32_size ());
- ASSERT_EQ(2, message.repeated_int64_size ());
- ASSERT_EQ(2, message.repeated_uint32_size ());
- ASSERT_EQ(2, message.repeated_uint64_size ());
- ASSERT_EQ(2, message.repeated_sint32_size ());
- ASSERT_EQ(2, message.repeated_sint64_size ());
- ASSERT_EQ(2, message.repeated_fixed32_size ());
- ASSERT_EQ(2, message.repeated_fixed64_size ());
- ASSERT_EQ(2, message.repeated_sfixed32_size());
- ASSERT_EQ(2, message.repeated_sfixed64_size());
- ASSERT_EQ(2, message.repeated_float_size ());
- ASSERT_EQ(2, message.repeated_double_size ());
- ASSERT_EQ(2, message.repeated_bool_size ());
- ASSERT_EQ(2, message.repeated_string_size ());
- ASSERT_EQ(2, message.repeated_bytes_size ());
-
- ASSERT_EQ(2, message.repeatedgroup_size ());
- ASSERT_EQ(2, message.repeated_nested_message_size ());
- ASSERT_EQ(2, message.repeated_foreign_message_size());
- ASSERT_EQ(2, message.repeated_import_message_size ());
- ASSERT_EQ(2, message.repeated_lazy_message_size ());
- ASSERT_EQ(2, message.repeated_nested_enum_size ());
- ASSERT_EQ(2, message.repeated_foreign_enum_size ());
- ASSERT_EQ(2, message.repeated_import_enum_size ());
-
-#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
- ASSERT_EQ(2, message.repeated_string_piece_size());
- ASSERT_EQ(2, message.repeated_cord_size());
-#endif
-
- EXPECT_EQ(201 , message.repeated_int32 (0));
- EXPECT_EQ(202 , message.repeated_int64 (0));
- EXPECT_EQ(203 , message.repeated_uint32 (0));
- EXPECT_EQ(204 , message.repeated_uint64 (0));
- EXPECT_EQ(205 , message.repeated_sint32 (0));
- EXPECT_EQ(206 , message.repeated_sint64 (0));
- EXPECT_EQ(207 , message.repeated_fixed32 (0));
- EXPECT_EQ(208 , message.repeated_fixed64 (0));
- EXPECT_EQ(209 , message.repeated_sfixed32(0));
- EXPECT_EQ(210 , message.repeated_sfixed64(0));
- EXPECT_EQ(211 , message.repeated_float (0));
- EXPECT_EQ(212 , message.repeated_double (0));
- EXPECT_TRUE( message.repeated_bool (0));
- EXPECT_EQ("215", message.repeated_string (0));
- EXPECT_EQ("216", message.repeated_bytes (0));
-
- EXPECT_EQ(217, message.repeatedgroup (0).a());
- EXPECT_EQ(218, message.repeated_nested_message (0).bb());
- EXPECT_EQ(219, message.repeated_foreign_message(0).c());
- EXPECT_EQ(220, message.repeated_import_message (0).d());
- EXPECT_EQ(227, message.repeated_lazy_message (0).bb());
-
- EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (0));
- EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(0));
- EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (0));
-
-
- // Actually verify the second (modified) elements now.
- EXPECT_EQ(501 , message.repeated_int32 (1));
- EXPECT_EQ(502 , message.repeated_int64 (1));
- EXPECT_EQ(503 , message.repeated_uint32 (1));
- EXPECT_EQ(504 , message.repeated_uint64 (1));
- EXPECT_EQ(505 , message.repeated_sint32 (1));
- EXPECT_EQ(506 , message.repeated_sint64 (1));
- EXPECT_EQ(507 , message.repeated_fixed32 (1));
- EXPECT_EQ(508 , message.repeated_fixed64 (1));
- EXPECT_EQ(509 , message.repeated_sfixed32(1));
- EXPECT_EQ(510 , message.repeated_sfixed64(1));
- EXPECT_EQ(511 , message.repeated_float (1));
- EXPECT_EQ(512 , message.repeated_double (1));
- EXPECT_TRUE( message.repeated_bool (1));
- EXPECT_EQ("515", message.repeated_string (1));
- EXPECT_EQ("516", message.repeated_bytes (1));
-
- EXPECT_EQ(517, message.repeatedgroup (1).a());
- EXPECT_EQ(518, message.repeated_nested_message (1).bb());
- EXPECT_EQ(519, message.repeated_foreign_message(1).c());
- EXPECT_EQ(520, message.repeated_import_message (1).d());
- EXPECT_EQ(527, message.repeated_lazy_message (1).bb());
-
- EXPECT_EQ(unittest::TestAllTypes::FOO, message.repeated_nested_enum (1));
- EXPECT_EQ(unittest::FOREIGN_FOO , message.repeated_foreign_enum(1));
- EXPECT_EQ(unittest_import::IMPORT_FOO, message.repeated_import_enum (1));
-
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::SetPackedFields(unittest::TestPackedTypes* message) {
- message->add_packed_int32 (601);
- message->add_packed_int64 (602);
- message->add_packed_uint32 (603);
- message->add_packed_uint64 (604);
- message->add_packed_sint32 (605);
- message->add_packed_sint64 (606);
- message->add_packed_fixed32 (607);
- message->add_packed_fixed64 (608);
- message->add_packed_sfixed32(609);
- message->add_packed_sfixed64(610);
- message->add_packed_float (611);
- message->add_packed_double (612);
- message->add_packed_bool (true);
- message->add_packed_enum (unittest::FOREIGN_BAR);
- // add a second one of each field
- message->add_packed_int32 (701);
- message->add_packed_int64 (702);
- message->add_packed_uint32 (703);
- message->add_packed_uint64 (704);
- message->add_packed_sint32 (705);
- message->add_packed_sint64 (706);
- message->add_packed_fixed32 (707);
- message->add_packed_fixed64 (708);
- message->add_packed_sfixed32(709);
- message->add_packed_sfixed64(710);
- message->add_packed_float (711);
- message->add_packed_double (712);
- message->add_packed_bool (false);
- message->add_packed_enum (unittest::FOREIGN_BAZ);
-}
-
-void TestUtil::SetUnpackedFields(unittest::TestUnpackedTypes* message) {
- // The values applied here must match those of SetPackedFields.
-
- message->add_unpacked_int32 (601);
- message->add_unpacked_int64 (602);
- message->add_unpacked_uint32 (603);
- message->add_unpacked_uint64 (604);
- message->add_unpacked_sint32 (605);
- message->add_unpacked_sint64 (606);
- message->add_unpacked_fixed32 (607);
- message->add_unpacked_fixed64 (608);
- message->add_unpacked_sfixed32(609);
- message->add_unpacked_sfixed64(610);
- message->add_unpacked_float (611);
- message->add_unpacked_double (612);
- message->add_unpacked_bool (true);
- message->add_unpacked_enum (unittest::FOREIGN_BAR);
- // add a second one of each field
- message->add_unpacked_int32 (701);
- message->add_unpacked_int64 (702);
- message->add_unpacked_uint32 (703);
- message->add_unpacked_uint64 (704);
- message->add_unpacked_sint32 (705);
- message->add_unpacked_sint64 (706);
- message->add_unpacked_fixed32 (707);
- message->add_unpacked_fixed64 (708);
- message->add_unpacked_sfixed32(709);
- message->add_unpacked_sfixed64(710);
- message->add_unpacked_float (711);
- message->add_unpacked_double (712);
- message->add_unpacked_bool (false);
- message->add_unpacked_enum (unittest::FOREIGN_BAZ);
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ModifyPackedFields(unittest::TestPackedTypes* message) {
- message->set_packed_int32 (1, 801);
- message->set_packed_int64 (1, 802);
- message->set_packed_uint32 (1, 803);
- message->set_packed_uint64 (1, 804);
- message->set_packed_sint32 (1, 805);
- message->set_packed_sint64 (1, 806);
- message->set_packed_fixed32 (1, 807);
- message->set_packed_fixed64 (1, 808);
- message->set_packed_sfixed32(1, 809);
- message->set_packed_sfixed64(1, 810);
- message->set_packed_float (1, 811);
- message->set_packed_double (1, 812);
- message->set_packed_bool (1, true);
- message->set_packed_enum (1, unittest::FOREIGN_FOO);
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ExpectPackedFieldsSet(const unittest::TestPackedTypes& message) {
- ASSERT_EQ(2, message.packed_int32_size ());
- ASSERT_EQ(2, message.packed_int64_size ());
- ASSERT_EQ(2, message.packed_uint32_size ());
- ASSERT_EQ(2, message.packed_uint64_size ());
- ASSERT_EQ(2, message.packed_sint32_size ());
- ASSERT_EQ(2, message.packed_sint64_size ());
- ASSERT_EQ(2, message.packed_fixed32_size ());
- ASSERT_EQ(2, message.packed_fixed64_size ());
- ASSERT_EQ(2, message.packed_sfixed32_size());
- ASSERT_EQ(2, message.packed_sfixed64_size());
- ASSERT_EQ(2, message.packed_float_size ());
- ASSERT_EQ(2, message.packed_double_size ());
- ASSERT_EQ(2, message.packed_bool_size ());
- ASSERT_EQ(2, message.packed_enum_size ());
-
- EXPECT_EQ(601 , message.packed_int32 (0));
- EXPECT_EQ(602 , message.packed_int64 (0));
- EXPECT_EQ(603 , message.packed_uint32 (0));
- EXPECT_EQ(604 , message.packed_uint64 (0));
- EXPECT_EQ(605 , message.packed_sint32 (0));
- EXPECT_EQ(606 , message.packed_sint64 (0));
- EXPECT_EQ(607 , message.packed_fixed32 (0));
- EXPECT_EQ(608 , message.packed_fixed64 (0));
- EXPECT_EQ(609 , message.packed_sfixed32(0));
- EXPECT_EQ(610 , message.packed_sfixed64(0));
- EXPECT_EQ(611 , message.packed_float (0));
- EXPECT_EQ(612 , message.packed_double (0));
- EXPECT_TRUE( message.packed_bool (0));
- EXPECT_EQ(unittest::FOREIGN_BAR, message.packed_enum(0));
-
- EXPECT_EQ(701 , message.packed_int32 (1));
- EXPECT_EQ(702 , message.packed_int64 (1));
- EXPECT_EQ(703 , message.packed_uint32 (1));
- EXPECT_EQ(704 , message.packed_uint64 (1));
- EXPECT_EQ(705 , message.packed_sint32 (1));
- EXPECT_EQ(706 , message.packed_sint64 (1));
- EXPECT_EQ(707 , message.packed_fixed32 (1));
- EXPECT_EQ(708 , message.packed_fixed64 (1));
- EXPECT_EQ(709 , message.packed_sfixed32(1));
- EXPECT_EQ(710 , message.packed_sfixed64(1));
- EXPECT_EQ(711 , message.packed_float (1));
- EXPECT_EQ(712 , message.packed_double (1));
- EXPECT_FALSE( message.packed_bool (1));
- EXPECT_EQ(unittest::FOREIGN_BAZ, message.packed_enum(1));
-}
-
-void TestUtil::ExpectUnpackedFieldsSet(
- const unittest::TestUnpackedTypes& message) {
- // The values expected here must match those of ExpectPackedFieldsSet.
-
- ASSERT_EQ(2, message.unpacked_int32_size ());
- ASSERT_EQ(2, message.unpacked_int64_size ());
- ASSERT_EQ(2, message.unpacked_uint32_size ());
- ASSERT_EQ(2, message.unpacked_uint64_size ());
- ASSERT_EQ(2, message.unpacked_sint32_size ());
- ASSERT_EQ(2, message.unpacked_sint64_size ());
- ASSERT_EQ(2, message.unpacked_fixed32_size ());
- ASSERT_EQ(2, message.unpacked_fixed64_size ());
- ASSERT_EQ(2, message.unpacked_sfixed32_size());
- ASSERT_EQ(2, message.unpacked_sfixed64_size());
- ASSERT_EQ(2, message.unpacked_float_size ());
- ASSERT_EQ(2, message.unpacked_double_size ());
- ASSERT_EQ(2, message.unpacked_bool_size ());
- ASSERT_EQ(2, message.unpacked_enum_size ());
-
- EXPECT_EQ(601 , message.unpacked_int32 (0));
- EXPECT_EQ(602 , message.unpacked_int64 (0));
- EXPECT_EQ(603 , message.unpacked_uint32 (0));
- EXPECT_EQ(604 , message.unpacked_uint64 (0));
- EXPECT_EQ(605 , message.unpacked_sint32 (0));
- EXPECT_EQ(606 , message.unpacked_sint64 (0));
- EXPECT_EQ(607 , message.unpacked_fixed32 (0));
- EXPECT_EQ(608 , message.unpacked_fixed64 (0));
- EXPECT_EQ(609 , message.unpacked_sfixed32(0));
- EXPECT_EQ(610 , message.unpacked_sfixed64(0));
- EXPECT_EQ(611 , message.unpacked_float (0));
- EXPECT_EQ(612 , message.unpacked_double (0));
- EXPECT_TRUE( message.unpacked_bool (0));
- EXPECT_EQ(unittest::FOREIGN_BAR, message.unpacked_enum(0));
-
- EXPECT_EQ(701 , message.unpacked_int32 (1));
- EXPECT_EQ(702 , message.unpacked_int64 (1));
- EXPECT_EQ(703 , message.unpacked_uint32 (1));
- EXPECT_EQ(704 , message.unpacked_uint64 (1));
- EXPECT_EQ(705 , message.unpacked_sint32 (1));
- EXPECT_EQ(706 , message.unpacked_sint64 (1));
- EXPECT_EQ(707 , message.unpacked_fixed32 (1));
- EXPECT_EQ(708 , message.unpacked_fixed64 (1));
- EXPECT_EQ(709 , message.unpacked_sfixed32(1));
- EXPECT_EQ(710 , message.unpacked_sfixed64(1));
- EXPECT_EQ(711 , message.unpacked_float (1));
- EXPECT_EQ(712 , message.unpacked_double (1));
- EXPECT_FALSE( message.unpacked_bool (1));
- EXPECT_EQ(unittest::FOREIGN_BAZ, message.unpacked_enum(1));
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ExpectPackedClear(
- const unittest::TestPackedTypes& message) {
- // Packed repeated fields are empty.
- EXPECT_EQ(0, message.packed_int32_size ());
- EXPECT_EQ(0, message.packed_int64_size ());
- EXPECT_EQ(0, message.packed_uint32_size ());
- EXPECT_EQ(0, message.packed_uint64_size ());
- EXPECT_EQ(0, message.packed_sint32_size ());
- EXPECT_EQ(0, message.packed_sint64_size ());
- EXPECT_EQ(0, message.packed_fixed32_size ());
- EXPECT_EQ(0, message.packed_fixed64_size ());
- EXPECT_EQ(0, message.packed_sfixed32_size());
- EXPECT_EQ(0, message.packed_sfixed64_size());
- EXPECT_EQ(0, message.packed_float_size ());
- EXPECT_EQ(0, message.packed_double_size ());
- EXPECT_EQ(0, message.packed_bool_size ());
- EXPECT_EQ(0, message.packed_enum_size ());
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ExpectPackedFieldsModified(
- const unittest::TestPackedTypes& message) {
- // Do the same for packed repeated fields.
- ASSERT_EQ(2, message.packed_int32_size ());
- ASSERT_EQ(2, message.packed_int64_size ());
- ASSERT_EQ(2, message.packed_uint32_size ());
- ASSERT_EQ(2, message.packed_uint64_size ());
- ASSERT_EQ(2, message.packed_sint32_size ());
- ASSERT_EQ(2, message.packed_sint64_size ());
- ASSERT_EQ(2, message.packed_fixed32_size ());
- ASSERT_EQ(2, message.packed_fixed64_size ());
- ASSERT_EQ(2, message.packed_sfixed32_size());
- ASSERT_EQ(2, message.packed_sfixed64_size());
- ASSERT_EQ(2, message.packed_float_size ());
- ASSERT_EQ(2, message.packed_double_size ());
- ASSERT_EQ(2, message.packed_bool_size ());
- ASSERT_EQ(2, message.packed_enum_size ());
-
- EXPECT_EQ(601 , message.packed_int32 (0));
- EXPECT_EQ(602 , message.packed_int64 (0));
- EXPECT_EQ(603 , message.packed_uint32 (0));
- EXPECT_EQ(604 , message.packed_uint64 (0));
- EXPECT_EQ(605 , message.packed_sint32 (0));
- EXPECT_EQ(606 , message.packed_sint64 (0));
- EXPECT_EQ(607 , message.packed_fixed32 (0));
- EXPECT_EQ(608 , message.packed_fixed64 (0));
- EXPECT_EQ(609 , message.packed_sfixed32(0));
- EXPECT_EQ(610 , message.packed_sfixed64(0));
- EXPECT_EQ(611 , message.packed_float (0));
- EXPECT_EQ(612 , message.packed_double (0));
- EXPECT_TRUE( message.packed_bool (0));
- EXPECT_EQ(unittest::FOREIGN_BAR, message.packed_enum(0));
- // Actually verify the second (modified) elements now.
- EXPECT_EQ(801 , message.packed_int32 (1));
- EXPECT_EQ(802 , message.packed_int64 (1));
- EXPECT_EQ(803 , message.packed_uint32 (1));
- EXPECT_EQ(804 , message.packed_uint64 (1));
- EXPECT_EQ(805 , message.packed_sint32 (1));
- EXPECT_EQ(806 , message.packed_sint64 (1));
- EXPECT_EQ(807 , message.packed_fixed32 (1));
- EXPECT_EQ(808 , message.packed_fixed64 (1));
- EXPECT_EQ(809 , message.packed_sfixed32(1));
- EXPECT_EQ(810 , message.packed_sfixed64(1));
- EXPECT_EQ(811 , message.packed_float (1));
- EXPECT_EQ(812 , message.packed_double (1));
- EXPECT_TRUE( message.packed_bool (1));
- EXPECT_EQ(unittest::FOREIGN_FOO, message.packed_enum(1));
-}
-
-// ===================================================================
-// Extensions
-//
-// All this code is exactly equivalent to the above code except that it's
-// manipulating extension fields instead of normal ones.
-//
-// I gave up on the 80-char limit here. Sorry.
-
-void TestUtil::SetAllExtensions(unittest::TestAllExtensions* message) {
- message->SetExtension(unittest::optional_int32_extension , 101);
- message->SetExtension(unittest::optional_int64_extension , 102);
- message->SetExtension(unittest::optional_uint32_extension , 103);
- message->SetExtension(unittest::optional_uint64_extension , 104);
- message->SetExtension(unittest::optional_sint32_extension , 105);
- message->SetExtension(unittest::optional_sint64_extension , 106);
- message->SetExtension(unittest::optional_fixed32_extension , 107);
- message->SetExtension(unittest::optional_fixed64_extension , 108);
- message->SetExtension(unittest::optional_sfixed32_extension, 109);
- message->SetExtension(unittest::optional_sfixed64_extension, 110);
- message->SetExtension(unittest::optional_float_extension , 111);
- message->SetExtension(unittest::optional_double_extension , 112);
- message->SetExtension(unittest::optional_bool_extension , true);
- message->SetExtension(unittest::optional_string_extension , "115");
- message->SetExtension(unittest::optional_bytes_extension , "116");
-
- message->MutableExtension(unittest::optionalgroup_extension )->set_a(117);
- message->MutableExtension(unittest::optional_nested_message_extension )->set_bb(118);
- message->MutableExtension(unittest::optional_foreign_message_extension)->set_c(119);
- message->MutableExtension(unittest::optional_import_message_extension )->set_d(120);
-
- message->SetExtension(unittest::optional_nested_enum_extension , unittest::TestAllTypes::BAZ);
- message->SetExtension(unittest::optional_foreign_enum_extension, unittest::FOREIGN_BAZ );
- message->SetExtension(unittest::optional_import_enum_extension , unittest_import::IMPORT_BAZ);
-
- message->SetExtension(unittest::optional_string_piece_extension, "124");
- message->SetExtension(unittest::optional_cord_extension, "125");
-
- message->MutableExtension(unittest::optional_public_import_message_extension)->set_e(126);
- message->MutableExtension(unittest::optional_lazy_message_extension)->set_bb(127);
-
- // -----------------------------------------------------------------
-
- message->AddExtension(unittest::repeated_int32_extension , 201);
- message->AddExtension(unittest::repeated_int64_extension , 202);
- message->AddExtension(unittest::repeated_uint32_extension , 203);
- message->AddExtension(unittest::repeated_uint64_extension , 204);
- message->AddExtension(unittest::repeated_sint32_extension , 205);
- message->AddExtension(unittest::repeated_sint64_extension , 206);
- message->AddExtension(unittest::repeated_fixed32_extension , 207);
- message->AddExtension(unittest::repeated_fixed64_extension , 208);
- message->AddExtension(unittest::repeated_sfixed32_extension, 209);
- message->AddExtension(unittest::repeated_sfixed64_extension, 210);
- message->AddExtension(unittest::repeated_float_extension , 211);
- message->AddExtension(unittest::repeated_double_extension , 212);
- message->AddExtension(unittest::repeated_bool_extension , true);
- message->AddExtension(unittest::repeated_string_extension , "215");
- message->AddExtension(unittest::repeated_bytes_extension , "216");
-
- message->AddExtension(unittest::repeatedgroup_extension )->set_a(217);
- message->AddExtension(unittest::repeated_nested_message_extension )->set_bb(218);
- message->AddExtension(unittest::repeated_foreign_message_extension)->set_c(219);
- message->AddExtension(unittest::repeated_import_message_extension )->set_d(220);
- message->AddExtension(unittest::repeated_lazy_message_extension )->set_bb(227);
-
- message->AddExtension(unittest::repeated_nested_enum_extension , unittest::TestAllTypes::BAR);
- message->AddExtension(unittest::repeated_foreign_enum_extension, unittest::FOREIGN_BAR );
- message->AddExtension(unittest::repeated_import_enum_extension , unittest_import::IMPORT_BAR);
-
- message->AddExtension(unittest::repeated_string_piece_extension, "224");
- message->AddExtension(unittest::repeated_cord_extension, "225");
-
- // Add a second one of each field.
- message->AddExtension(unittest::repeated_int32_extension , 301);
- message->AddExtension(unittest::repeated_int64_extension , 302);
- message->AddExtension(unittest::repeated_uint32_extension , 303);
- message->AddExtension(unittest::repeated_uint64_extension , 304);
- message->AddExtension(unittest::repeated_sint32_extension , 305);
- message->AddExtension(unittest::repeated_sint64_extension , 306);
- message->AddExtension(unittest::repeated_fixed32_extension , 307);
- message->AddExtension(unittest::repeated_fixed64_extension , 308);
- message->AddExtension(unittest::repeated_sfixed32_extension, 309);
- message->AddExtension(unittest::repeated_sfixed64_extension, 310);
- message->AddExtension(unittest::repeated_float_extension , 311);
- message->AddExtension(unittest::repeated_double_extension , 312);
- message->AddExtension(unittest::repeated_bool_extension , false);
- message->AddExtension(unittest::repeated_string_extension , "315");
- message->AddExtension(unittest::repeated_bytes_extension , "316");
-
- message->AddExtension(unittest::repeatedgroup_extension )->set_a(317);
- message->AddExtension(unittest::repeated_nested_message_extension )->set_bb(318);
- message->AddExtension(unittest::repeated_foreign_message_extension)->set_c(319);
- message->AddExtension(unittest::repeated_import_message_extension )->set_d(320);
- message->AddExtension(unittest::repeated_lazy_message_extension )->set_bb(327);
-
- message->AddExtension(unittest::repeated_nested_enum_extension , unittest::TestAllTypes::BAZ);
- message->AddExtension(unittest::repeated_foreign_enum_extension, unittest::FOREIGN_BAZ );
- message->AddExtension(unittest::repeated_import_enum_extension , unittest_import::IMPORT_BAZ);
-
- message->AddExtension(unittest::repeated_string_piece_extension, "324");
- message->AddExtension(unittest::repeated_cord_extension, "325");
-
- // -----------------------------------------------------------------
-
- message->SetExtension(unittest::default_int32_extension , 401);
- message->SetExtension(unittest::default_int64_extension , 402);
- message->SetExtension(unittest::default_uint32_extension , 403);
- message->SetExtension(unittest::default_uint64_extension , 404);
- message->SetExtension(unittest::default_sint32_extension , 405);
- message->SetExtension(unittest::default_sint64_extension , 406);
- message->SetExtension(unittest::default_fixed32_extension , 407);
- message->SetExtension(unittest::default_fixed64_extension , 408);
- message->SetExtension(unittest::default_sfixed32_extension, 409);
- message->SetExtension(unittest::default_sfixed64_extension, 410);
- message->SetExtension(unittest::default_float_extension , 411);
- message->SetExtension(unittest::default_double_extension , 412);
- message->SetExtension(unittest::default_bool_extension , false);
- message->SetExtension(unittest::default_string_extension , "415");
- message->SetExtension(unittest::default_bytes_extension , "416");
-
- message->SetExtension(unittest::default_nested_enum_extension , unittest::TestAllTypes::FOO);
- message->SetExtension(unittest::default_foreign_enum_extension, unittest::FOREIGN_FOO );
- message->SetExtension(unittest::default_import_enum_extension , unittest_import::IMPORT_FOO);
-
- message->SetExtension(unittest::default_string_piece_extension, "424");
- message->SetExtension(unittest::default_cord_extension, "425");
-
- SetOneofFields(message);
-}
-
-void TestUtil::SetOneofFields(unittest::TestAllExtensions* message) {
- message->SetExtension(unittest::oneof_uint32_extension, 601);
- message->MutableExtension(unittest::oneof_nested_message_extension)->set_bb(602);
- message->SetExtension(unittest::oneof_string_extension, "603");
- message->SetExtension(unittest::oneof_bytes_extension, "604");
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::SetAllFieldsAndExtensions(
- unittest::TestFieldOrderings* message) {
- GOOGLE_CHECK(message);
- message->set_my_int(1);
- message->set_my_string("foo");
- message->set_my_float(1.0);
- message->SetExtension(unittest::my_extension_int, 23);
- message->SetExtension(unittest::my_extension_string, "bar");
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ModifyRepeatedExtensions(unittest::TestAllExtensions* message) {
- message->SetExtension(unittest::repeated_int32_extension , 1, 501);
- message->SetExtension(unittest::repeated_int64_extension , 1, 502);
- message->SetExtension(unittest::repeated_uint32_extension , 1, 503);
- message->SetExtension(unittest::repeated_uint64_extension , 1, 504);
- message->SetExtension(unittest::repeated_sint32_extension , 1, 505);
- message->SetExtension(unittest::repeated_sint64_extension , 1, 506);
- message->SetExtension(unittest::repeated_fixed32_extension , 1, 507);
- message->SetExtension(unittest::repeated_fixed64_extension , 1, 508);
- message->SetExtension(unittest::repeated_sfixed32_extension, 1, 509);
- message->SetExtension(unittest::repeated_sfixed64_extension, 1, 510);
- message->SetExtension(unittest::repeated_float_extension , 1, 511);
- message->SetExtension(unittest::repeated_double_extension , 1, 512);
- message->SetExtension(unittest::repeated_bool_extension , 1, true);
- message->SetExtension(unittest::repeated_string_extension , 1, "515");
- message->SetExtension(unittest::repeated_bytes_extension , 1, "516");
-
- message->MutableExtension(unittest::repeatedgroup_extension , 1)->set_a(517);
- message->MutableExtension(unittest::repeated_nested_message_extension , 1)->set_bb(518);
- message->MutableExtension(unittest::repeated_foreign_message_extension, 1)->set_c(519);
- message->MutableExtension(unittest::repeated_import_message_extension , 1)->set_d(520);
- message->MutableExtension(unittest::repeated_lazy_message_extension , 1)->set_bb(527);
-
- message->SetExtension(unittest::repeated_nested_enum_extension , 1, unittest::TestAllTypes::FOO);
- message->SetExtension(unittest::repeated_foreign_enum_extension, 1, unittest::FOREIGN_FOO );
- message->SetExtension(unittest::repeated_import_enum_extension , 1, unittest_import::IMPORT_FOO);
-
- message->SetExtension(unittest::repeated_string_piece_extension, 1, "524");
- message->SetExtension(unittest::repeated_cord_extension, 1, "525");
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ExpectAllExtensionsSet(
- const unittest::TestAllExtensions& message) {
- EXPECT_TRUE(message.HasExtension(unittest::optional_int32_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_int64_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_uint32_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_uint64_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_sint32_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_sint64_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_fixed32_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_fixed64_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_sfixed32_extension));
- EXPECT_TRUE(message.HasExtension(unittest::optional_sfixed64_extension));
- EXPECT_TRUE(message.HasExtension(unittest::optional_float_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_double_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_bool_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_string_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_bytes_extension ));
-
- EXPECT_TRUE(message.HasExtension(unittest::optionalgroup_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_nested_message_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_foreign_message_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_import_message_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_public_import_message_extension));
- EXPECT_TRUE(message.HasExtension(unittest::optional_lazy_message_extension ));
-
- EXPECT_TRUE(message.GetExtension(unittest::optionalgroup_extension ).has_a());
- EXPECT_TRUE(message.GetExtension(unittest::optional_nested_message_extension ).has_bb());
- EXPECT_TRUE(message.GetExtension(unittest::optional_foreign_message_extension ).has_c());
- EXPECT_TRUE(message.GetExtension(unittest::optional_import_message_extension ).has_d());
- EXPECT_TRUE(message.GetExtension(unittest::optional_public_import_message_extension).has_e());
- EXPECT_TRUE(message.GetExtension(unittest::optional_lazy_message_extension ).has_bb());
-
- EXPECT_TRUE(message.HasExtension(unittest::optional_nested_enum_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::optional_foreign_enum_extension));
- EXPECT_TRUE(message.HasExtension(unittest::optional_import_enum_extension ));
-
- EXPECT_TRUE(message.HasExtension(unittest::optional_string_piece_extension));
- EXPECT_TRUE(message.HasExtension(unittest::optional_cord_extension));
-
- EXPECT_EQ(101 , message.GetExtension(unittest::optional_int32_extension ));
- EXPECT_EQ(102 , message.GetExtension(unittest::optional_int64_extension ));
- EXPECT_EQ(103 , message.GetExtension(unittest::optional_uint32_extension ));
- EXPECT_EQ(104 , message.GetExtension(unittest::optional_uint64_extension ));
- EXPECT_EQ(105 , message.GetExtension(unittest::optional_sint32_extension ));
- EXPECT_EQ(106 , message.GetExtension(unittest::optional_sint64_extension ));
- EXPECT_EQ(107 , message.GetExtension(unittest::optional_fixed32_extension ));
- EXPECT_EQ(108 , message.GetExtension(unittest::optional_fixed64_extension ));
- EXPECT_EQ(109 , message.GetExtension(unittest::optional_sfixed32_extension));
- EXPECT_EQ(110 , message.GetExtension(unittest::optional_sfixed64_extension));
- EXPECT_EQ(111 , message.GetExtension(unittest::optional_float_extension ));
- EXPECT_EQ(112 , message.GetExtension(unittest::optional_double_extension ));
- EXPECT_TRUE( message.GetExtension(unittest::optional_bool_extension ));
- EXPECT_EQ("115", message.GetExtension(unittest::optional_string_extension ));
- EXPECT_EQ("116", message.GetExtension(unittest::optional_bytes_extension ));
-
- EXPECT_EQ(117, message.GetExtension(unittest::optionalgroup_extension ).a());
- EXPECT_EQ(118, message.GetExtension(unittest::optional_nested_message_extension ).bb());
- EXPECT_EQ(119, message.GetExtension(unittest::optional_foreign_message_extension).c());
- EXPECT_EQ(120, message.GetExtension(unittest::optional_import_message_extension ).d());
-
- EXPECT_EQ(unittest::TestAllTypes::BAZ, message.GetExtension(unittest::optional_nested_enum_extension ));
- EXPECT_EQ(unittest::FOREIGN_BAZ , message.GetExtension(unittest::optional_foreign_enum_extension));
- EXPECT_EQ(unittest_import::IMPORT_BAZ, message.GetExtension(unittest::optional_import_enum_extension ));
-
- EXPECT_EQ("124", message.GetExtension(unittest::optional_string_piece_extension));
- EXPECT_EQ("125", message.GetExtension(unittest::optional_cord_extension));
- EXPECT_EQ(126, message.GetExtension(unittest::optional_public_import_message_extension ).e());
- EXPECT_EQ(127, message.GetExtension(unittest::optional_lazy_message_extension).bb());
-
- // -----------------------------------------------------------------
-
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension ));
-
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_lazy_message_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension ));
-
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_piece_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_cord_extension));
-
- EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 0));
- EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 0));
- EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 0));
- EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 0));
- EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 0));
- EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 0));
- EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 0));
- EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 0));
- EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 0));
- EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 0));
- EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 0));
- EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 0));
- EXPECT_TRUE( message.GetExtension(unittest::repeated_bool_extension , 0));
- EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 0));
- EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 0));
-
- EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 0).a());
- EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb());
- EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c());
- EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 0).d());
- EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension , 0).bb());
-
- EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 0));
- EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 0));
- EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 0));
-
- EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 0));
- EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 0));
-
- EXPECT_EQ(301 , message.GetExtension(unittest::repeated_int32_extension , 1));
- EXPECT_EQ(302 , message.GetExtension(unittest::repeated_int64_extension , 1));
- EXPECT_EQ(303 , message.GetExtension(unittest::repeated_uint32_extension , 1));
- EXPECT_EQ(304 , message.GetExtension(unittest::repeated_uint64_extension , 1));
- EXPECT_EQ(305 , message.GetExtension(unittest::repeated_sint32_extension , 1));
- EXPECT_EQ(306 , message.GetExtension(unittest::repeated_sint64_extension , 1));
- EXPECT_EQ(307 , message.GetExtension(unittest::repeated_fixed32_extension , 1));
- EXPECT_EQ(308 , message.GetExtension(unittest::repeated_fixed64_extension , 1));
- EXPECT_EQ(309 , message.GetExtension(unittest::repeated_sfixed32_extension, 1));
- EXPECT_EQ(310 , message.GetExtension(unittest::repeated_sfixed64_extension, 1));
- EXPECT_EQ(311 , message.GetExtension(unittest::repeated_float_extension , 1));
- EXPECT_EQ(312 , message.GetExtension(unittest::repeated_double_extension , 1));
- EXPECT_FALSE( message.GetExtension(unittest::repeated_bool_extension , 1));
- EXPECT_EQ("315", message.GetExtension(unittest::repeated_string_extension , 1));
- EXPECT_EQ("316", message.GetExtension(unittest::repeated_bytes_extension , 1));
-
- EXPECT_EQ(317, message.GetExtension(unittest::repeatedgroup_extension , 1).a());
- EXPECT_EQ(318, message.GetExtension(unittest::repeated_nested_message_extension , 1).bb());
- EXPECT_EQ(319, message.GetExtension(unittest::repeated_foreign_message_extension, 1).c());
- EXPECT_EQ(320, message.GetExtension(unittest::repeated_import_message_extension , 1).d());
- EXPECT_EQ(327, message.GetExtension(unittest::repeated_lazy_message_extension , 1).bb());
-
- EXPECT_EQ(unittest::TestAllTypes::BAZ, message.GetExtension(unittest::repeated_nested_enum_extension , 1));
- EXPECT_EQ(unittest::FOREIGN_BAZ , message.GetExtension(unittest::repeated_foreign_enum_extension, 1));
- EXPECT_EQ(unittest_import::IMPORT_BAZ, message.GetExtension(unittest::repeated_import_enum_extension , 1));
-
- EXPECT_EQ("324", message.GetExtension(unittest::repeated_string_piece_extension, 1));
- EXPECT_EQ("325", message.GetExtension(unittest::repeated_cord_extension, 1));
-
- // -----------------------------------------------------------------
-
- EXPECT_TRUE(message.HasExtension(unittest::default_int32_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::default_int64_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::default_uint32_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::default_uint64_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::default_sint32_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::default_sint64_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::default_fixed32_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::default_fixed64_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::default_sfixed32_extension));
- EXPECT_TRUE(message.HasExtension(unittest::default_sfixed64_extension));
- EXPECT_TRUE(message.HasExtension(unittest::default_float_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::default_double_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::default_bool_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::default_string_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::default_bytes_extension ));
-
- EXPECT_TRUE(message.HasExtension(unittest::default_nested_enum_extension ));
- EXPECT_TRUE(message.HasExtension(unittest::default_foreign_enum_extension));
- EXPECT_TRUE(message.HasExtension(unittest::default_import_enum_extension ));
-
- EXPECT_TRUE(message.HasExtension(unittest::default_string_piece_extension));
- EXPECT_TRUE(message.HasExtension(unittest::default_cord_extension));
-
- EXPECT_EQ(401 , message.GetExtension(unittest::default_int32_extension ));
- EXPECT_EQ(402 , message.GetExtension(unittest::default_int64_extension ));
- EXPECT_EQ(403 , message.GetExtension(unittest::default_uint32_extension ));
- EXPECT_EQ(404 , message.GetExtension(unittest::default_uint64_extension ));
- EXPECT_EQ(405 , message.GetExtension(unittest::default_sint32_extension ));
- EXPECT_EQ(406 , message.GetExtension(unittest::default_sint64_extension ));
- EXPECT_EQ(407 , message.GetExtension(unittest::default_fixed32_extension ));
- EXPECT_EQ(408 , message.GetExtension(unittest::default_fixed64_extension ));
- EXPECT_EQ(409 , message.GetExtension(unittest::default_sfixed32_extension));
- EXPECT_EQ(410 , message.GetExtension(unittest::default_sfixed64_extension));
- EXPECT_EQ(411 , message.GetExtension(unittest::default_float_extension ));
- EXPECT_EQ(412 , message.GetExtension(unittest::default_double_extension ));
- EXPECT_FALSE( message.GetExtension(unittest::default_bool_extension ));
- EXPECT_EQ("415", message.GetExtension(unittest::default_string_extension ));
- EXPECT_EQ("416", message.GetExtension(unittest::default_bytes_extension ));
-
- EXPECT_EQ(unittest::TestAllTypes::FOO, message.GetExtension(unittest::default_nested_enum_extension ));
- EXPECT_EQ(unittest::FOREIGN_FOO , message.GetExtension(unittest::default_foreign_enum_extension));
- EXPECT_EQ(unittest_import::IMPORT_FOO, message.GetExtension(unittest::default_import_enum_extension ));
-
- EXPECT_EQ("424", message.GetExtension(unittest::default_string_piece_extension));
- EXPECT_EQ("425", message.GetExtension(unittest::default_cord_extension));
-
- EXPECT_TRUE(message.HasExtension(unittest::oneof_uint32_extension));
- EXPECT_TRUE(message.GetExtension(unittest::oneof_nested_message_extension).has_bb());
- EXPECT_TRUE(message.HasExtension(unittest::oneof_string_extension));
- EXPECT_TRUE(message.HasExtension(unittest::oneof_bytes_extension));
-
- EXPECT_EQ(601, message.GetExtension(unittest::oneof_uint32_extension));
- EXPECT_EQ(602, message.GetExtension(unittest::oneof_nested_message_extension).bb());
- EXPECT_EQ("603", message.GetExtension(unittest::oneof_string_extension));
- EXPECT_EQ("604", message.GetExtension(unittest::oneof_bytes_extension));
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ExpectExtensionsClear(
- const unittest::TestAllExtensions& message) {
- string serialized;
- ASSERT_TRUE(message.SerializeToString(&serialized));
- EXPECT_EQ("", serialized);
- EXPECT_EQ(0, message.ByteSize());
-
- // has_blah() should initially be false for all optional fields.
- EXPECT_FALSE(message.HasExtension(unittest::optional_int32_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_int64_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_uint32_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_uint64_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_sint32_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_sint64_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_fixed32_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_fixed64_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_sfixed32_extension));
- EXPECT_FALSE(message.HasExtension(unittest::optional_sfixed64_extension));
- EXPECT_FALSE(message.HasExtension(unittest::optional_float_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_double_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_bool_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_string_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_bytes_extension ));
-
- EXPECT_FALSE(message.HasExtension(unittest::optionalgroup_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_nested_message_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_foreign_message_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_import_message_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_public_import_message_extension));
- EXPECT_FALSE(message.HasExtension(unittest::optional_lazy_message_extension ));
-
- EXPECT_FALSE(message.HasExtension(unittest::optional_nested_enum_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::optional_foreign_enum_extension));
- EXPECT_FALSE(message.HasExtension(unittest::optional_import_enum_extension ));
-
- EXPECT_FALSE(message.HasExtension(unittest::optional_string_piece_extension));
- EXPECT_FALSE(message.HasExtension(unittest::optional_cord_extension));
-
- // Optional fields without defaults are set to zero or something like it.
- EXPECT_EQ(0 , message.GetExtension(unittest::optional_int32_extension ));
- EXPECT_EQ(0 , message.GetExtension(unittest::optional_int64_extension ));
- EXPECT_EQ(0 , message.GetExtension(unittest::optional_uint32_extension ));
- EXPECT_EQ(0 , message.GetExtension(unittest::optional_uint64_extension ));
- EXPECT_EQ(0 , message.GetExtension(unittest::optional_sint32_extension ));
- EXPECT_EQ(0 , message.GetExtension(unittest::optional_sint64_extension ));
- EXPECT_EQ(0 , message.GetExtension(unittest::optional_fixed32_extension ));
- EXPECT_EQ(0 , message.GetExtension(unittest::optional_fixed64_extension ));
- EXPECT_EQ(0 , message.GetExtension(unittest::optional_sfixed32_extension));
- EXPECT_EQ(0 , message.GetExtension(unittest::optional_sfixed64_extension));
- EXPECT_EQ(0 , message.GetExtension(unittest::optional_float_extension ));
- EXPECT_EQ(0 , message.GetExtension(unittest::optional_double_extension ));
- EXPECT_FALSE( message.GetExtension(unittest::optional_bool_extension ));
- EXPECT_EQ("" , message.GetExtension(unittest::optional_string_extension ));
- EXPECT_EQ("" , message.GetExtension(unittest::optional_bytes_extension ));
-
- // Embedded messages should also be clear.
- EXPECT_FALSE(message.GetExtension(unittest::optionalgroup_extension ).has_a());
- EXPECT_FALSE(message.GetExtension(unittest::optional_nested_message_extension ).has_bb());
- EXPECT_FALSE(message.GetExtension(unittest::optional_foreign_message_extension ).has_c());
- EXPECT_FALSE(message.GetExtension(unittest::optional_import_message_extension ).has_d());
- EXPECT_FALSE(message.GetExtension(unittest::optional_public_import_message_extension).has_e());
- EXPECT_FALSE(message.GetExtension(unittest::optional_lazy_message_extension ).has_bb());
-
- EXPECT_EQ(0, message.GetExtension(unittest::optionalgroup_extension ).a());
- EXPECT_EQ(0, message.GetExtension(unittest::optional_nested_message_extension ).bb());
- EXPECT_EQ(0, message.GetExtension(unittest::optional_foreign_message_extension ).c());
- EXPECT_EQ(0, message.GetExtension(unittest::optional_import_message_extension ).d());
- EXPECT_EQ(0, message.GetExtension(unittest::optional_public_import_message_extension).e());
- EXPECT_EQ(0, message.GetExtension(unittest::optional_lazy_message_extension ).bb());
-
- // Enums without defaults are set to the first value in the enum.
- EXPECT_EQ(unittest::TestAllTypes::FOO, message.GetExtension(unittest::optional_nested_enum_extension ));
- EXPECT_EQ(unittest::FOREIGN_FOO , message.GetExtension(unittest::optional_foreign_enum_extension));
- EXPECT_EQ(unittest_import::IMPORT_FOO, message.GetExtension(unittest::optional_import_enum_extension ));
-
- EXPECT_EQ("", message.GetExtension(unittest::optional_string_piece_extension));
- EXPECT_EQ("", message.GetExtension(unittest::optional_cord_extension));
-
- // Repeated fields are empty.
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_int32_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_int64_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_uint32_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_uint64_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sint32_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sint64_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_fixed32_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_fixed64_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sfixed32_extension));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sfixed64_extension));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_float_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_double_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_bool_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_string_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_bytes_extension ));
-
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeatedgroup_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_nested_message_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_foreign_message_extension));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_import_message_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_lazy_message_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_nested_enum_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_foreign_enum_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_import_enum_extension ));
-
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_string_piece_extension));
- EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_cord_extension));
-
- // has_blah() should also be false for all default fields.
- EXPECT_FALSE(message.HasExtension(unittest::default_int32_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::default_int64_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::default_uint32_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::default_uint64_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::default_sint32_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::default_sint64_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::default_fixed32_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::default_fixed64_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::default_sfixed32_extension));
- EXPECT_FALSE(message.HasExtension(unittest::default_sfixed64_extension));
- EXPECT_FALSE(message.HasExtension(unittest::default_float_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::default_double_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::default_bool_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::default_string_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::default_bytes_extension ));
-
- EXPECT_FALSE(message.HasExtension(unittest::default_nested_enum_extension ));
- EXPECT_FALSE(message.HasExtension(unittest::default_foreign_enum_extension));
- EXPECT_FALSE(message.HasExtension(unittest::default_import_enum_extension ));
-
- EXPECT_FALSE(message.HasExtension(unittest::default_string_piece_extension));
- EXPECT_FALSE(message.HasExtension(unittest::default_cord_extension));
-
- // Fields with defaults have their default values (duh).
- EXPECT_EQ( 41 , message.GetExtension(unittest::default_int32_extension ));
- EXPECT_EQ( 42 , message.GetExtension(unittest::default_int64_extension ));
- EXPECT_EQ( 43 , message.GetExtension(unittest::default_uint32_extension ));
- EXPECT_EQ( 44 , message.GetExtension(unittest::default_uint64_extension ));
- EXPECT_EQ(-45 , message.GetExtension(unittest::default_sint32_extension ));
- EXPECT_EQ( 46 , message.GetExtension(unittest::default_sint64_extension ));
- EXPECT_EQ( 47 , message.GetExtension(unittest::default_fixed32_extension ));
- EXPECT_EQ( 48 , message.GetExtension(unittest::default_fixed64_extension ));
- EXPECT_EQ( 49 , message.GetExtension(unittest::default_sfixed32_extension));
- EXPECT_EQ(-50 , message.GetExtension(unittest::default_sfixed64_extension));
- EXPECT_EQ( 51.5 , message.GetExtension(unittest::default_float_extension ));
- EXPECT_EQ( 52e3 , message.GetExtension(unittest::default_double_extension ));
- EXPECT_TRUE( message.GetExtension(unittest::default_bool_extension ));
- EXPECT_EQ("hello", message.GetExtension(unittest::default_string_extension ));
- EXPECT_EQ("world", message.GetExtension(unittest::default_bytes_extension ));
-
- EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::default_nested_enum_extension ));
- EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::default_foreign_enum_extension));
- EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::default_import_enum_extension ));
-
- EXPECT_EQ("abc", message.GetExtension(unittest::default_string_piece_extension));
- EXPECT_EQ("123", message.GetExtension(unittest::default_cord_extension));
-
- EXPECT_FALSE(message.HasExtension(unittest::oneof_uint32_extension));
- EXPECT_FALSE(message.GetExtension(unittest::oneof_nested_message_extension).has_bb());
- EXPECT_FALSE(message.HasExtension(unittest::oneof_string_extension));
- EXPECT_FALSE(message.HasExtension(unittest::oneof_bytes_extension));
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ExpectRepeatedExtensionsModified(
- const unittest::TestAllExtensions& 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_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension ));
-
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_lazy_message_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension ));
-
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_piece_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_cord_extension));
-
- EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 0));
- EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 0));
- EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 0));
- EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 0));
- EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 0));
- EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 0));
- EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 0));
- EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 0));
- EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 0));
- EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 0));
- EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 0));
- EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 0));
- EXPECT_TRUE( message.GetExtension(unittest::repeated_bool_extension , 0));
- EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 0));
- EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 0));
-
- EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 0).a());
- EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb());
- EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c());
- EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 0).d());
- EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension , 0).bb());
-
- EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 0));
- EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 0));
- EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 0));
-
- EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 0));
- EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 0));
-
- // Actually verify the second (modified) elements now.
- EXPECT_EQ(501 , message.GetExtension(unittest::repeated_int32_extension , 1));
- EXPECT_EQ(502 , message.GetExtension(unittest::repeated_int64_extension , 1));
- EXPECT_EQ(503 , message.GetExtension(unittest::repeated_uint32_extension , 1));
- EXPECT_EQ(504 , message.GetExtension(unittest::repeated_uint64_extension , 1));
- EXPECT_EQ(505 , message.GetExtension(unittest::repeated_sint32_extension , 1));
- EXPECT_EQ(506 , message.GetExtension(unittest::repeated_sint64_extension , 1));
- EXPECT_EQ(507 , message.GetExtension(unittest::repeated_fixed32_extension , 1));
- EXPECT_EQ(508 , message.GetExtension(unittest::repeated_fixed64_extension , 1));
- EXPECT_EQ(509 , message.GetExtension(unittest::repeated_sfixed32_extension, 1));
- EXPECT_EQ(510 , message.GetExtension(unittest::repeated_sfixed64_extension, 1));
- EXPECT_EQ(511 , message.GetExtension(unittest::repeated_float_extension , 1));
- EXPECT_EQ(512 , message.GetExtension(unittest::repeated_double_extension , 1));
- EXPECT_TRUE( message.GetExtension(unittest::repeated_bool_extension , 1));
- EXPECT_EQ("515", message.GetExtension(unittest::repeated_string_extension , 1));
- EXPECT_EQ("516", message.GetExtension(unittest::repeated_bytes_extension , 1));
-
- EXPECT_EQ(517, message.GetExtension(unittest::repeatedgroup_extension , 1).a());
- EXPECT_EQ(518, message.GetExtension(unittest::repeated_nested_message_extension , 1).bb());
- EXPECT_EQ(519, message.GetExtension(unittest::repeated_foreign_message_extension, 1).c());
- EXPECT_EQ(520, message.GetExtension(unittest::repeated_import_message_extension , 1).d());
- EXPECT_EQ(527, message.GetExtension(unittest::repeated_lazy_message_extension , 1).bb());
-
- EXPECT_EQ(unittest::TestAllTypes::FOO, message.GetExtension(unittest::repeated_nested_enum_extension , 1));
- EXPECT_EQ(unittest::FOREIGN_FOO , message.GetExtension(unittest::repeated_foreign_enum_extension, 1));
- EXPECT_EQ(unittest_import::IMPORT_FOO, message.GetExtension(unittest::repeated_import_enum_extension , 1));
-
- EXPECT_EQ("524", message.GetExtension(unittest::repeated_string_piece_extension, 1));
- EXPECT_EQ("525", message.GetExtension(unittest::repeated_cord_extension, 1));
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::SetPackedExtensions(unittest::TestPackedExtensions* message) {
- message->AddExtension(unittest::packed_int32_extension , 601);
- message->AddExtension(unittest::packed_int64_extension , 602);
- message->AddExtension(unittest::packed_uint32_extension , 603);
- message->AddExtension(unittest::packed_uint64_extension , 604);
- message->AddExtension(unittest::packed_sint32_extension , 605);
- message->AddExtension(unittest::packed_sint64_extension , 606);
- message->AddExtension(unittest::packed_fixed32_extension , 607);
- message->AddExtension(unittest::packed_fixed64_extension , 608);
- message->AddExtension(unittest::packed_sfixed32_extension, 609);
- message->AddExtension(unittest::packed_sfixed64_extension, 610);
- message->AddExtension(unittest::packed_float_extension , 611);
- message->AddExtension(unittest::packed_double_extension , 612);
- message->AddExtension(unittest::packed_bool_extension , true);
- message->AddExtension(unittest::packed_enum_extension, unittest::FOREIGN_BAR);
- // add a second one of each field
- message->AddExtension(unittest::packed_int32_extension , 701);
- message->AddExtension(unittest::packed_int64_extension , 702);
- message->AddExtension(unittest::packed_uint32_extension , 703);
- message->AddExtension(unittest::packed_uint64_extension , 704);
- message->AddExtension(unittest::packed_sint32_extension , 705);
- message->AddExtension(unittest::packed_sint64_extension , 706);
- message->AddExtension(unittest::packed_fixed32_extension , 707);
- message->AddExtension(unittest::packed_fixed64_extension , 708);
- message->AddExtension(unittest::packed_sfixed32_extension, 709);
- message->AddExtension(unittest::packed_sfixed64_extension, 710);
- message->AddExtension(unittest::packed_float_extension , 711);
- message->AddExtension(unittest::packed_double_extension , 712);
- message->AddExtension(unittest::packed_bool_extension , false);
- message->AddExtension(unittest::packed_enum_extension, unittest::FOREIGN_BAZ);
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ModifyPackedExtensions(unittest::TestPackedExtensions* message) {
- message->SetExtension(unittest::packed_int32_extension , 1, 801);
- message->SetExtension(unittest::packed_int64_extension , 1, 802);
- message->SetExtension(unittest::packed_uint32_extension , 1, 803);
- message->SetExtension(unittest::packed_uint64_extension , 1, 804);
- message->SetExtension(unittest::packed_sint32_extension , 1, 805);
- message->SetExtension(unittest::packed_sint64_extension , 1, 806);
- message->SetExtension(unittest::packed_fixed32_extension , 1, 807);
- message->SetExtension(unittest::packed_fixed64_extension , 1, 808);
- message->SetExtension(unittest::packed_sfixed32_extension, 1, 809);
- message->SetExtension(unittest::packed_sfixed64_extension, 1, 810);
- message->SetExtension(unittest::packed_float_extension , 1, 811);
- message->SetExtension(unittest::packed_double_extension , 1, 812);
- message->SetExtension(unittest::packed_bool_extension , 1, true);
- message->SetExtension(unittest::packed_enum_extension , 1,
- unittest::FOREIGN_FOO);
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ExpectPackedExtensionsSet(
- const unittest::TestPackedExtensions& message) {
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed32_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed64_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_float_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_double_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_bool_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_enum_extension ));
-
- EXPECT_EQ(601 , message.GetExtension(unittest::packed_int32_extension , 0));
- EXPECT_EQ(602 , message.GetExtension(unittest::packed_int64_extension , 0));
- EXPECT_EQ(603 , message.GetExtension(unittest::packed_uint32_extension , 0));
- EXPECT_EQ(604 , message.GetExtension(unittest::packed_uint64_extension , 0));
- EXPECT_EQ(605 , message.GetExtension(unittest::packed_sint32_extension , 0));
- EXPECT_EQ(606 , message.GetExtension(unittest::packed_sint64_extension , 0));
- EXPECT_EQ(607 , message.GetExtension(unittest::packed_fixed32_extension , 0));
- EXPECT_EQ(608 , message.GetExtension(unittest::packed_fixed64_extension , 0));
- EXPECT_EQ(609 , message.GetExtension(unittest::packed_sfixed32_extension, 0));
- EXPECT_EQ(610 , message.GetExtension(unittest::packed_sfixed64_extension, 0));
- EXPECT_EQ(611 , message.GetExtension(unittest::packed_float_extension , 0));
- EXPECT_EQ(612 , message.GetExtension(unittest::packed_double_extension , 0));
- EXPECT_TRUE( message.GetExtension(unittest::packed_bool_extension , 0));
- EXPECT_EQ(unittest::FOREIGN_BAR,
- message.GetExtension(unittest::packed_enum_extension, 0));
- EXPECT_EQ(701 , message.GetExtension(unittest::packed_int32_extension , 1));
- EXPECT_EQ(702 , message.GetExtension(unittest::packed_int64_extension , 1));
- EXPECT_EQ(703 , message.GetExtension(unittest::packed_uint32_extension , 1));
- EXPECT_EQ(704 , message.GetExtension(unittest::packed_uint64_extension , 1));
- EXPECT_EQ(705 , message.GetExtension(unittest::packed_sint32_extension , 1));
- EXPECT_EQ(706 , message.GetExtension(unittest::packed_sint64_extension , 1));
- EXPECT_EQ(707 , message.GetExtension(unittest::packed_fixed32_extension , 1));
- EXPECT_EQ(708 , message.GetExtension(unittest::packed_fixed64_extension , 1));
- EXPECT_EQ(709 , message.GetExtension(unittest::packed_sfixed32_extension, 1));
- EXPECT_EQ(710 , message.GetExtension(unittest::packed_sfixed64_extension, 1));
- EXPECT_EQ(711 , message.GetExtension(unittest::packed_float_extension , 1));
- EXPECT_EQ(712 , message.GetExtension(unittest::packed_double_extension , 1));
- EXPECT_FALSE( message.GetExtension(unittest::packed_bool_extension , 1));
- EXPECT_EQ(unittest::FOREIGN_BAZ,
- message.GetExtension(unittest::packed_enum_extension, 1));
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ExpectPackedExtensionsClear(
- const unittest::TestPackedExtensions& message) {
- EXPECT_EQ(0, message.ExtensionSize(unittest::packed_int32_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::packed_int64_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::packed_uint32_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::packed_uint64_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sint32_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sint64_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::packed_fixed32_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::packed_fixed64_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sfixed32_extension));
- EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sfixed64_extension));
- EXPECT_EQ(0, message.ExtensionSize(unittest::packed_float_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::packed_double_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::packed_bool_extension ));
- EXPECT_EQ(0, message.ExtensionSize(unittest::packed_enum_extension ));
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ExpectPackedExtensionsModified(
- const unittest::TestPackedExtensions& message) {
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed32_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed64_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_float_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_double_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_bool_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::packed_enum_extension ));
- EXPECT_EQ(601 , message.GetExtension(unittest::packed_int32_extension , 0));
- EXPECT_EQ(602 , message.GetExtension(unittest::packed_int64_extension , 0));
- EXPECT_EQ(603 , message.GetExtension(unittest::packed_uint32_extension , 0));
- EXPECT_EQ(604 , message.GetExtension(unittest::packed_uint64_extension , 0));
- EXPECT_EQ(605 , message.GetExtension(unittest::packed_sint32_extension , 0));
- EXPECT_EQ(606 , message.GetExtension(unittest::packed_sint64_extension , 0));
- EXPECT_EQ(607 , message.GetExtension(unittest::packed_fixed32_extension , 0));
- EXPECT_EQ(608 , message.GetExtension(unittest::packed_fixed64_extension , 0));
- EXPECT_EQ(609 , message.GetExtension(unittest::packed_sfixed32_extension, 0));
- EXPECT_EQ(610 , message.GetExtension(unittest::packed_sfixed64_extension, 0));
- EXPECT_EQ(611 , message.GetExtension(unittest::packed_float_extension , 0));
- EXPECT_EQ(612 , message.GetExtension(unittest::packed_double_extension , 0));
- EXPECT_TRUE( message.GetExtension(unittest::packed_bool_extension , 0));
- EXPECT_EQ(unittest::FOREIGN_BAR,
- message.GetExtension(unittest::packed_enum_extension, 0));
-
- // Actually verify the second (modified) elements now.
- EXPECT_EQ(801 , message.GetExtension(unittest::packed_int32_extension , 1));
- EXPECT_EQ(802 , message.GetExtension(unittest::packed_int64_extension , 1));
- EXPECT_EQ(803 , message.GetExtension(unittest::packed_uint32_extension , 1));
- EXPECT_EQ(804 , message.GetExtension(unittest::packed_uint64_extension , 1));
- EXPECT_EQ(805 , message.GetExtension(unittest::packed_sint32_extension , 1));
- EXPECT_EQ(806 , message.GetExtension(unittest::packed_sint64_extension , 1));
- EXPECT_EQ(807 , message.GetExtension(unittest::packed_fixed32_extension , 1));
- EXPECT_EQ(808 , message.GetExtension(unittest::packed_fixed64_extension , 1));
- EXPECT_EQ(809 , message.GetExtension(unittest::packed_sfixed32_extension, 1));
- EXPECT_EQ(810 , message.GetExtension(unittest::packed_sfixed64_extension, 1));
- EXPECT_EQ(811 , message.GetExtension(unittest::packed_float_extension , 1));
- EXPECT_EQ(812 , message.GetExtension(unittest::packed_double_extension , 1));
- EXPECT_TRUE( message.GetExtension(unittest::packed_bool_extension , 1));
- EXPECT_EQ(unittest::FOREIGN_FOO,
- message.GetExtension(unittest::packed_enum_extension, 1));
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ExpectUnpackedExtensionsSet(
- const unittest::TestUnpackedExtensions& message) {
- ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_int32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_int64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_uint32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_uint64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_sint32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_sint64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_fixed32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_fixed64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_sfixed32_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_sfixed64_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_float_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_double_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_bool_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_enum_extension ));
-
- EXPECT_EQ(601 , message.GetExtension(unittest::unpacked_int32_extension , 0));
- EXPECT_EQ(602 , message.GetExtension(unittest::unpacked_int64_extension , 0));
- EXPECT_EQ(603 , message.GetExtension(unittest::unpacked_uint32_extension , 0));
- EXPECT_EQ(604 , message.GetExtension(unittest::unpacked_uint64_extension , 0));
- EXPECT_EQ(605 , message.GetExtension(unittest::unpacked_sint32_extension , 0));
- EXPECT_EQ(606 , message.GetExtension(unittest::unpacked_sint64_extension , 0));
- EXPECT_EQ(607 , message.GetExtension(unittest::unpacked_fixed32_extension , 0));
- EXPECT_EQ(608 , message.GetExtension(unittest::unpacked_fixed64_extension , 0));
- EXPECT_EQ(609 , message.GetExtension(unittest::unpacked_sfixed32_extension, 0));
- EXPECT_EQ(610 , message.GetExtension(unittest::unpacked_sfixed64_extension, 0));
- EXPECT_EQ(611 , message.GetExtension(unittest::unpacked_float_extension , 0));
- EXPECT_EQ(612 , message.GetExtension(unittest::unpacked_double_extension , 0));
- EXPECT_EQ(true , message.GetExtension(unittest::unpacked_bool_extension , 0));
- EXPECT_EQ(unittest::FOREIGN_BAR,
- message.GetExtension(unittest::unpacked_enum_extension, 0));
- EXPECT_EQ(701 , message.GetExtension(unittest::unpacked_int32_extension , 1));
- EXPECT_EQ(702 , message.GetExtension(unittest::unpacked_int64_extension , 1));
- EXPECT_EQ(703 , message.GetExtension(unittest::unpacked_uint32_extension , 1));
- EXPECT_EQ(704 , message.GetExtension(unittest::unpacked_uint64_extension , 1));
- EXPECT_EQ(705 , message.GetExtension(unittest::unpacked_sint32_extension , 1));
- EXPECT_EQ(706 , message.GetExtension(unittest::unpacked_sint64_extension , 1));
- EXPECT_EQ(707 , message.GetExtension(unittest::unpacked_fixed32_extension , 1));
- EXPECT_EQ(708 , message.GetExtension(unittest::unpacked_fixed64_extension , 1));
- EXPECT_EQ(709 , message.GetExtension(unittest::unpacked_sfixed32_extension, 1));
- EXPECT_EQ(710 , message.GetExtension(unittest::unpacked_sfixed64_extension, 1));
- EXPECT_EQ(711 , message.GetExtension(unittest::unpacked_float_extension , 1));
- EXPECT_EQ(712 , message.GetExtension(unittest::unpacked_double_extension , 1));
- EXPECT_EQ(false, message.GetExtension(unittest::unpacked_bool_extension , 1));
- EXPECT_EQ(unittest::FOREIGN_BAZ,
- message.GetExtension(unittest::unpacked_enum_extension, 1));
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ExpectAllFieldsAndExtensionsInOrder(const string& serialized) {
- // We set each field individually, serialize separately, and concatenate all
- // the strings in canonical order to determine the expected serialization.
- string expected;
- unittest::TestFieldOrderings message;
- message.set_my_int(1); // Field 1.
- message.AppendToString(&expected);
- message.Clear();
- message.SetExtension(unittest::my_extension_int, 23); // Field 5.
- message.AppendToString(&expected);
- message.Clear();
- message.set_my_string("foo"); // Field 11.
- message.AppendToString(&expected);
- message.Clear();
- message.SetExtension(unittest::my_extension_string, "bar"); // Field 50.
- message.AppendToString(&expected);
- message.Clear();
- message.set_my_float(1.0); // Field 101.
- message.AppendToString(&expected);
- message.Clear();
-
- // We don't EXPECT_EQ() since we don't want to print raw bytes to stdout.
- EXPECT_TRUE(serialized == expected);
-}
-
-void TestUtil::ExpectLastRepeatedsRemoved(
- const unittest::TestAllTypes& message) {
- ASSERT_EQ(1, message.repeated_int32_size ());
- ASSERT_EQ(1, message.repeated_int64_size ());
- ASSERT_EQ(1, message.repeated_uint32_size ());
- ASSERT_EQ(1, message.repeated_uint64_size ());
- ASSERT_EQ(1, message.repeated_sint32_size ());
- ASSERT_EQ(1, message.repeated_sint64_size ());
- ASSERT_EQ(1, message.repeated_fixed32_size ());
- ASSERT_EQ(1, message.repeated_fixed64_size ());
- ASSERT_EQ(1, message.repeated_sfixed32_size());
- ASSERT_EQ(1, message.repeated_sfixed64_size());
- ASSERT_EQ(1, message.repeated_float_size ());
- ASSERT_EQ(1, message.repeated_double_size ());
- ASSERT_EQ(1, message.repeated_bool_size ());
- ASSERT_EQ(1, message.repeated_string_size ());
- ASSERT_EQ(1, message.repeated_bytes_size ());
-
- ASSERT_EQ(1, message.repeatedgroup_size ());
- ASSERT_EQ(1, message.repeated_nested_message_size ());
- ASSERT_EQ(1, message.repeated_foreign_message_size());
- ASSERT_EQ(1, message.repeated_import_message_size ());
- ASSERT_EQ(1, message.repeated_import_message_size ());
- ASSERT_EQ(1, message.repeated_nested_enum_size ());
- ASSERT_EQ(1, message.repeated_foreign_enum_size ());
- ASSERT_EQ(1, message.repeated_import_enum_size ());
-
-#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
- ASSERT_EQ(1, message.repeated_string_piece_size());
- ASSERT_EQ(1, message.repeated_cord_size());
-#endif
-
- // Test that the remaining element is the correct one.
- EXPECT_EQ(201 , message.repeated_int32 (0));
- EXPECT_EQ(202 , message.repeated_int64 (0));
- EXPECT_EQ(203 , message.repeated_uint32 (0));
- EXPECT_EQ(204 , message.repeated_uint64 (0));
- EXPECT_EQ(205 , message.repeated_sint32 (0));
- EXPECT_EQ(206 , message.repeated_sint64 (0));
- EXPECT_EQ(207 , message.repeated_fixed32 (0));
- EXPECT_EQ(208 , message.repeated_fixed64 (0));
- EXPECT_EQ(209 , message.repeated_sfixed32(0));
- EXPECT_EQ(210 , message.repeated_sfixed64(0));
- EXPECT_EQ(211 , message.repeated_float (0));
- EXPECT_EQ(212 , message.repeated_double (0));
- EXPECT_TRUE( message.repeated_bool (0));
- EXPECT_EQ("215", message.repeated_string (0));
- EXPECT_EQ("216", message.repeated_bytes (0));
-
- EXPECT_EQ(217, message.repeatedgroup (0).a());
- EXPECT_EQ(218, message.repeated_nested_message (0).bb());
- EXPECT_EQ(219, message.repeated_foreign_message(0).c());
- EXPECT_EQ(220, message.repeated_import_message (0).d());
- EXPECT_EQ(220, message.repeated_import_message (0).d());
-
- EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (0));
- EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(0));
- EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (0));
-}
-
-void TestUtil::ExpectLastRepeatedExtensionsRemoved(
- const unittest::TestAllExtensions& message) {
-
- // Test that one element was removed.
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_int32_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_int64_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_uint32_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_uint64_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sint32_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sint64_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_fixed32_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_fixed64_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sfixed32_extension));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sfixed64_extension));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_float_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_double_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_bool_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_string_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_bytes_extension ));
-
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeatedgroup_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_nested_message_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_foreign_message_extension));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_import_message_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_lazy_message_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_nested_enum_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_foreign_enum_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_import_enum_extension ));
-
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_string_piece_extension));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_cord_extension));
-
- // Test that the remaining element is the correct one.
- EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 0));
- EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 0));
- EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 0));
- EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 0));
- EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 0));
- EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 0));
- EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 0));
- EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 0));
- EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 0));
- EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 0));
- EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 0));
- EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 0));
- EXPECT_TRUE( message.GetExtension(unittest::repeated_bool_extension , 0));
- EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 0));
- EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 0));
-
- EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 0).a());
- EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb());
- EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c());
- EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 0).d());
- EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension , 0).bb());
-
- EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 0));
- EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 0));
- EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 0));
-
- EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 0));
- EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 0));
-}
-
-void TestUtil::ExpectLastRepeatedsReleased(
- const unittest::TestAllTypes& message) {
- ASSERT_EQ(1, message.repeatedgroup_size ());
- ASSERT_EQ(1, message.repeated_nested_message_size ());
- ASSERT_EQ(1, message.repeated_foreign_message_size());
- ASSERT_EQ(1, message.repeated_import_message_size ());
- ASSERT_EQ(1, message.repeated_import_message_size ());
-
- EXPECT_EQ(217, message.repeatedgroup (0).a());
- EXPECT_EQ(218, message.repeated_nested_message (0).bb());
- EXPECT_EQ(219, message.repeated_foreign_message(0).c());
- EXPECT_EQ(220, message.repeated_import_message (0).d());
- EXPECT_EQ(220, message.repeated_import_message (0).d());
-}
-
-void TestUtil::ExpectLastRepeatedExtensionsReleased(
- const unittest::TestAllExtensions& message) {
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeatedgroup_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_nested_message_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_foreign_message_extension));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_import_message_extension ));
- ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_lazy_message_extension ));
-
- EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 0).a());
- EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb());
- EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c());
- EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 0).d());
- EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension , 0).bb());
-}
-
-void TestUtil::ExpectRepeatedsSwapped(
- const unittest::TestAllTypes& message) {
- ASSERT_EQ(2, message.repeated_int32_size ());
- ASSERT_EQ(2, message.repeated_int64_size ());
- ASSERT_EQ(2, message.repeated_uint32_size ());
- ASSERT_EQ(2, message.repeated_uint64_size ());
- ASSERT_EQ(2, message.repeated_sint32_size ());
- ASSERT_EQ(2, message.repeated_sint64_size ());
- ASSERT_EQ(2, message.repeated_fixed32_size ());
- ASSERT_EQ(2, message.repeated_fixed64_size ());
- ASSERT_EQ(2, message.repeated_sfixed32_size());
- ASSERT_EQ(2, message.repeated_sfixed64_size());
- ASSERT_EQ(2, message.repeated_float_size ());
- ASSERT_EQ(2, message.repeated_double_size ());
- ASSERT_EQ(2, message.repeated_bool_size ());
- ASSERT_EQ(2, message.repeated_string_size ());
- ASSERT_EQ(2, message.repeated_bytes_size ());
-
- ASSERT_EQ(2, message.repeatedgroup_size ());
- ASSERT_EQ(2, message.repeated_nested_message_size ());
- ASSERT_EQ(2, message.repeated_foreign_message_size());
- ASSERT_EQ(2, message.repeated_import_message_size ());
- ASSERT_EQ(2, message.repeated_import_message_size ());
- ASSERT_EQ(2, message.repeated_nested_enum_size ());
- ASSERT_EQ(2, message.repeated_foreign_enum_size ());
- ASSERT_EQ(2, message.repeated_import_enum_size ());
-
-#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
- ASSERT_EQ(2, message.repeated_string_piece_size());
- ASSERT_EQ(2, message.repeated_cord_size());
-#endif
-
- // Test that the first element and second element are flipped.
- EXPECT_EQ(201 , message.repeated_int32 (1));
- EXPECT_EQ(202 , message.repeated_int64 (1));
- EXPECT_EQ(203 , message.repeated_uint32 (1));
- EXPECT_EQ(204 , message.repeated_uint64 (1));
- EXPECT_EQ(205 , message.repeated_sint32 (1));
- EXPECT_EQ(206 , message.repeated_sint64 (1));
- EXPECT_EQ(207 , message.repeated_fixed32 (1));
- EXPECT_EQ(208 , message.repeated_fixed64 (1));
- EXPECT_EQ(209 , message.repeated_sfixed32(1));
- EXPECT_EQ(210 , message.repeated_sfixed64(1));
- EXPECT_EQ(211 , message.repeated_float (1));
- EXPECT_EQ(212 , message.repeated_double (1));
- EXPECT_TRUE( message.repeated_bool (1));
- EXPECT_EQ("215", message.repeated_string (1));
- EXPECT_EQ("216", message.repeated_bytes (1));
-
- EXPECT_EQ(217, message.repeatedgroup (1).a());
- EXPECT_EQ(218, message.repeated_nested_message (1).bb());
- EXPECT_EQ(219, message.repeated_foreign_message(1).c());
- EXPECT_EQ(220, message.repeated_import_message (1).d());
- EXPECT_EQ(220, message.repeated_import_message (1).d());
-
- EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (1));
- EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(1));
- EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (1));
-
- EXPECT_EQ(301 , message.repeated_int32 (0));
- EXPECT_EQ(302 , message.repeated_int64 (0));
- EXPECT_EQ(303 , message.repeated_uint32 (0));
- EXPECT_EQ(304 , message.repeated_uint64 (0));
- EXPECT_EQ(305 , message.repeated_sint32 (0));
- EXPECT_EQ(306 , message.repeated_sint64 (0));
- EXPECT_EQ(307 , message.repeated_fixed32 (0));
- EXPECT_EQ(308 , message.repeated_fixed64 (0));
- EXPECT_EQ(309 , message.repeated_sfixed32(0));
- EXPECT_EQ(310 , message.repeated_sfixed64(0));
- EXPECT_EQ(311 , message.repeated_float (0));
- EXPECT_EQ(312 , message.repeated_double (0));
- EXPECT_FALSE( message.repeated_bool (0));
- EXPECT_EQ("315", message.repeated_string (0));
- EXPECT_EQ("316", message.repeated_bytes (0));
-
- EXPECT_EQ(317, message.repeatedgroup (0).a());
- EXPECT_EQ(318, message.repeated_nested_message (0).bb());
- EXPECT_EQ(319, message.repeated_foreign_message(0).c());
- EXPECT_EQ(320, message.repeated_import_message (0).d());
- EXPECT_EQ(320, message.repeated_import_message (0).d());
-
- EXPECT_EQ(unittest::TestAllTypes::BAZ, message.repeated_nested_enum (0));
- EXPECT_EQ(unittest::FOREIGN_BAZ , message.repeated_foreign_enum(0));
- EXPECT_EQ(unittest_import::IMPORT_BAZ, message.repeated_import_enum (0));
-}
-
-void TestUtil::ExpectRepeatedExtensionsSwapped(
- const unittest::TestAllExtensions& message) {
-
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension ));
-
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_lazy_message_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension ));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension ));
-
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_piece_extension));
- ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_cord_extension));
-
- EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 1));
- EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 1));
- EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 1));
- EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 1));
- EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 1));
- EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 1));
- EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 1));
- EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 1));
- EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 1));
- EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 1));
- EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 1));
- EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 1));
- EXPECT_TRUE( message.GetExtension(unittest::repeated_bool_extension , 1));
- EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 1));
- EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 1));
-
- EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 1).a());
- EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 1).bb());
- EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 1).c());
- EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 1).d());
- EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension , 1).bb());
-
- EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 1));
- EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 1));
- EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 1));
-
- EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 1));
- EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 1));
-
- EXPECT_EQ(301 , message.GetExtension(unittest::repeated_int32_extension , 0));
- EXPECT_EQ(302 , message.GetExtension(unittest::repeated_int64_extension , 0));
- EXPECT_EQ(303 , message.GetExtension(unittest::repeated_uint32_extension , 0));
- EXPECT_EQ(304 , message.GetExtension(unittest::repeated_uint64_extension , 0));
- EXPECT_EQ(305 , message.GetExtension(unittest::repeated_sint32_extension , 0));
- EXPECT_EQ(306 , message.GetExtension(unittest::repeated_sint64_extension , 0));
- EXPECT_EQ(307 , message.GetExtension(unittest::repeated_fixed32_extension , 0));
- EXPECT_EQ(308 , message.GetExtension(unittest::repeated_fixed64_extension , 0));
- EXPECT_EQ(309 , message.GetExtension(unittest::repeated_sfixed32_extension, 0));
- EXPECT_EQ(310 , message.GetExtension(unittest::repeated_sfixed64_extension, 0));
- EXPECT_EQ(311 , message.GetExtension(unittest::repeated_float_extension , 0));
- EXPECT_EQ(312 , message.GetExtension(unittest::repeated_double_extension , 0));
- EXPECT_FALSE( message.GetExtension(unittest::repeated_bool_extension , 0));
- EXPECT_EQ("315", message.GetExtension(unittest::repeated_string_extension , 0));
- EXPECT_EQ("316", message.GetExtension(unittest::repeated_bytes_extension , 0));
-
- EXPECT_EQ(317, message.GetExtension(unittest::repeatedgroup_extension , 0).a());
- EXPECT_EQ(318, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb());
- EXPECT_EQ(319, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c());
- EXPECT_EQ(320, message.GetExtension(unittest::repeated_import_message_extension , 0).d());
- EXPECT_EQ(327, message.GetExtension(unittest::repeated_lazy_message_extension , 0).bb());
-
- EXPECT_EQ(unittest::TestAllTypes::BAZ, message.GetExtension(unittest::repeated_nested_enum_extension , 0));
- EXPECT_EQ(unittest::FOREIGN_BAZ , message.GetExtension(unittest::repeated_foreign_enum_extension, 0));
- EXPECT_EQ(unittest_import::IMPORT_BAZ, message.GetExtension(unittest::repeated_import_enum_extension , 0));
-
- EXPECT_EQ("324", message.GetExtension(unittest::repeated_string_piece_extension, 0));
- EXPECT_EQ("325", message.GetExtension(unittest::repeated_cord_extension, 0));
-}
-
-void TestUtil::SetOneof1(unittest::TestOneof2* message) {
- message->mutable_foo_lazy_message()->set_qux_int(100);
- message->set_bar_string("101");
- message->set_baz_int(102);
- message->set_baz_string("103");
-}
-
-void TestUtil::SetOneof2(unittest::TestOneof2* message) {
- message->set_foo_int(200);
- message->set_bar_enum(unittest::TestOneof2::BAZ);
- message->set_baz_int(202);
- message->set_baz_string("203");
-}
-
-void TestUtil::ExpectOneofSet1(const unittest::TestOneof2& message) {
- ExpectAtMostOneFieldSetInOneof(message);
-
- EXPECT_TRUE(message.has_foo_lazy_message ());
- EXPECT_TRUE(message.foo_lazy_message().has_qux_int());
-
- EXPECT_TRUE(message.has_bar_string());
- EXPECT_TRUE(message.has_baz_int ());
- EXPECT_TRUE(message.has_baz_string());
-
- ASSERT_EQ(0, message.foo_lazy_message().corge_int_size());
-
- EXPECT_EQ(100 , message.foo_lazy_message().qux_int());
- EXPECT_EQ("101", message.bar_string ());
- EXPECT_EQ(102 , message.baz_int ());
- EXPECT_EQ("103", message.baz_string ());
-}
-
-void TestUtil::ExpectOneofSet2(const unittest::TestOneof2& message) {
- ExpectAtMostOneFieldSetInOneof(message);
-
- EXPECT_TRUE(message.has_foo_int ());
- EXPECT_TRUE(message.has_bar_enum ());
- EXPECT_TRUE(message.has_baz_int ());
- EXPECT_TRUE(message.has_baz_string());
-
- EXPECT_EQ(200 , message.foo_int ());
- EXPECT_EQ(unittest::TestOneof2::BAZ, message.bar_enum ());
- EXPECT_EQ(202 , message.baz_int ());
- EXPECT_EQ("203" , message.baz_string());
-}
-
-void TestUtil::ExpectOneofClear(const unittest::TestOneof2& message) {
- EXPECT_FALSE(message.has_foo_int());
- EXPECT_FALSE(message.has_foo_string());
- EXPECT_FALSE(message.has_foo_bytes());
- EXPECT_FALSE(message.has_foo_enum());
- EXPECT_FALSE(message.has_foo_message());
- EXPECT_FALSE(message.has_foogroup());
- EXPECT_FALSE(message.has_foo_lazy_message());
-
- EXPECT_FALSE(message.has_bar_int());
- EXPECT_FALSE(message.has_bar_string());
- EXPECT_FALSE(message.has_bar_bytes());
- EXPECT_FALSE(message.has_bar_enum());
-
- EXPECT_FALSE(message.has_baz_int());
- EXPECT_FALSE(message.has_baz_string());
-
- EXPECT_EQ(unittest::TestOneof2::FOO_NOT_SET, message.foo_case());
- EXPECT_EQ(unittest::TestOneof2::BAR_NOT_SET, message.bar_case());
-}
-
-void TestUtil::ExpectAtMostOneFieldSetInOneof(
- const unittest::TestOneof2& message) {
- int count = 0;
- if (message.has_foo_int()) count++;
- if (message.has_foo_string()) count++;
- if (message.has_foo_bytes()) count++;
- if (message.has_foo_enum()) count++;
- if (message.has_foo_message()) count++;
- if (message.has_foogroup()) count++;
- if (message.has_foo_lazy_message()) count++;
- EXPECT_LE(count, 1);
- count = 0;
- if (message.has_bar_int()) count++;
- if (message.has_bar_string()) count++;
- if (message.has_bar_bytes()) count++;
- if (message.has_bar_enum()) count++;
- EXPECT_TRUE(count == 0 || count == 1);
-}
-
-// ===================================================================
-
-TestUtil::ReflectionTester::ReflectionTester(
- const Descriptor* base_descriptor)
- : base_descriptor_(base_descriptor) {
-
- const DescriptorPool* pool = base_descriptor->file()->pool();
-
- nested_b_ =
- pool->FindFieldByName("protobuf_unittest.TestAllTypes.NestedMessage.bb");
- foreign_c_ =
- pool->FindFieldByName("protobuf_unittest.ForeignMessage.c");
- import_d_ =
- pool->FindFieldByName("protobuf_unittest_import.ImportMessage.d");
- import_e_ =
- pool->FindFieldByName("protobuf_unittest_import.PublicImportMessage.e");
- nested_foo_ =
- pool->FindEnumValueByName("protobuf_unittest.TestAllTypes.FOO");
- nested_bar_ =
- pool->FindEnumValueByName("protobuf_unittest.TestAllTypes.BAR");
- nested_baz_ =
- pool->FindEnumValueByName("protobuf_unittest.TestAllTypes.BAZ");
- foreign_foo_ =
- pool->FindEnumValueByName("protobuf_unittest.FOREIGN_FOO");
- foreign_bar_ =
- pool->FindEnumValueByName("protobuf_unittest.FOREIGN_BAR");
- foreign_baz_ =
- pool->FindEnumValueByName("protobuf_unittest.FOREIGN_BAZ");
- import_foo_ =
- pool->FindEnumValueByName("protobuf_unittest_import.IMPORT_FOO");
- import_bar_ =
- pool->FindEnumValueByName("protobuf_unittest_import.IMPORT_BAR");
- import_baz_ =
- pool->FindEnumValueByName("protobuf_unittest_import.IMPORT_BAZ");
-
- if (base_descriptor_->name() == "TestAllExtensions") {
- group_a_ =
- pool->FindFieldByName("protobuf_unittest.OptionalGroup_extension.a");
- repeated_group_a_ =
- pool->FindFieldByName("protobuf_unittest.RepeatedGroup_extension.a");
- } else {
- group_a_ =
- pool->FindFieldByName("protobuf_unittest.TestAllTypes.OptionalGroup.a");
- repeated_group_a_ =
- pool->FindFieldByName("protobuf_unittest.TestAllTypes.RepeatedGroup.a");
- }
-
- EXPECT_TRUE(group_a_ != NULL);
- EXPECT_TRUE(repeated_group_a_ != NULL);
- EXPECT_TRUE(nested_b_ != NULL);
- EXPECT_TRUE(foreign_c_ != NULL);
- EXPECT_TRUE(import_d_ != NULL);
- EXPECT_TRUE(import_e_ != NULL);
- EXPECT_TRUE(nested_foo_ != NULL);
- EXPECT_TRUE(nested_bar_ != NULL);
- EXPECT_TRUE(nested_baz_ != NULL);
- EXPECT_TRUE(foreign_foo_ != NULL);
- EXPECT_TRUE(foreign_bar_ != NULL);
- EXPECT_TRUE(foreign_baz_ != NULL);
- EXPECT_TRUE(import_foo_ != NULL);
- EXPECT_TRUE(import_bar_ != NULL);
- EXPECT_TRUE(import_baz_ != NULL);
-}
-
-// Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes.
-const FieldDescriptor* TestUtil::ReflectionTester::F(const string& name) {
- const FieldDescriptor* result = NULL;
- if (base_descriptor_->name() == "TestAllExtensions" ||
- base_descriptor_->name() == "TestPackedExtensions") {
- result = base_descriptor_->file()->FindExtensionByName(name + "_extension");
- } else {
- result = base_descriptor_->FindFieldByName(name);
- }
- GOOGLE_CHECK(result != NULL);
- return result;
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ReflectionTester::SetAllFieldsViaReflection(Message* message) {
- const Reflection* reflection = message->GetReflection();
- Message* sub_message;
-
- reflection->SetInt32 (message, F("optional_int32" ), 101);
- reflection->SetInt64 (message, F("optional_int64" ), 102);
- reflection->SetUInt32(message, F("optional_uint32" ), 103);
- reflection->SetUInt64(message, F("optional_uint64" ), 104);
- reflection->SetInt32 (message, F("optional_sint32" ), 105);
- reflection->SetInt64 (message, F("optional_sint64" ), 106);
- reflection->SetUInt32(message, F("optional_fixed32" ), 107);
- reflection->SetUInt64(message, F("optional_fixed64" ), 108);
- reflection->SetInt32 (message, F("optional_sfixed32"), 109);
- reflection->SetInt64 (message, F("optional_sfixed64"), 110);
- reflection->SetFloat (message, F("optional_float" ), 111);
- reflection->SetDouble(message, F("optional_double" ), 112);
- reflection->SetBool (message, F("optional_bool" ), true);
- reflection->SetString(message, F("optional_string" ), "115");
- reflection->SetString(message, F("optional_bytes" ), "116");
-
- sub_message = reflection->MutableMessage(message, F("optionalgroup"));
- sub_message->GetReflection()->SetInt32(sub_message, group_a_, 117);
- sub_message = reflection->MutableMessage(message, F("optional_nested_message"));
- sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 118);
- sub_message = reflection->MutableMessage(message, F("optional_foreign_message"));
- sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 119);
- sub_message = reflection->MutableMessage(message, F("optional_import_message"));
- sub_message->GetReflection()->SetInt32(sub_message, import_d_, 120);
-
- reflection->SetEnum(message, F("optional_nested_enum" ), nested_baz_);
- reflection->SetEnum(message, F("optional_foreign_enum"), foreign_baz_);
- reflection->SetEnum(message, F("optional_import_enum" ), import_baz_);
-
- reflection->SetString(message, F("optional_string_piece"), "124");
- reflection->SetString(message, F("optional_cord"), "125");
-
- sub_message = reflection->MutableMessage(message, F("optional_public_import_message"));
- sub_message->GetReflection()->SetInt32(sub_message, import_e_, 126);
-
- sub_message = reflection->MutableMessage(message, F("optional_lazy_message"));
- sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 127);
-
- // -----------------------------------------------------------------
-
- reflection->AddInt32 (message, F("repeated_int32" ), 201);
- reflection->AddInt64 (message, F("repeated_int64" ), 202);
- reflection->AddUInt32(message, F("repeated_uint32" ), 203);
- reflection->AddUInt64(message, F("repeated_uint64" ), 204);
- reflection->AddInt32 (message, F("repeated_sint32" ), 205);
- reflection->AddInt64 (message, F("repeated_sint64" ), 206);
- reflection->AddUInt32(message, F("repeated_fixed32" ), 207);
- reflection->AddUInt64(message, F("repeated_fixed64" ), 208);
- reflection->AddInt32 (message, F("repeated_sfixed32"), 209);
- reflection->AddInt64 (message, F("repeated_sfixed64"), 210);
- reflection->AddFloat (message, F("repeated_float" ), 211);
- reflection->AddDouble(message, F("repeated_double" ), 212);
- reflection->AddBool (message, F("repeated_bool" ), true);
- reflection->AddString(message, F("repeated_string" ), "215");
- reflection->AddString(message, F("repeated_bytes" ), "216");
-
- sub_message = reflection->AddMessage(message, F("repeatedgroup"));
- sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 217);
- sub_message = reflection->AddMessage(message, F("repeated_nested_message"));
- sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 218);
- sub_message = reflection->AddMessage(message, F("repeated_foreign_message"));
- sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 219);
- sub_message = reflection->AddMessage(message, F("repeated_import_message"));
- sub_message->GetReflection()->SetInt32(sub_message, import_d_, 220);
- sub_message = reflection->AddMessage(message, F("repeated_lazy_message"));
- sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 227);
-
- reflection->AddEnum(message, F("repeated_nested_enum" ), nested_bar_);
- reflection->AddEnum(message, F("repeated_foreign_enum"), foreign_bar_);
- reflection->AddEnum(message, F("repeated_import_enum" ), import_bar_);
-
- reflection->AddString(message, F("repeated_string_piece"), "224");
- reflection->AddString(message, F("repeated_cord"), "225");
-
- // Add a second one of each field.
- reflection->AddInt32 (message, F("repeated_int32" ), 301);
- reflection->AddInt64 (message, F("repeated_int64" ), 302);
- reflection->AddUInt32(message, F("repeated_uint32" ), 303);
- reflection->AddUInt64(message, F("repeated_uint64" ), 304);
- reflection->AddInt32 (message, F("repeated_sint32" ), 305);
- reflection->AddInt64 (message, F("repeated_sint64" ), 306);
- reflection->AddUInt32(message, F("repeated_fixed32" ), 307);
- reflection->AddUInt64(message, F("repeated_fixed64" ), 308);
- reflection->AddInt32 (message, F("repeated_sfixed32"), 309);
- reflection->AddInt64 (message, F("repeated_sfixed64"), 310);
- reflection->AddFloat (message, F("repeated_float" ), 311);
- reflection->AddDouble(message, F("repeated_double" ), 312);
- reflection->AddBool (message, F("repeated_bool" ), false);
- reflection->AddString(message, F("repeated_string" ), "315");
- reflection->AddString(message, F("repeated_bytes" ), "316");
-
- sub_message = reflection->AddMessage(message, F("repeatedgroup"));
- sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 317);
- sub_message = reflection->AddMessage(message, F("repeated_nested_message"));
- sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 318);
- sub_message = reflection->AddMessage(message, F("repeated_foreign_message"));
- sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 319);
- sub_message = reflection->AddMessage(message, F("repeated_import_message"));
- sub_message->GetReflection()->SetInt32(sub_message, import_d_, 320);
- sub_message = reflection->AddMessage(message, F("repeated_lazy_message"));
- sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 327);
-
- reflection->AddEnum(message, F("repeated_nested_enum" ), nested_baz_);
- reflection->AddEnum(message, F("repeated_foreign_enum"), foreign_baz_);
- reflection->AddEnum(message, F("repeated_import_enum" ), import_baz_);
-
- reflection->AddString(message, F("repeated_string_piece"), "324");
- reflection->AddString(message, F("repeated_cord"), "325");
-
- // -----------------------------------------------------------------
-
- reflection->SetInt32 (message, F("default_int32" ), 401);
- reflection->SetInt64 (message, F("default_int64" ), 402);
- reflection->SetUInt32(message, F("default_uint32" ), 403);
- reflection->SetUInt64(message, F("default_uint64" ), 404);
- reflection->SetInt32 (message, F("default_sint32" ), 405);
- reflection->SetInt64 (message, F("default_sint64" ), 406);
- reflection->SetUInt32(message, F("default_fixed32" ), 407);
- reflection->SetUInt64(message, F("default_fixed64" ), 408);
- reflection->SetInt32 (message, F("default_sfixed32"), 409);
- reflection->SetInt64 (message, F("default_sfixed64"), 410);
- reflection->SetFloat (message, F("default_float" ), 411);
- reflection->SetDouble(message, F("default_double" ), 412);
- reflection->SetBool (message, F("default_bool" ), false);
- reflection->SetString(message, F("default_string" ), "415");
- reflection->SetString(message, F("default_bytes" ), "416");
-
- reflection->SetEnum(message, F("default_nested_enum" ), nested_foo_);
- reflection->SetEnum(message, F("default_foreign_enum"), foreign_foo_);
- reflection->SetEnum(message, F("default_import_enum" ), import_foo_);
-
- reflection->SetString(message, F("default_string_piece"), "424");
- reflection->SetString(message, F("default_cord"), "425");
-
- reflection->SetUInt32(message, F("oneof_uint32" ), 601);
- sub_message = reflection->MutableMessage(message, F("oneof_nested_message"));
- sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 602);
- reflection->SetString(message, F("oneof_string"), "603");
- reflection->SetString(message, F("oneof_bytes" ), "604");
-}
-
-void TestUtil::ReflectionTester::SetOneofViaReflection(Message* message) {
- const Descriptor* descriptor = message->GetDescriptor();
- const Reflection* reflection = message->GetReflection();
- Message* sub_message = reflection->MutableMessage(
- message, descriptor->FindFieldByName("foo_lazy_message"));
- sub_message->GetReflection()->SetInt64(
- sub_message,
- descriptor->file()->pool()->FindFieldByName(
- "protobuf_unittest.TestOneof2.NestedMessage.qux_int"),
- 100);
-
- reflection->SetString(message,
- descriptor->FindFieldByName("bar_cord"),
- "101");
- reflection->SetInt32(message,
- descriptor->FindFieldByName("baz_int"),
- 102);
- reflection->SetString(message,
- descriptor->FindFieldByName("baz_string"),
- "103");
-}
-
-void TestUtil::ReflectionTester::ExpectOneofSetViaReflection(
- const Message& message) {
- const Descriptor* descriptor = message.GetDescriptor();
- const Reflection* reflection = message.GetReflection();
- string scratch;
- EXPECT_TRUE(reflection->HasField(
- message, descriptor->FindFieldByName("foo_lazy_message")));
- EXPECT_TRUE(reflection->HasField(
- message, descriptor->FindFieldByName("bar_cord")));
- EXPECT_TRUE(reflection->HasField(
- message, descriptor->FindFieldByName("baz_int")));
- EXPECT_TRUE(reflection->HasField(
- message, descriptor->FindFieldByName("baz_string")));
-
- const Message* sub_message = &reflection->GetMessage(
- message, descriptor->FindFieldByName("foo_lazy_message"));
- EXPECT_EQ(100, sub_message->GetReflection()->GetInt64(
- *sub_message,
- descriptor->file()->pool()->FindFieldByName(
- "protobuf_unittest.TestOneof2.NestedMessage.qux_int")));
-
- EXPECT_EQ("101", reflection->GetString(
- message, descriptor->FindFieldByName("bar_cord")));
- EXPECT_EQ("101", reflection->GetStringReference(
- message, descriptor->FindFieldByName("bar_cord"), &scratch));
-
- EXPECT_EQ(102, reflection->GetInt32(
- message, descriptor->FindFieldByName("baz_int")));
-
- EXPECT_EQ("103", reflection->GetString(
- message, descriptor->FindFieldByName("baz_string")));
- EXPECT_EQ("103", reflection->GetStringReference(
- message, descriptor->FindFieldByName("baz_string"), &scratch));
-}
-
-void TestUtil::ReflectionTester::SetPackedFieldsViaReflection(
- Message* message) {
- const Reflection* reflection = message->GetReflection();
- reflection->AddInt32 (message, F("packed_int32" ), 601);
- reflection->AddInt64 (message, F("packed_int64" ), 602);
- reflection->AddUInt32(message, F("packed_uint32" ), 603);
- reflection->AddUInt64(message, F("packed_uint64" ), 604);
- reflection->AddInt32 (message, F("packed_sint32" ), 605);
- reflection->AddInt64 (message, F("packed_sint64" ), 606);
- reflection->AddUInt32(message, F("packed_fixed32" ), 607);
- reflection->AddUInt64(message, F("packed_fixed64" ), 608);
- reflection->AddInt32 (message, F("packed_sfixed32"), 609);
- reflection->AddInt64 (message, F("packed_sfixed64"), 610);
- reflection->AddFloat (message, F("packed_float" ), 611);
- reflection->AddDouble(message, F("packed_double" ), 612);
- reflection->AddBool (message, F("packed_bool" ), true);
- reflection->AddEnum (message, F("packed_enum" ), foreign_bar_);
-
- reflection->AddInt32 (message, F("packed_int32" ), 701);
- reflection->AddInt64 (message, F("packed_int64" ), 702);
- reflection->AddUInt32(message, F("packed_uint32" ), 703);
- reflection->AddUInt64(message, F("packed_uint64" ), 704);
- reflection->AddInt32 (message, F("packed_sint32" ), 705);
- reflection->AddInt64 (message, F("packed_sint64" ), 706);
- reflection->AddUInt32(message, F("packed_fixed32" ), 707);
- reflection->AddUInt64(message, F("packed_fixed64" ), 708);
- reflection->AddInt32 (message, F("packed_sfixed32"), 709);
- reflection->AddInt64 (message, F("packed_sfixed64"), 710);
- reflection->AddFloat (message, F("packed_float" ), 711);
- reflection->AddDouble(message, F("packed_double" ), 712);
- reflection->AddBool (message, F("packed_bool" ), false);
- reflection->AddEnum (message, F("packed_enum" ), foreign_baz_);
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection(
- const Message& message) {
- // We have to split this into three function otherwise it creates a stack
- // frame so large that it triggers a warning.
- ExpectAllFieldsSetViaReflection1(message);
- ExpectAllFieldsSetViaReflection2(message);
- ExpectAllFieldsSetViaReflection3(message);
-}
-
-void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection1(
- const Message& message) {
- const Reflection* reflection = message.GetReflection();
- string scratch;
- const Message* sub_message;
-
- EXPECT_TRUE(reflection->HasField(message, F("optional_int32" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_int64" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_uint32" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_uint64" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_sint32" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_sint64" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_fixed32" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_fixed64" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_sfixed32")));
- EXPECT_TRUE(reflection->HasField(message, F("optional_sfixed64")));
- EXPECT_TRUE(reflection->HasField(message, F("optional_float" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_double" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_bool" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_string" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_bytes" )));
-
- EXPECT_TRUE(reflection->HasField(message, F("optionalgroup" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_nested_message" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_foreign_message" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_import_message" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_public_import_message")));
- EXPECT_TRUE(reflection->HasField(message, F("optional_lazy_message" )));
-
- sub_message = &reflection->GetMessage(message, F("optionalgroup"));
- EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, group_a_));
- sub_message = &reflection->GetMessage(message, F("optional_nested_message"));
- EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, nested_b_));
- sub_message = &reflection->GetMessage(message, F("optional_foreign_message"));
- EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, foreign_c_));
- sub_message = &reflection->GetMessage(message, F("optional_import_message"));
- EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, import_d_));
- sub_message = &reflection->GetMessage(message, F("optional_public_import_message"));
- EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, import_e_));
- sub_message = &reflection->GetMessage(message, F("optional_lazy_message"));
- EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, nested_b_));
-
- EXPECT_TRUE(reflection->HasField(message, F("optional_nested_enum" )));
- EXPECT_TRUE(reflection->HasField(message, F("optional_foreign_enum")));
- EXPECT_TRUE(reflection->HasField(message, F("optional_import_enum" )));
-
- EXPECT_TRUE(reflection->HasField(message, F("optional_string_piece")));
- EXPECT_TRUE(reflection->HasField(message, F("optional_cord")));
-
- EXPECT_EQ(101 , reflection->GetInt32 (message, F("optional_int32" )));
- EXPECT_EQ(102 , reflection->GetInt64 (message, F("optional_int64" )));
- EXPECT_EQ(103 , reflection->GetUInt32(message, F("optional_uint32" )));
- EXPECT_EQ(104 , reflection->GetUInt64(message, F("optional_uint64" )));
- EXPECT_EQ(105 , reflection->GetInt32 (message, F("optional_sint32" )));
- EXPECT_EQ(106 , reflection->GetInt64 (message, F("optional_sint64" )));
- EXPECT_EQ(107 , reflection->GetUInt32(message, F("optional_fixed32" )));
- EXPECT_EQ(108 , reflection->GetUInt64(message, F("optional_fixed64" )));
- EXPECT_EQ(109 , reflection->GetInt32 (message, F("optional_sfixed32")));
- EXPECT_EQ(110 , reflection->GetInt64 (message, F("optional_sfixed64")));
- EXPECT_EQ(111 , reflection->GetFloat (message, F("optional_float" )));
- EXPECT_EQ(112 , reflection->GetDouble(message, F("optional_double" )));
- EXPECT_TRUE( reflection->GetBool (message, F("optional_bool" )));
- EXPECT_EQ("115", reflection->GetString(message, F("optional_string" )));
- EXPECT_EQ("116", reflection->GetString(message, F("optional_bytes" )));
-
- EXPECT_EQ("115", reflection->GetStringReference(message, F("optional_string"), &scratch));
- EXPECT_EQ("116", reflection->GetStringReference(message, F("optional_bytes" ), &scratch));
-
- sub_message = &reflection->GetMessage(message, F("optionalgroup"));
- EXPECT_EQ(117, sub_message->GetReflection()->GetInt32(*sub_message, group_a_));
- sub_message = &reflection->GetMessage(message, F("optional_nested_message"));
- EXPECT_EQ(118, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
- sub_message = &reflection->GetMessage(message, F("optional_foreign_message"));
- EXPECT_EQ(119, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_));
- sub_message = &reflection->GetMessage(message, F("optional_import_message"));
- EXPECT_EQ(120, sub_message->GetReflection()->GetInt32(*sub_message, import_d_));
- sub_message = &reflection->GetMessage(message, F("optional_public_import_message"));
- EXPECT_EQ(126, sub_message->GetReflection()->GetInt32(*sub_message, import_e_));
- sub_message = &reflection->GetMessage(message, F("optional_lazy_message"));
- EXPECT_EQ(127, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
-
- EXPECT_EQ( nested_baz_, reflection->GetEnum(message, F("optional_nested_enum" )));
- EXPECT_EQ(foreign_baz_, reflection->GetEnum(message, F("optional_foreign_enum")));
- EXPECT_EQ( import_baz_, reflection->GetEnum(message, F("optional_import_enum" )));
-
- EXPECT_EQ("124", reflection->GetString(message, F("optional_string_piece")));
- EXPECT_EQ("124", reflection->GetStringReference(message, F("optional_string_piece"), &scratch));
-
- EXPECT_EQ("125", reflection->GetString(message, F("optional_cord")));
- EXPECT_EQ("125", reflection->GetStringReference(message, F("optional_cord"), &scratch));
-
- EXPECT_TRUE(reflection->HasField(message, F("oneof_bytes" )));
- EXPECT_EQ("604", reflection->GetString(message, F("oneof_bytes" )));
-
- if (base_descriptor_->name() == "TestAllTypes") {
- EXPECT_FALSE(reflection->HasField(message, F("oneof_uint32")));
- EXPECT_FALSE(reflection->HasField(message, F("oneof_string")));
- } else {
- EXPECT_TRUE(reflection->HasField(message, F("oneof_uint32")));
- EXPECT_TRUE(reflection->HasField(message, F("oneof_string")));
- EXPECT_EQ(601 , reflection->GetUInt32(message, F("oneof_uint32")));
- EXPECT_EQ("603", reflection->GetString(message, F("oneof_string")));
- sub_message = &reflection->GetMessage(message, F("oneof_nested_message"));
- EXPECT_EQ(602, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
- }
-}
-
-void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection2(
- const Message& message) {
- const Reflection* reflection = message.GetReflection();
- string scratch;
- const Message* sub_message;
-
- // -----------------------------------------------------------------
-
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_int32" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_int64" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_uint32" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_uint64" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sint32" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sint64" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_fixed32" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_fixed64" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sfixed32")));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sfixed64")));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_float" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_double" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_bool" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_string" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_bytes" )));
-
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeatedgroup" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_nested_message" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_foreign_message")));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_import_message" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_lazy_message" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_nested_enum" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_foreign_enum" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_import_enum" )));
-
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_string_piece")));
- ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_cord")));
-
- EXPECT_EQ(201 , reflection->GetRepeatedInt32 (message, F("repeated_int32" ), 0));
- EXPECT_EQ(202 , reflection->GetRepeatedInt64 (message, F("repeated_int64" ), 0));
- EXPECT_EQ(203 , reflection->GetRepeatedUInt32(message, F("repeated_uint32" ), 0));
- EXPECT_EQ(204 , reflection->GetRepeatedUInt64(message, F("repeated_uint64" ), 0));
- EXPECT_EQ(205 , reflection->GetRepeatedInt32 (message, F("repeated_sint32" ), 0));
- EXPECT_EQ(206 , reflection->GetRepeatedInt64 (message, F("repeated_sint64" ), 0));
- EXPECT_EQ(207 , reflection->GetRepeatedUInt32(message, F("repeated_fixed32" ), 0));
- EXPECT_EQ(208 , reflection->GetRepeatedUInt64(message, F("repeated_fixed64" ), 0));
- EXPECT_EQ(209 , reflection->GetRepeatedInt32 (message, F("repeated_sfixed32"), 0));
- EXPECT_EQ(210 , reflection->GetRepeatedInt64 (message, F("repeated_sfixed64"), 0));
- EXPECT_EQ(211 , reflection->GetRepeatedFloat (message, F("repeated_float" ), 0));
- EXPECT_EQ(212 , reflection->GetRepeatedDouble(message, F("repeated_double" ), 0));
- EXPECT_TRUE( reflection->GetRepeatedBool (message, F("repeated_bool" ), 0));
- EXPECT_EQ("215", reflection->GetRepeatedString(message, F("repeated_string" ), 0));
- EXPECT_EQ("216", reflection->GetRepeatedString(message, F("repeated_bytes" ), 0));
-
- EXPECT_EQ("215", reflection->GetRepeatedStringReference(message, F("repeated_string"), 0, &scratch));
- EXPECT_EQ("216", reflection->GetRepeatedStringReference(message, F("repeated_bytes"), 0, &scratch));
-
- sub_message = &reflection->GetRepeatedMessage(message, F("repeatedgroup"), 0);
- EXPECT_EQ(217, sub_message->GetReflection()->GetInt32(*sub_message, repeated_group_a_));
- sub_message = &reflection->GetRepeatedMessage(message, F("repeated_nested_message"), 0);
- EXPECT_EQ(218, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
- sub_message = &reflection->GetRepeatedMessage(message, F("repeated_foreign_message"), 0);
- EXPECT_EQ(219, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_));
- sub_message = &reflection->GetRepeatedMessage(message, F("repeated_import_message"), 0);
- EXPECT_EQ(220, sub_message->GetReflection()->GetInt32(*sub_message, import_d_));
- sub_message = &reflection->GetRepeatedMessage(message, F("repeated_lazy_message"), 0);
- EXPECT_EQ(227, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
-
- EXPECT_EQ( nested_bar_, reflection->GetRepeatedEnum(message, F("repeated_nested_enum" ),0));
- EXPECT_EQ(foreign_bar_, reflection->GetRepeatedEnum(message, F("repeated_foreign_enum"),0));
- EXPECT_EQ( import_bar_, reflection->GetRepeatedEnum(message, F("repeated_import_enum" ),0));
-
- EXPECT_EQ("224", reflection->GetRepeatedString(message, F("repeated_string_piece"), 0));
- EXPECT_EQ("224", reflection->GetRepeatedStringReference(
- message, F("repeated_string_piece"), 0, &scratch));
-
- EXPECT_EQ("225", reflection->GetRepeatedString(message, F("repeated_cord"), 0));
- EXPECT_EQ("225", reflection->GetRepeatedStringReference(
- message, F("repeated_cord"), 0, &scratch));
-
- EXPECT_EQ(301 , reflection->GetRepeatedInt32 (message, F("repeated_int32" ), 1));
- EXPECT_EQ(302 , reflection->GetRepeatedInt64 (message, F("repeated_int64" ), 1));
- EXPECT_EQ(303 , reflection->GetRepeatedUInt32(message, F("repeated_uint32" ), 1));
- EXPECT_EQ(304 , reflection->GetRepeatedUInt64(message, F("repeated_uint64" ), 1));
- EXPECT_EQ(305 , reflection->GetRepeatedInt32 (message, F("repeated_sint32" ), 1));
- EXPECT_EQ(306 , reflection->GetRepeatedInt64 (message, F("repeated_sint64" ), 1));
- EXPECT_EQ(307 , reflection->GetRepeatedUInt32(message, F("repeated_fixed32" ), 1));
- EXPECT_EQ(308 , reflection->GetRepeatedUInt64(message, F("repeated_fixed64" ), 1));
- EXPECT_EQ(309 , reflection->GetRepeatedInt32 (message, F("repeated_sfixed32"), 1));
- EXPECT_EQ(310 , reflection->GetRepeatedInt64 (message, F("repeated_sfixed64"), 1));
- EXPECT_EQ(311 , reflection->GetRepeatedFloat (message, F("repeated_float" ), 1));
- EXPECT_EQ(312 , reflection->GetRepeatedDouble(message, F("repeated_double" ), 1));
- EXPECT_FALSE( reflection->GetRepeatedBool (message, F("repeated_bool" ), 1));
- EXPECT_EQ("315", reflection->GetRepeatedString(message, F("repeated_string" ), 1));
- EXPECT_EQ("316", reflection->GetRepeatedString(message, F("repeated_bytes" ), 1));
-
- EXPECT_EQ("315", reflection->GetRepeatedStringReference(message, F("repeated_string"),
- 1, &scratch));
- EXPECT_EQ("316", reflection->GetRepeatedStringReference(message, F("repeated_bytes"),
- 1, &scratch));
-
- sub_message = &reflection->GetRepeatedMessage(message, F("repeatedgroup"), 1);
- EXPECT_EQ(317, sub_message->GetReflection()->GetInt32(*sub_message, repeated_group_a_));
- sub_message = &reflection->GetRepeatedMessage(message, F("repeated_nested_message"), 1);
- EXPECT_EQ(318, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
- sub_message = &reflection->GetRepeatedMessage(message, F("repeated_foreign_message"), 1);
- EXPECT_EQ(319, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_));
- sub_message = &reflection->GetRepeatedMessage(message, F("repeated_import_message"), 1);
- EXPECT_EQ(320, sub_message->GetReflection()->GetInt32(*sub_message, import_d_));
- sub_message = &reflection->GetRepeatedMessage(message, F("repeated_lazy_message"), 1);
- EXPECT_EQ(327, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
-
- EXPECT_EQ( nested_baz_, reflection->GetRepeatedEnum(message, F("repeated_nested_enum" ),1));
- EXPECT_EQ(foreign_baz_, reflection->GetRepeatedEnum(message, F("repeated_foreign_enum"),1));
- EXPECT_EQ( import_baz_, reflection->GetRepeatedEnum(message, F("repeated_import_enum" ),1));
-
- EXPECT_EQ("324", reflection->GetRepeatedString(message, F("repeated_string_piece"), 1));
- EXPECT_EQ("324", reflection->GetRepeatedStringReference(
- message, F("repeated_string_piece"), 1, &scratch));
-
- EXPECT_EQ("325", reflection->GetRepeatedString(message, F("repeated_cord"), 1));
- EXPECT_EQ("325", reflection->GetRepeatedStringReference(
- message, F("repeated_cord"), 1, &scratch));
-}
-
-void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection3(
- const Message& message) {
- const Reflection* reflection = message.GetReflection();
- string scratch;
-
- // -----------------------------------------------------------------
-
- EXPECT_TRUE(reflection->HasField(message, F("default_int32" )));
- EXPECT_TRUE(reflection->HasField(message, F("default_int64" )));
- EXPECT_TRUE(reflection->HasField(message, F("default_uint32" )));
- EXPECT_TRUE(reflection->HasField(message, F("default_uint64" )));
- EXPECT_TRUE(reflection->HasField(message, F("default_sint32" )));
- EXPECT_TRUE(reflection->HasField(message, F("default_sint64" )));
- EXPECT_TRUE(reflection->HasField(message, F("default_fixed32" )));
- EXPECT_TRUE(reflection->HasField(message, F("default_fixed64" )));
- EXPECT_TRUE(reflection->HasField(message, F("default_sfixed32")));
- EXPECT_TRUE(reflection->HasField(message, F("default_sfixed64")));
- EXPECT_TRUE(reflection->HasField(message, F("default_float" )));
- EXPECT_TRUE(reflection->HasField(message, F("default_double" )));
- EXPECT_TRUE(reflection->HasField(message, F("default_bool" )));
- EXPECT_TRUE(reflection->HasField(message, F("default_string" )));
- EXPECT_TRUE(reflection->HasField(message, F("default_bytes" )));
-
- EXPECT_TRUE(reflection->HasField(message, F("default_nested_enum" )));
- EXPECT_TRUE(reflection->HasField(message, F("default_foreign_enum")));
- EXPECT_TRUE(reflection->HasField(message, F("default_import_enum" )));
-
- EXPECT_TRUE(reflection->HasField(message, F("default_string_piece")));
- EXPECT_TRUE(reflection->HasField(message, F("default_cord")));
-
- EXPECT_EQ(401 , reflection->GetInt32 (message, F("default_int32" )));
- EXPECT_EQ(402 , reflection->GetInt64 (message, F("default_int64" )));
- EXPECT_EQ(403 , reflection->GetUInt32(message, F("default_uint32" )));
- EXPECT_EQ(404 , reflection->GetUInt64(message, F("default_uint64" )));
- EXPECT_EQ(405 , reflection->GetInt32 (message, F("default_sint32" )));
- EXPECT_EQ(406 , reflection->GetInt64 (message, F("default_sint64" )));
- EXPECT_EQ(407 , reflection->GetUInt32(message, F("default_fixed32" )));
- EXPECT_EQ(408 , reflection->GetUInt64(message, F("default_fixed64" )));
- EXPECT_EQ(409 , reflection->GetInt32 (message, F("default_sfixed32")));
- EXPECT_EQ(410 , reflection->GetInt64 (message, F("default_sfixed64")));
- EXPECT_EQ(411 , reflection->GetFloat (message, F("default_float" )));
- EXPECT_EQ(412 , reflection->GetDouble(message, F("default_double" )));
- EXPECT_FALSE( reflection->GetBool (message, F("default_bool" )));
- EXPECT_EQ("415", reflection->GetString(message, F("default_string" )));
- EXPECT_EQ("416", reflection->GetString(message, F("default_bytes" )));
-
- EXPECT_EQ("415", reflection->GetStringReference(message, F("default_string"), &scratch));
- EXPECT_EQ("416", reflection->GetStringReference(message, F("default_bytes" ), &scratch));
-
- EXPECT_EQ( nested_foo_, reflection->GetEnum(message, F("default_nested_enum" )));
- EXPECT_EQ(foreign_foo_, reflection->GetEnum(message, F("default_foreign_enum")));
- EXPECT_EQ( import_foo_, reflection->GetEnum(message, F("default_import_enum" )));
-
- EXPECT_EQ("424", reflection->GetString(message, F("default_string_piece")));
- EXPECT_EQ("424", reflection->GetStringReference(message, F("default_string_piece"),
- &scratch));
-
- EXPECT_EQ("425", reflection->GetString(message, F("default_cord")));
- EXPECT_EQ("425", reflection->GetStringReference(message, F("default_cord"), &scratch));
-}
-
-void TestUtil::ReflectionTester::ExpectPackedFieldsSetViaReflection(
- const Message& message) {
- const Reflection* reflection = message.GetReflection();
-
- ASSERT_EQ(2, reflection->FieldSize(message, F("packed_int32" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("packed_int64" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("packed_uint32" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("packed_uint64" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sint32" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sint64" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("packed_fixed32" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("packed_fixed64" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sfixed32")));
- ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sfixed64")));
- ASSERT_EQ(2, reflection->FieldSize(message, F("packed_float" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("packed_double" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("packed_bool" )));
- ASSERT_EQ(2, reflection->FieldSize(message, F("packed_enum" )));
-
- EXPECT_EQ(601 , reflection->GetRepeatedInt32 (message, F("packed_int32" ), 0));
- EXPECT_EQ(602 , reflection->GetRepeatedInt64 (message, F("packed_int64" ), 0));
- EXPECT_EQ(603 , reflection->GetRepeatedUInt32(message, F("packed_uint32" ), 0));
- EXPECT_EQ(604 , reflection->GetRepeatedUInt64(message, F("packed_uint64" ), 0));
- EXPECT_EQ(605 , reflection->GetRepeatedInt32 (message, F("packed_sint32" ), 0));
- EXPECT_EQ(606 , reflection->GetRepeatedInt64 (message, F("packed_sint64" ), 0));
- EXPECT_EQ(607 , reflection->GetRepeatedUInt32(message, F("packed_fixed32" ), 0));
- EXPECT_EQ(608 , reflection->GetRepeatedUInt64(message, F("packed_fixed64" ), 0));
- EXPECT_EQ(609 , reflection->GetRepeatedInt32 (message, F("packed_sfixed32"), 0));
- EXPECT_EQ(610 , reflection->GetRepeatedInt64 (message, F("packed_sfixed64"), 0));
- EXPECT_EQ(611 , reflection->GetRepeatedFloat (message, F("packed_float" ), 0));
- EXPECT_EQ(612 , reflection->GetRepeatedDouble(message, F("packed_double" ), 0));
- EXPECT_TRUE( reflection->GetRepeatedBool (message, F("packed_bool" ), 0));
- EXPECT_EQ(foreign_bar_,
- reflection->GetRepeatedEnum(message, F("packed_enum"), 0));
-
- EXPECT_EQ(701 , reflection->GetRepeatedInt32 (message, F("packed_int32" ), 1));
- EXPECT_EQ(702 , reflection->GetRepeatedInt64 (message, F("packed_int64" ), 1));
- EXPECT_EQ(703 , reflection->GetRepeatedUInt32(message, F("packed_uint32" ), 1));
- EXPECT_EQ(704 , reflection->GetRepeatedUInt64(message, F("packed_uint64" ), 1));
- EXPECT_EQ(705 , reflection->GetRepeatedInt32 (message, F("packed_sint32" ), 1));
- EXPECT_EQ(706 , reflection->GetRepeatedInt64 (message, F("packed_sint64" ), 1));
- EXPECT_EQ(707 , reflection->GetRepeatedUInt32(message, F("packed_fixed32" ), 1));
- EXPECT_EQ(708 , reflection->GetRepeatedUInt64(message, F("packed_fixed64" ), 1));
- EXPECT_EQ(709 , reflection->GetRepeatedInt32 (message, F("packed_sfixed32"), 1));
- EXPECT_EQ(710 , reflection->GetRepeatedInt64 (message, F("packed_sfixed64"), 1));
- EXPECT_EQ(711 , reflection->GetRepeatedFloat (message, F("packed_float" ), 1));
- EXPECT_EQ(712 , reflection->GetRepeatedDouble(message, F("packed_double" ), 1));
- EXPECT_FALSE( reflection->GetRepeatedBool (message, F("packed_bool" ), 1));
- EXPECT_EQ(foreign_baz_,
- reflection->GetRepeatedEnum(message, F("packed_enum"), 1));
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ReflectionTester::ExpectClearViaReflection(
- const Message& message) {
- const Reflection* reflection = message.GetReflection();
- string scratch;
- const Message* sub_message;
-
- // has_blah() should initially be false for all optional fields.
- EXPECT_FALSE(reflection->HasField(message, F("optional_int32" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_int64" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_uint32" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_uint64" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_sint32" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_sint64" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_fixed32" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_fixed64" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_sfixed32")));
- EXPECT_FALSE(reflection->HasField(message, F("optional_sfixed64")));
- EXPECT_FALSE(reflection->HasField(message, F("optional_float" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_double" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_bool" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_string" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_bytes" )));
-
- EXPECT_FALSE(reflection->HasField(message, F("optionalgroup" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_nested_message" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_foreign_message")));
- EXPECT_FALSE(reflection->HasField(message, F("optional_import_message" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_public_import_message")));
- EXPECT_FALSE(reflection->HasField(message, F("optional_lazy_message")));
-
- EXPECT_FALSE(reflection->HasField(message, F("optional_nested_enum" )));
- EXPECT_FALSE(reflection->HasField(message, F("optional_foreign_enum")));
- EXPECT_FALSE(reflection->HasField(message, F("optional_import_enum" )));
-
- EXPECT_FALSE(reflection->HasField(message, F("optional_string_piece")));
- EXPECT_FALSE(reflection->HasField(message, F("optional_cord")));
-
- // Optional fields without defaults are set to zero or something like it.
- EXPECT_EQ(0 , reflection->GetInt32 (message, F("optional_int32" )));
- EXPECT_EQ(0 , reflection->GetInt64 (message, F("optional_int64" )));
- EXPECT_EQ(0 , reflection->GetUInt32(message, F("optional_uint32" )));
- EXPECT_EQ(0 , reflection->GetUInt64(message, F("optional_uint64" )));
- EXPECT_EQ(0 , reflection->GetInt32 (message, F("optional_sint32" )));
- EXPECT_EQ(0 , reflection->GetInt64 (message, F("optional_sint64" )));
- EXPECT_EQ(0 , reflection->GetUInt32(message, F("optional_fixed32" )));
- EXPECT_EQ(0 , reflection->GetUInt64(message, F("optional_fixed64" )));
- EXPECT_EQ(0 , reflection->GetInt32 (message, F("optional_sfixed32")));
- EXPECT_EQ(0 , reflection->GetInt64 (message, F("optional_sfixed64")));
- EXPECT_EQ(0 , reflection->GetFloat (message, F("optional_float" )));
- EXPECT_EQ(0 , reflection->GetDouble(message, F("optional_double" )));
- EXPECT_FALSE( reflection->GetBool (message, F("optional_bool" )));
- EXPECT_EQ("" , reflection->GetString(message, F("optional_string" )));
- EXPECT_EQ("" , reflection->GetString(message, F("optional_bytes" )));
-
- EXPECT_EQ("", reflection->GetStringReference(message, F("optional_string"), &scratch));
- EXPECT_EQ("", reflection->GetStringReference(message, F("optional_bytes" ), &scratch));
-
- // Embedded messages should also be clear.
- sub_message = &reflection->GetMessage(message, F("optionalgroup"));
- EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, group_a_));
- EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, group_a_));
- sub_message = &reflection->GetMessage(message, F("optional_nested_message"));
- EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, nested_b_));
- EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
- sub_message = &reflection->GetMessage(message, F("optional_foreign_message"));
- EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, foreign_c_));
- EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_));
- sub_message = &reflection->GetMessage(message, F("optional_import_message"));
- EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, import_d_));
- EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, import_d_));
- sub_message = &reflection->GetMessage(message, F("optional_public_import_message"));
- EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, import_e_));
- EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, import_e_));
- sub_message = &reflection->GetMessage(message, F("optional_lazy_message"));
- EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, nested_b_));
- EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
-
- // Enums without defaults are set to the first value in the enum.
- EXPECT_EQ( nested_foo_, reflection->GetEnum(message, F("optional_nested_enum" )));
- EXPECT_EQ(foreign_foo_, reflection->GetEnum(message, F("optional_foreign_enum")));
- EXPECT_EQ( import_foo_, reflection->GetEnum(message, F("optional_import_enum" )));
-
- EXPECT_EQ("", reflection->GetString(message, F("optional_string_piece")));
- EXPECT_EQ("", reflection->GetStringReference(message, F("optional_string_piece"), &scratch));
-
- EXPECT_EQ("", reflection->GetString(message, F("optional_cord")));
- EXPECT_EQ("", reflection->GetStringReference(message, F("optional_cord"), &scratch));
-
- // Repeated fields are empty.
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_int32" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_int64" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_uint32" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_uint64" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sint32" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sint64" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_fixed32" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_fixed64" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sfixed32")));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sfixed64")));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_float" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_double" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_bool" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_string" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_bytes" )));
-
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeatedgroup" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_nested_message" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_foreign_message")));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_import_message" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_lazy_message" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_nested_enum" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_foreign_enum" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_import_enum" )));
-
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_string_piece")));
- EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_cord")));
-
- // has_blah() should also be false for all default fields.
- EXPECT_FALSE(reflection->HasField(message, F("default_int32" )));
- EXPECT_FALSE(reflection->HasField(message, F("default_int64" )));
- EXPECT_FALSE(reflection->HasField(message, F("default_uint32" )));
- EXPECT_FALSE(reflection->HasField(message, F("default_uint64" )));
- EXPECT_FALSE(reflection->HasField(message, F("default_sint32" )));
- EXPECT_FALSE(reflection->HasField(message, F("default_sint64" )));
- EXPECT_FALSE(reflection->HasField(message, F("default_fixed32" )));
- EXPECT_FALSE(reflection->HasField(message, F("default_fixed64" )));
- EXPECT_FALSE(reflection->HasField(message, F("default_sfixed32")));
- EXPECT_FALSE(reflection->HasField(message, F("default_sfixed64")));
- EXPECT_FALSE(reflection->HasField(message, F("default_float" )));
- EXPECT_FALSE(reflection->HasField(message, F("default_double" )));
- EXPECT_FALSE(reflection->HasField(message, F("default_bool" )));
- EXPECT_FALSE(reflection->HasField(message, F("default_string" )));
- EXPECT_FALSE(reflection->HasField(message, F("default_bytes" )));
-
- EXPECT_FALSE(reflection->HasField(message, F("default_nested_enum" )));
- EXPECT_FALSE(reflection->HasField(message, F("default_foreign_enum")));
- EXPECT_FALSE(reflection->HasField(message, F("default_import_enum" )));
-
- EXPECT_FALSE(reflection->HasField(message, F("default_string_piece")));
- EXPECT_FALSE(reflection->HasField(message, F("default_cord")));
-
- // Fields with defaults have their default values (duh).
- EXPECT_EQ( 41 , reflection->GetInt32 (message, F("default_int32" )));
- EXPECT_EQ( 42 , reflection->GetInt64 (message, F("default_int64" )));
- EXPECT_EQ( 43 , reflection->GetUInt32(message, F("default_uint32" )));
- EXPECT_EQ( 44 , reflection->GetUInt64(message, F("default_uint64" )));
- EXPECT_EQ(-45 , reflection->GetInt32 (message, F("default_sint32" )));
- EXPECT_EQ( 46 , reflection->GetInt64 (message, F("default_sint64" )));
- EXPECT_EQ( 47 , reflection->GetUInt32(message, F("default_fixed32" )));
- EXPECT_EQ( 48 , reflection->GetUInt64(message, F("default_fixed64" )));
- EXPECT_EQ( 49 , reflection->GetInt32 (message, F("default_sfixed32")));
- EXPECT_EQ(-50 , reflection->GetInt64 (message, F("default_sfixed64")));
- EXPECT_EQ( 51.5 , reflection->GetFloat (message, F("default_float" )));
- EXPECT_EQ( 52e3 , reflection->GetDouble(message, F("default_double" )));
- EXPECT_TRUE( reflection->GetBool (message, F("default_bool" )));
- EXPECT_EQ("hello", reflection->GetString(message, F("default_string" )));
- EXPECT_EQ("world", reflection->GetString(message, F("default_bytes" )));
-
- EXPECT_EQ("hello", reflection->GetStringReference(message, F("default_string"), &scratch));
- EXPECT_EQ("world", reflection->GetStringReference(message, F("default_bytes" ), &scratch));
-
- EXPECT_EQ( nested_bar_, reflection->GetEnum(message, F("default_nested_enum" )));
- EXPECT_EQ(foreign_bar_, reflection->GetEnum(message, F("default_foreign_enum")));
- EXPECT_EQ( import_bar_, reflection->GetEnum(message, F("default_import_enum" )));
-
- EXPECT_EQ("abc", reflection->GetString(message, F("default_string_piece")));
- EXPECT_EQ("abc", reflection->GetStringReference(message, F("default_string_piece"), &scratch));
-
- EXPECT_EQ("123", reflection->GetString(message, F("default_cord")));
- EXPECT_EQ("123", reflection->GetStringReference(message, F("default_cord"), &scratch));
-}
-
-void TestUtil::ReflectionTester::ExpectPackedClearViaReflection(
- const Message& message) {
- const Reflection* reflection = message.GetReflection();
-
- EXPECT_EQ(0, reflection->FieldSize(message, F("packed_int32" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("packed_int64" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("packed_uint32" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("packed_uint64" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sint32" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sint64" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("packed_fixed32" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("packed_fixed64" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sfixed32")));
- EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sfixed64")));
- EXPECT_EQ(0, reflection->FieldSize(message, F("packed_float" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("packed_double" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("packed_bool" )));
- EXPECT_EQ(0, reflection->FieldSize(message, F("packed_enum" )));
-}
-
-// -------------------------------------------------------------------
-
-void TestUtil::ReflectionTester::ModifyRepeatedFieldsViaReflection(
- Message* message) {
- const Reflection* reflection = message->GetReflection();
- Message* sub_message;
-
- reflection->SetRepeatedInt32 (message, F("repeated_int32" ), 1, 501);
- reflection->SetRepeatedInt64 (message, F("repeated_int64" ), 1, 502);
- reflection->SetRepeatedUInt32(message, F("repeated_uint32" ), 1, 503);
- reflection->SetRepeatedUInt64(message, F("repeated_uint64" ), 1, 504);
- reflection->SetRepeatedInt32 (message, F("repeated_sint32" ), 1, 505);
- reflection->SetRepeatedInt64 (message, F("repeated_sint64" ), 1, 506);
- reflection->SetRepeatedUInt32(message, F("repeated_fixed32" ), 1, 507);
- reflection->SetRepeatedUInt64(message, F("repeated_fixed64" ), 1, 508);
- reflection->SetRepeatedInt32 (message, F("repeated_sfixed32"), 1, 509);
- reflection->SetRepeatedInt64 (message, F("repeated_sfixed64"), 1, 510);
- reflection->SetRepeatedFloat (message, F("repeated_float" ), 1, 511);
- reflection->SetRepeatedDouble(message, F("repeated_double" ), 1, 512);
- reflection->SetRepeatedBool (message, F("repeated_bool" ), 1, true);
- reflection->SetRepeatedString(message, F("repeated_string" ), 1, "515");
- reflection->SetRepeatedString(message, F("repeated_bytes" ), 1, "516");
-
- sub_message = reflection->MutableRepeatedMessage(message, F("repeatedgroup"), 1);
- sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 517);
- sub_message = reflection->MutableRepeatedMessage(message, F("repeated_nested_message"), 1);
- sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 518);
- sub_message = reflection->MutableRepeatedMessage(message, F("repeated_foreign_message"), 1);
- sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 519);
- sub_message = reflection->MutableRepeatedMessage(message, F("repeated_import_message"), 1);
- sub_message->GetReflection()->SetInt32(sub_message, import_d_, 520);
- sub_message = reflection->MutableRepeatedMessage(message, F("repeated_lazy_message"), 1);
- sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 527);
-
- reflection->SetRepeatedEnum(message, F("repeated_nested_enum" ), 1, nested_foo_);
- reflection->SetRepeatedEnum(message, F("repeated_foreign_enum"), 1, foreign_foo_);
- reflection->SetRepeatedEnum(message, F("repeated_import_enum" ), 1, import_foo_);
-
- reflection->SetRepeatedString(message, F("repeated_string_piece"), 1, "524");
- reflection->SetRepeatedString(message, F("repeated_cord"), 1, "525");
-}
-
-void TestUtil::ReflectionTester::ModifyPackedFieldsViaReflection(
- Message* message) {
- const Reflection* reflection = message->GetReflection();
- reflection->SetRepeatedInt32 (message, F("packed_int32" ), 1, 801);
- reflection->SetRepeatedInt64 (message, F("packed_int64" ), 1, 802);
- reflection->SetRepeatedUInt32(message, F("packed_uint32" ), 1, 803);
- reflection->SetRepeatedUInt64(message, F("packed_uint64" ), 1, 804);
- reflection->SetRepeatedInt32 (message, F("packed_sint32" ), 1, 805);
- reflection->SetRepeatedInt64 (message, F("packed_sint64" ), 1, 806);
- reflection->SetRepeatedUInt32(message, F("packed_fixed32" ), 1, 807);
- reflection->SetRepeatedUInt64(message, F("packed_fixed64" ), 1, 808);
- reflection->SetRepeatedInt32 (message, F("packed_sfixed32"), 1, 809);
- reflection->SetRepeatedInt64 (message, F("packed_sfixed64"), 1, 810);
- reflection->SetRepeatedFloat (message, F("packed_float" ), 1, 811);
- reflection->SetRepeatedDouble(message, F("packed_double" ), 1, 812);
- reflection->SetRepeatedBool (message, F("packed_bool" ), 1, true);
- reflection->SetRepeatedEnum (message, F("packed_enum" ), 1, foreign_foo_);
-}
-
-void TestUtil::ReflectionTester::RemoveLastRepeatedsViaReflection(
- Message* message) {
- const Reflection* reflection = message->GetReflection();
-
- std::vector<const FieldDescriptor*> output;
- reflection->ListFields(*message, &output);
- for (int i=0; i<output.size(); ++i) {
- const FieldDescriptor* field = output[i];
- if (!field->is_repeated()) continue;
-
- reflection->RemoveLast(message, field);
- }
-}
-
-void TestUtil::ReflectionTester::ReleaseLastRepeatedsViaReflection(
- Message* message, bool expect_extensions_notnull) {
- const Reflection* reflection = message->GetReflection();
-
- std::vector<const FieldDescriptor*> output;
- reflection->ListFields(*message, &output);
- for (int i=0; i<output.size(); ++i) {
- const FieldDescriptor* field = output[i];
- if (!field->is_repeated()) continue;
- if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) continue;
-
- Message* released = reflection->ReleaseLast(message, field);
- if (!field->is_extension() || expect_extensions_notnull) {
- ASSERT_TRUE(released != NULL) << "ReleaseLast returned NULL for: "
- << field->name();
- }
- delete released;
- }
-}
-
-void TestUtil::ReflectionTester::SwapRepeatedsViaReflection(Message* message) {
- const Reflection* reflection = message->GetReflection();
-
- std::vector<const FieldDescriptor*> output;
- reflection->ListFields(*message, &output);
- for (int i=0; i<output.size(); ++i) {
- const FieldDescriptor* field = output[i];
- if (!field->is_repeated()) continue;
-
- reflection->SwapElements(message, field, 0, 1);
- }
-}
-
-void TestUtil::ReflectionTester::
-SetAllocatedOptionalMessageFieldsToNullViaReflection(
- Message* message) {
- const Reflection* reflection = message->GetReflection();
-
- std::vector<const FieldDescriptor*> fields;
- reflection->ListFields(*message, &fields);
-
- for (int i = 0; i < fields.size(); ++i) {
- const FieldDescriptor* field = fields[i];
- if (!field->is_optional() ||
- field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) continue;
-
- reflection->SetAllocatedMessage(message, NULL, field);
- }
-}
-
-void TestUtil::ReflectionTester::
-SetAllocatedOptionalMessageFieldsToMessageViaReflection(
- Message* from_message,
- Message* to_message) {
- EXPECT_EQ(from_message->GetDescriptor(), to_message->GetDescriptor());
- const Reflection* from_reflection = from_message->GetReflection();
- const Reflection* to_reflection = to_message->GetReflection();
-
- std::vector<const FieldDescriptor*> fields;
- from_reflection->ListFields(*from_message, &fields);
-
- for (int i = 0; i < fields.size(); ++i) {
- const FieldDescriptor* field = fields[i];
- if (!field->is_optional() ||
- field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) continue;
-
- Message* sub_message =
- from_reflection->ReleaseMessage(from_message, field);
- to_reflection->SetAllocatedMessage(to_message, sub_message, field);
- }
-}
-
-void TestUtil::ReflectionTester::ExpectMessagesReleasedViaReflection(
- Message* message,
- TestUtil::ReflectionTester::MessageReleaseState expected_release_state) {
- const Reflection* reflection = message->GetReflection();
-
- static const char* fields[] = {
- "optionalgroup",
- "optional_nested_message",
- "optional_foreign_message",
- "optional_import_message",
- };
- for (int i = 0; i < GOOGLE_ARRAYSIZE(fields); i++) {
- const Message& sub_message = reflection->GetMessage(*message, F(fields[i]));
- Message* released = reflection->ReleaseMessage(message, F(fields[i]));
- switch (expected_release_state) {
- case IS_NULL:
- EXPECT_TRUE(released == NULL);
- break;
- case NOT_NULL:
- EXPECT_TRUE(released != NULL);
- if (message->GetArena() == NULL) {
- // released message must be same as sub_message if source message is
- // not on arena.
- EXPECT_EQ(&sub_message, released);
- }
- break;
- case CAN_BE_NULL:
- break;
- }
- delete released;
- EXPECT_FALSE(reflection->HasField(*message, F(fields[i])));
- }
-}
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/test_util.h b/src/google/protobuf/test_util.h
index 1c13a1a7..b9abb671 100644
--- a/src/google/protobuf/test_util.h
+++ b/src/google/protobuf/test_util.h
@@ -35,180 +35,1266 @@
#ifndef GOOGLE_PROTOBUF_TEST_UTIL_H__
#define GOOGLE_PROTOBUF_TEST_UTIL_H__
-#include <stack>
-#include <string>
-#include <google/protobuf/message.h>
#include <google/protobuf/unittest.pb.h>
+#define UNITTEST ::protobuf_unittest
+#define UNITTEST_IMPORT ::protobuf_unittest_import
+// Must be included when the preprocessor symbols above are defined.
+#include <google/protobuf/test_util.inc>
+#undef UNITTEST
+#undef UNITTEST_IMPORT
+
+
namespace google {
namespace protobuf {
-
+// This file doesn't use these declarations, but some .cc files do.
namespace unittest = ::protobuf_unittest;
-namespace unittest_import = protobuf_unittest_import;
+namespace unittest_import = ::protobuf_unittest_import;
-class TestUtil {
+namespace TestUtil {
+
+class ReflectionTester {
public:
- // Set every field in the message to a unique value.
- static void SetAllFields(unittest::TestAllTypes* message);
- static void SetOptionalFields(unittest::TestAllTypes* message);
- static void AddRepeatedFields1(unittest::TestAllTypes* message);
- static void AddRepeatedFields2(unittest::TestAllTypes* message);
- static void SetDefaultFields(unittest::TestAllTypes* message);
- static void SetOneofFields(unittest::TestAllTypes* message);
- static void SetAllExtensions(unittest::TestAllExtensions* message);
- static void SetOneofFields(unittest::TestAllExtensions* message);
- static void SetAllFieldsAndExtensions(unittest::TestFieldOrderings* message);
- static void SetPackedFields(unittest::TestPackedTypes* message);
- static void SetPackedExtensions(unittest::TestPackedExtensions* message);
- static void SetUnpackedFields(unittest::TestUnpackedTypes* message);
- static void SetOneof1(unittest::TestOneof2* message);
- static void SetOneof2(unittest::TestOneof2* message);
-
- // Use the repeated versions of the set_*() accessors to modify all the
- // repeated fields of the message (which should already have been
- // initialized with Set*Fields()). Set*Fields() itself only tests
- // the add_*() accessors.
- static void ModifyRepeatedFields(unittest::TestAllTypes* message);
- static void ModifyRepeatedExtensions(unittest::TestAllExtensions* message);
- static void ModifyPackedFields(unittest::TestPackedTypes* message);
- static void ModifyPackedExtensions(unittest::TestPackedExtensions* message);
-
- // Check that all fields have the values that they should have after
- // Set*Fields() is called.
- static void ExpectAllFieldsSet(const unittest::TestAllTypes& message);
- static void ExpectAllExtensionsSet(
- const unittest::TestAllExtensions& message);
- static void ExpectPackedFieldsSet(const unittest::TestPackedTypes& message);
- static void ExpectPackedExtensionsSet(
- const unittest::TestPackedExtensions& message);
- static void ExpectUnpackedFieldsSet(
- const unittest::TestUnpackedTypes& message);
- static void ExpectUnpackedExtensionsSet(
- const unittest::TestUnpackedExtensions& message);
- static void ExpectOneofSet1(const unittest::TestOneof2& message);
- static void ExpectOneofSet2(const unittest::TestOneof2& message);
-
- // Expect that the message is modified as would be expected from
- // Modify*Fields().
- static void ExpectRepeatedFieldsModified(
- const unittest::TestAllTypes& message);
- static void ExpectRepeatedExtensionsModified(
- const unittest::TestAllExtensions& message);
- static void ExpectPackedFieldsModified(
- const unittest::TestPackedTypes& message);
- static void ExpectPackedExtensionsModified(
- const unittest::TestPackedExtensions& message);
-
- // Check that all fields have their default values.
- static void ExpectClear(const unittest::TestAllTypes& message);
- static void ExpectExtensionsClear(const unittest::TestAllExtensions& message);
- static void ExpectPackedClear(const unittest::TestPackedTypes& message);
- static void ExpectPackedExtensionsClear(
- const unittest::TestPackedExtensions& message);
- static void ExpectOneofClear(const unittest::TestOneof2& message);
-
- // Check that the passed-in serialization is the canonical serialization we
- // expect for a TestFieldOrderings message filled in by
- // SetAllFieldsAndExtensions().
- static void ExpectAllFieldsAndExtensionsInOrder(const string& serialized);
-
- // Check that all repeated fields have had their last elements removed.
- static void ExpectLastRepeatedsRemoved(
- const unittest::TestAllTypes& message);
- static void ExpectLastRepeatedExtensionsRemoved(
- const unittest::TestAllExtensions& message);
- static void ExpectLastRepeatedsReleased(
- const unittest::TestAllTypes& message);
- static void ExpectLastRepeatedExtensionsReleased(
- const unittest::TestAllExtensions& message);
-
- // Check that all repeated fields have had their first and last elements
- // swapped.
- static void ExpectRepeatedsSwapped(const unittest::TestAllTypes& message);
- static void ExpectRepeatedExtensionsSwapped(
- const unittest::TestAllExtensions& message);
-
- static void ExpectAtMostOneFieldSetInOneof(
- const unittest::TestOneof2 &message);
-
- // Like above, but use the reflection interface.
- class ReflectionTester {
- public:
- // base_descriptor must be a descriptor for TestAllTypes or
- // TestAllExtensions. In the former case, ReflectionTester fetches from
- // it the FieldDescriptors needed to use the reflection interface. In
- // the latter case, ReflectionTester searches for extension fields in
- // its file.
- explicit ReflectionTester(const Descriptor* base_descriptor);
-
- void SetAllFieldsViaReflection(Message* message);
- void ModifyRepeatedFieldsViaReflection(Message* message);
- void ExpectAllFieldsSetViaReflection(const Message& message);
- void ExpectClearViaReflection(const Message& message);
-
- void SetPackedFieldsViaReflection(Message* message);
- void ModifyPackedFieldsViaReflection(Message* message);
- void ExpectPackedFieldsSetViaReflection(const Message& message);
- void ExpectPackedClearViaReflection(const Message& message);
-
- void RemoveLastRepeatedsViaReflection(Message* message);
- void ReleaseLastRepeatedsViaReflection(
- Message* message, bool expect_extensions_notnull);
- void SwapRepeatedsViaReflection(Message* message);
- void SetAllocatedOptionalMessageFieldsToNullViaReflection(
- Message* message);
- static void SetAllocatedOptionalMessageFieldsToMessageViaReflection(
- Message* from_message,
- Message* to_message);
-
- enum MessageReleaseState {
- IS_NULL,
- CAN_BE_NULL,
- NOT_NULL,
- };
- void ExpectMessagesReleasedViaReflection(
- Message* message, MessageReleaseState expected_release_state);
-
- // Set and check functions for TestOneof2 messages. No need to construct
- // the ReflectionTester by TestAllTypes nor TestAllExtensions.
- static void SetOneofViaReflection(Message* message);
- static void ExpectOneofSetViaReflection(const Message& message);
-
- private:
- const FieldDescriptor* F(const string& name);
-
- const Descriptor* base_descriptor_;
-
- const FieldDescriptor* group_a_;
- const FieldDescriptor* repeated_group_a_;
- const FieldDescriptor* nested_b_;
- const FieldDescriptor* foreign_c_;
- const FieldDescriptor* import_d_;
- const FieldDescriptor* import_e_;
-
- const EnumValueDescriptor* nested_foo_;
- const EnumValueDescriptor* nested_bar_;
- const EnumValueDescriptor* nested_baz_;
- const EnumValueDescriptor* foreign_foo_;
- const EnumValueDescriptor* foreign_bar_;
- const EnumValueDescriptor* foreign_baz_;
- const EnumValueDescriptor* import_foo_;
- const EnumValueDescriptor* import_bar_;
- const EnumValueDescriptor* import_baz_;
-
- // We have to split this into three function otherwise it creates a stack
- // frame so large that it triggers a warning.
- void ExpectAllFieldsSetViaReflection1(const Message& message);
- void ExpectAllFieldsSetViaReflection2(const Message& message);
- void ExpectAllFieldsSetViaReflection3(const Message& message);
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ReflectionTester);
+ // base_descriptor must be a descriptor for TestAllTypes or
+ // TestAllExtensions. In the former case, ReflectionTester fetches from
+ // it the FieldDescriptors needed to use the reflection interface. In
+ // the latter case, ReflectionTester searches for extension fields in
+ // its file.
+ explicit ReflectionTester(const Descriptor* base_descriptor);
+
+ void SetAllFieldsViaReflection(Message* message);
+ void ModifyRepeatedFieldsViaReflection(Message* message);
+ void ExpectAllFieldsSetViaReflection(const Message& message);
+ void ExpectClearViaReflection(const Message& message);
+
+ void SetPackedFieldsViaReflection(Message* message);
+ void ModifyPackedFieldsViaReflection(Message* message);
+ void ExpectPackedFieldsSetViaReflection(const Message& message);
+ void ExpectPackedClearViaReflection(const Message& message);
+
+ void RemoveLastRepeatedsViaReflection(Message* message);
+ void ReleaseLastRepeatedsViaReflection(Message* message,
+ bool expect_extensions_notnull);
+ void SwapRepeatedsViaReflection(Message* message);
+ void SetAllocatedOptionalMessageFieldsToNullViaReflection(Message* message);
+ static void SetAllocatedOptionalMessageFieldsToMessageViaReflection(
+ Message* from_message, Message* to_message);
+
+ enum MessageReleaseState {
+ IS_NULL,
+ CAN_BE_NULL,
+ NOT_NULL,
};
+ void ExpectMessagesReleasedViaReflection(
+ Message* message, MessageReleaseState expected_release_state);
+
+ // Set and check functions for TestOneof2 messages. No need to construct
+ // the ReflectionTester by TestAllTypes nor TestAllExtensions.
+ static void SetOneofViaReflection(Message* message);
+ static void ExpectOneofSetViaReflection(const Message& message);
private:
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TestUtil);
+ const FieldDescriptor* F(const string& name);
+
+ const Descriptor* base_descriptor_;
+
+ const FieldDescriptor* group_a_;
+ const FieldDescriptor* repeated_group_a_;
+ const FieldDescriptor* nested_b_;
+ const FieldDescriptor* foreign_c_;
+ const FieldDescriptor* import_d_;
+ const FieldDescriptor* import_e_;
+
+ const EnumValueDescriptor* nested_foo_;
+ const EnumValueDescriptor* nested_bar_;
+ const EnumValueDescriptor* nested_baz_;
+ const EnumValueDescriptor* foreign_foo_;
+ const EnumValueDescriptor* foreign_bar_;
+ const EnumValueDescriptor* foreign_baz_;
+ const EnumValueDescriptor* import_foo_;
+ const EnumValueDescriptor* import_bar_;
+ const EnumValueDescriptor* import_baz_;
+
+ // We have to split this into three function otherwise it creates a stack
+ // frame so large that it triggers a warning.
+ void ExpectAllFieldsSetViaReflection1(const Message& message);
+ void ExpectAllFieldsSetViaReflection2(const Message& message);
+ void ExpectAllFieldsSetViaReflection3(const Message& message);
+
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ReflectionTester);
};
+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();
+ const FieldDescriptor* import_descriptor =
+ pool->FindFieldByName(package + ".TestAllTypes.optional_import_message");
+ string import_package = import_descriptor->message_type()->file()->package();
+
+ nested_b_ = pool->FindFieldByName(package + ".TestAllTypes.NestedMessage.bb");
+ foreign_c_ = pool->FindFieldByName(package + ".ForeignMessage.c");
+ import_d_ = pool->FindFieldByName(import_package + ".ImportMessage.d");
+ import_e_ = pool->FindFieldByName(import_package + ".PublicImportMessage.e");
+ nested_foo_ = pool->FindEnumValueByName(package + ".TestAllTypes.FOO");
+ nested_bar_ = pool->FindEnumValueByName(package + ".TestAllTypes.BAR");
+ nested_baz_ = pool->FindEnumValueByName(package + ".TestAllTypes.BAZ");
+ foreign_foo_ = pool->FindEnumValueByName(package + ".FOREIGN_FOO");
+ foreign_bar_ = pool->FindEnumValueByName(package + ".FOREIGN_BAR");
+ foreign_baz_ = pool->FindEnumValueByName(package + ".FOREIGN_BAZ");
+ import_foo_ = pool->FindEnumValueByName(import_package + ".IMPORT_FOO");
+ import_bar_ = pool->FindEnumValueByName(import_package + ".IMPORT_BAR");
+ import_baz_ = pool->FindEnumValueByName(import_package + ".IMPORT_BAZ");
+
+ if (base_descriptor_->name() == "TestAllExtensions") {
+ group_a_ = pool->FindFieldByName(package + ".OptionalGroup_extension.a");
+ repeated_group_a_ =
+ pool->FindFieldByName(package + ".RepeatedGroup_extension.a");
+ } else {
+ group_a_ = pool->FindFieldByName(package + ".TestAllTypes.OptionalGroup.a");
+ repeated_group_a_ =
+ pool->FindFieldByName(package + ".TestAllTypes.RepeatedGroup.a");
+ }
+
+ EXPECT_TRUE(group_a_ != nullptr);
+ EXPECT_TRUE(repeated_group_a_ != nullptr);
+ EXPECT_TRUE(nested_b_ != nullptr);
+ EXPECT_TRUE(foreign_c_ != nullptr);
+ EXPECT_TRUE(import_d_ != nullptr);
+ EXPECT_TRUE(import_e_ != nullptr);
+ EXPECT_TRUE(nested_foo_ != nullptr);
+ EXPECT_TRUE(nested_bar_ != nullptr);
+ EXPECT_TRUE(nested_baz_ != nullptr);
+ EXPECT_TRUE(foreign_foo_ != nullptr);
+ EXPECT_TRUE(foreign_bar_ != nullptr);
+ EXPECT_TRUE(foreign_baz_ != nullptr);
+ EXPECT_TRUE(import_foo_ != nullptr);
+ EXPECT_TRUE(import_bar_ != nullptr);
+ EXPECT_TRUE(import_baz_ != nullptr);
+}
+
+// Shorthand to get a FieldDescriptor for a field of TestAllTypes.
+inline const FieldDescriptor* TestUtil::ReflectionTester::F(
+ const string& name) {
+ const FieldDescriptor* result = nullptr;
+ if (base_descriptor_->name() == "TestAllExtensions" ||
+ base_descriptor_->name() == "TestPackedExtensions") {
+ result = base_descriptor_->file()->FindExtensionByName(name + "_extension");
+ } else {
+ result = base_descriptor_->FindFieldByName(name);
+ }
+ GOOGLE_CHECK(result != nullptr);
+ return result;
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ReflectionTester::SetAllFieldsViaReflection(
+ Message* message) {
+ const Reflection* reflection = message->GetReflection();
+ Message* sub_message;
+
+ reflection->SetInt32(message, F("optional_int32"), 101);
+ reflection->SetInt64(message, F("optional_int64"), 102);
+ reflection->SetUInt32(message, F("optional_uint32"), 103);
+ reflection->SetUInt64(message, F("optional_uint64"), 104);
+ reflection->SetInt32(message, F("optional_sint32"), 105);
+ reflection->SetInt64(message, F("optional_sint64"), 106);
+ reflection->SetUInt32(message, F("optional_fixed32"), 107);
+ reflection->SetUInt64(message, F("optional_fixed64"), 108);
+ reflection->SetInt32(message, F("optional_sfixed32"), 109);
+ reflection->SetInt64(message, F("optional_sfixed64"), 110);
+ reflection->SetFloat(message, F("optional_float"), 111);
+ reflection->SetDouble(message, F("optional_double"), 112);
+ reflection->SetBool(message, F("optional_bool"), true);
+ reflection->SetString(message, F("optional_string"), "115");
+ reflection->SetString(message, F("optional_bytes"), "116");
+
+ sub_message = reflection->MutableMessage(message, F("optionalgroup"));
+ sub_message->GetReflection()->SetInt32(sub_message, group_a_, 117);
+ sub_message =
+ reflection->MutableMessage(message, F("optional_nested_message"));
+ sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 118);
+ sub_message =
+ reflection->MutableMessage(message, F("optional_foreign_message"));
+ sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 119);
+ sub_message =
+ reflection->MutableMessage(message, F("optional_import_message"));
+ sub_message->GetReflection()->SetInt32(sub_message, import_d_, 120);
+
+ reflection->SetEnum(message, F("optional_nested_enum"), nested_baz_);
+ reflection->SetEnum(message, F("optional_foreign_enum"), foreign_baz_);
+ reflection->SetEnum(message, F("optional_import_enum"), import_baz_);
+
+ reflection->SetString(message, F("optional_string_piece"), "124");
+ reflection->SetString(message, F("optional_cord"), "125");
+
+ sub_message =
+ reflection->MutableMessage(message, F("optional_public_import_message"));
+ sub_message->GetReflection()->SetInt32(sub_message, import_e_, 126);
+
+ sub_message = reflection->MutableMessage(message, F("optional_lazy_message"));
+ sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 127);
+
+ // -----------------------------------------------------------------
+
+ reflection->AddInt32(message, F("repeated_int32"), 201);
+ reflection->AddInt64(message, F("repeated_int64"), 202);
+ reflection->AddUInt32(message, F("repeated_uint32"), 203);
+ reflection->AddUInt64(message, F("repeated_uint64"), 204);
+ reflection->AddInt32(message, F("repeated_sint32"), 205);
+ reflection->AddInt64(message, F("repeated_sint64"), 206);
+ reflection->AddUInt32(message, F("repeated_fixed32"), 207);
+ reflection->AddUInt64(message, F("repeated_fixed64"), 208);
+ reflection->AddInt32(message, F("repeated_sfixed32"), 209);
+ reflection->AddInt64(message, F("repeated_sfixed64"), 210);
+ reflection->AddFloat(message, F("repeated_float"), 211);
+ reflection->AddDouble(message, F("repeated_double"), 212);
+ reflection->AddBool(message, F("repeated_bool"), true);
+ reflection->AddString(message, F("repeated_string"), "215");
+ reflection->AddString(message, F("repeated_bytes"), "216");
+
+ sub_message = reflection->AddMessage(message, F("repeatedgroup"));
+ sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 217);
+ sub_message = reflection->AddMessage(message, F("repeated_nested_message"));
+ sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 218);
+ sub_message = reflection->AddMessage(message, F("repeated_foreign_message"));
+ sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 219);
+ sub_message = reflection->AddMessage(message, F("repeated_import_message"));
+ sub_message->GetReflection()->SetInt32(sub_message, import_d_, 220);
+ sub_message = reflection->AddMessage(message, F("repeated_lazy_message"));
+ sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 227);
+
+ reflection->AddEnum(message, F("repeated_nested_enum"), nested_bar_);
+ reflection->AddEnum(message, F("repeated_foreign_enum"), foreign_bar_);
+ reflection->AddEnum(message, F("repeated_import_enum"), import_bar_);
+
+ reflection->AddString(message, F("repeated_string_piece"), "224");
+ reflection->AddString(message, F("repeated_cord"), "225");
+
+ // Add a second one of each field.
+ reflection->AddInt32(message, F("repeated_int32"), 301);
+ reflection->AddInt64(message, F("repeated_int64"), 302);
+ reflection->AddUInt32(message, F("repeated_uint32"), 303);
+ reflection->AddUInt64(message, F("repeated_uint64"), 304);
+ reflection->AddInt32(message, F("repeated_sint32"), 305);
+ reflection->AddInt64(message, F("repeated_sint64"), 306);
+ reflection->AddUInt32(message, F("repeated_fixed32"), 307);
+ reflection->AddUInt64(message, F("repeated_fixed64"), 308);
+ reflection->AddInt32(message, F("repeated_sfixed32"), 309);
+ reflection->AddInt64(message, F("repeated_sfixed64"), 310);
+ reflection->AddFloat(message, F("repeated_float"), 311);
+ reflection->AddDouble(message, F("repeated_double"), 312);
+ reflection->AddBool(message, F("repeated_bool"), false);
+ reflection->AddString(message, F("repeated_string"), "315");
+ reflection->AddString(message, F("repeated_bytes"), "316");
+
+ sub_message = reflection->AddMessage(message, F("repeatedgroup"));
+ sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 317);
+ sub_message = reflection->AddMessage(message, F("repeated_nested_message"));
+ sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 318);
+ sub_message = reflection->AddMessage(message, F("repeated_foreign_message"));
+ sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 319);
+ sub_message = reflection->AddMessage(message, F("repeated_import_message"));
+ sub_message->GetReflection()->SetInt32(sub_message, import_d_, 320);
+ sub_message = reflection->AddMessage(message, F("repeated_lazy_message"));
+ sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 327);
+
+ reflection->AddEnum(message, F("repeated_nested_enum"), nested_baz_);
+ reflection->AddEnum(message, F("repeated_foreign_enum"), foreign_baz_);
+ reflection->AddEnum(message, F("repeated_import_enum"), import_baz_);
+
+ reflection->AddString(message, F("repeated_string_piece"), "324");
+ reflection->AddString(message, F("repeated_cord"), "325");
+
+ // -----------------------------------------------------------------
+
+ reflection->SetInt32(message, F("default_int32"), 401);
+ reflection->SetInt64(message, F("default_int64"), 402);
+ reflection->SetUInt32(message, F("default_uint32"), 403);
+ reflection->SetUInt64(message, F("default_uint64"), 404);
+ reflection->SetInt32(message, F("default_sint32"), 405);
+ reflection->SetInt64(message, F("default_sint64"), 406);
+ reflection->SetUInt32(message, F("default_fixed32"), 407);
+ reflection->SetUInt64(message, F("default_fixed64"), 408);
+ reflection->SetInt32(message, F("default_sfixed32"), 409);
+ reflection->SetInt64(message, F("default_sfixed64"), 410);
+ reflection->SetFloat(message, F("default_float"), 411);
+ reflection->SetDouble(message, F("default_double"), 412);
+ reflection->SetBool(message, F("default_bool"), false);
+ reflection->SetString(message, F("default_string"), "415");
+ reflection->SetString(message, F("default_bytes"), "416");
+
+ reflection->SetEnum(message, F("default_nested_enum"), nested_foo_);
+ reflection->SetEnum(message, F("default_foreign_enum"), foreign_foo_);
+ reflection->SetEnum(message, F("default_import_enum"), import_foo_);
+
+ reflection->SetString(message, F("default_string_piece"), "424");
+ reflection->SetString(message, F("default_cord"), "425");
+
+ reflection->SetUInt32(message, F("oneof_uint32"), 601);
+ sub_message = reflection->MutableMessage(message, F("oneof_nested_message"));
+ sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 602);
+ reflection->SetString(message, F("oneof_string"), "603");
+ reflection->SetString(message, F("oneof_bytes"), "604");
+}
+
+inline void TestUtil::ReflectionTester::SetOneofViaReflection(
+ Message* message) {
+ const Descriptor* descriptor = message->GetDescriptor();
+ const Reflection* reflection = message->GetReflection();
+ Message* sub_message = reflection->MutableMessage(
+ message, descriptor->FindFieldByName("foo_lazy_message"));
+ sub_message->GetReflection()->SetInt64(
+ sub_message, sub_message->GetDescriptor()->FindFieldByName("qux_int"),
+ 100);
+
+ reflection->SetString(message, descriptor->FindFieldByName("bar_cord"),
+ "101");
+ reflection->SetInt32(message, descriptor->FindFieldByName("baz_int"), 102);
+ reflection->SetString(message, descriptor->FindFieldByName("baz_string"),
+ "103");
+}
+
+inline void TestUtil::ReflectionTester::ExpectOneofSetViaReflection(
+ const Message& message) {
+ const Descriptor* descriptor = message.GetDescriptor();
+ const Reflection* reflection = message.GetReflection();
+ string scratch;
+ EXPECT_TRUE(reflection->HasField(
+ message, descriptor->FindFieldByName("foo_lazy_message")));
+ EXPECT_TRUE(
+ reflection->HasField(message, descriptor->FindFieldByName("bar_cord")));
+ EXPECT_TRUE(
+ reflection->HasField(message, descriptor->FindFieldByName("baz_int")));
+ EXPECT_TRUE(
+ reflection->HasField(message, descriptor->FindFieldByName("baz_string")));
+
+ const Message* sub_message = &reflection->GetMessage(
+ message, descriptor->FindFieldByName("foo_lazy_message"));
+ EXPECT_EQ(100, sub_message->GetReflection()->GetInt64(
+ *sub_message,
+ sub_message->GetDescriptor()->FindFieldByName("qux_int")));
+
+ EXPECT_EQ("101", reflection->GetString(
+ message, descriptor->FindFieldByName("bar_cord")));
+ EXPECT_EQ("101",
+ reflection->GetStringReference(
+ message, descriptor->FindFieldByName("bar_cord"), &scratch));
+
+ EXPECT_EQ(102, reflection->GetInt32(message,
+ descriptor->FindFieldByName("baz_int")));
+
+ EXPECT_EQ("103", reflection->GetString(
+ message, descriptor->FindFieldByName("baz_string")));
+ EXPECT_EQ("103",
+ reflection->GetStringReference(
+ message, descriptor->FindFieldByName("baz_string"), &scratch));
+}
+
+inline void TestUtil::ReflectionTester::SetPackedFieldsViaReflection(
+ Message* message) {
+ const Reflection* reflection = message->GetReflection();
+ reflection->AddInt32(message, F("packed_int32"), 601);
+ reflection->AddInt64(message, F("packed_int64"), 602);
+ reflection->AddUInt32(message, F("packed_uint32"), 603);
+ reflection->AddUInt64(message, F("packed_uint64"), 604);
+ reflection->AddInt32(message, F("packed_sint32"), 605);
+ reflection->AddInt64(message, F("packed_sint64"), 606);
+ reflection->AddUInt32(message, F("packed_fixed32"), 607);
+ reflection->AddUInt64(message, F("packed_fixed64"), 608);
+ reflection->AddInt32(message, F("packed_sfixed32"), 609);
+ reflection->AddInt64(message, F("packed_sfixed64"), 610);
+ reflection->AddFloat(message, F("packed_float"), 611);
+ reflection->AddDouble(message, F("packed_double"), 612);
+ reflection->AddBool(message, F("packed_bool"), true);
+ reflection->AddEnum(message, F("packed_enum"), foreign_bar_);
+
+ reflection->AddInt32(message, F("packed_int32"), 701);
+ reflection->AddInt64(message, F("packed_int64"), 702);
+ reflection->AddUInt32(message, F("packed_uint32"), 703);
+ reflection->AddUInt64(message, F("packed_uint64"), 704);
+ reflection->AddInt32(message, F("packed_sint32"), 705);
+ reflection->AddInt64(message, F("packed_sint64"), 706);
+ reflection->AddUInt32(message, F("packed_fixed32"), 707);
+ reflection->AddUInt64(message, F("packed_fixed64"), 708);
+ reflection->AddInt32(message, F("packed_sfixed32"), 709);
+ reflection->AddInt64(message, F("packed_sfixed64"), 710);
+ reflection->AddFloat(message, F("packed_float"), 711);
+ reflection->AddDouble(message, F("packed_double"), 712);
+ reflection->AddBool(message, F("packed_bool"), false);
+ reflection->AddEnum(message, F("packed_enum"), foreign_baz_);
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection(
+ const Message& message) {
+ // We have to split this into three function otherwise it creates a stack
+ // frame so large that it triggers a warning.
+ ExpectAllFieldsSetViaReflection1(message);
+ ExpectAllFieldsSetViaReflection2(message);
+ ExpectAllFieldsSetViaReflection3(message);
+}
+
+inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection1(
+ const Message& message) {
+ const Reflection* reflection = message.GetReflection();
+ string scratch;
+ const Message* sub_message;
+
+ EXPECT_TRUE(reflection->HasField(message, F("optional_int32")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_int64")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_uint32")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_uint64")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_sint32")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_sint64")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_fixed32")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_fixed64")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_sfixed32")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_sfixed64")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_float")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_double")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_bool")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_string")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_bytes")));
+
+ EXPECT_TRUE(reflection->HasField(message, F("optionalgroup")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_nested_message")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_foreign_message")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_import_message")));
+ EXPECT_TRUE(
+ reflection->HasField(message, F("optional_public_import_message")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_lazy_message")));
+
+ sub_message = &reflection->GetMessage(message, F("optionalgroup"));
+ EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, group_a_));
+ sub_message = &reflection->GetMessage(message, F("optional_nested_message"));
+ EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, nested_b_));
+ sub_message = &reflection->GetMessage(message, F("optional_foreign_message"));
+ EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, foreign_c_));
+ sub_message = &reflection->GetMessage(message, F("optional_import_message"));
+ EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, import_d_));
+ sub_message =
+ &reflection->GetMessage(message, F("optional_public_import_message"));
+ EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, import_e_));
+ sub_message = &reflection->GetMessage(message, F("optional_lazy_message"));
+ EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, nested_b_));
+
+ EXPECT_TRUE(reflection->HasField(message, F("optional_nested_enum")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_foreign_enum")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_import_enum")));
+
+ EXPECT_TRUE(reflection->HasField(message, F("optional_string_piece")));
+ EXPECT_TRUE(reflection->HasField(message, F("optional_cord")));
+
+ EXPECT_EQ(101, reflection->GetInt32(message, F("optional_int32")));
+ EXPECT_EQ(102, reflection->GetInt64(message, F("optional_int64")));
+ EXPECT_EQ(103, reflection->GetUInt32(message, F("optional_uint32")));
+ EXPECT_EQ(104, reflection->GetUInt64(message, F("optional_uint64")));
+ EXPECT_EQ(105, reflection->GetInt32(message, F("optional_sint32")));
+ EXPECT_EQ(106, reflection->GetInt64(message, F("optional_sint64")));
+ EXPECT_EQ(107, reflection->GetUInt32(message, F("optional_fixed32")));
+ EXPECT_EQ(108, reflection->GetUInt64(message, F("optional_fixed64")));
+ EXPECT_EQ(109, reflection->GetInt32(message, F("optional_sfixed32")));
+ EXPECT_EQ(110, reflection->GetInt64(message, F("optional_sfixed64")));
+ EXPECT_EQ(111, reflection->GetFloat(message, F("optional_float")));
+ EXPECT_EQ(112, reflection->GetDouble(message, F("optional_double")));
+ EXPECT_TRUE(reflection->GetBool(message, F("optional_bool")));
+ EXPECT_EQ("115", reflection->GetString(message, F("optional_string")));
+ EXPECT_EQ("116", reflection->GetString(message, F("optional_bytes")));
+
+ EXPECT_EQ("115", reflection->GetStringReference(message, F("optional_string"),
+ &scratch));
+ EXPECT_EQ("116", reflection->GetStringReference(message, F("optional_bytes"),
+ &scratch));
+
+ sub_message = &reflection->GetMessage(message, F("optionalgroup"));
+ EXPECT_EQ(117,
+ sub_message->GetReflection()->GetInt32(*sub_message, group_a_));
+ sub_message = &reflection->GetMessage(message, F("optional_nested_message"));
+ EXPECT_EQ(118,
+ sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
+ sub_message = &reflection->GetMessage(message, F("optional_foreign_message"));
+ EXPECT_EQ(119,
+ sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_));
+ sub_message = &reflection->GetMessage(message, F("optional_import_message"));
+ EXPECT_EQ(120,
+ sub_message->GetReflection()->GetInt32(*sub_message, import_d_));
+ sub_message =
+ &reflection->GetMessage(message, F("optional_public_import_message"));
+ EXPECT_EQ(126,
+ sub_message->GetReflection()->GetInt32(*sub_message, import_e_));
+ sub_message = &reflection->GetMessage(message, F("optional_lazy_message"));
+ EXPECT_EQ(127,
+ sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
+
+ EXPECT_EQ(nested_baz_,
+ reflection->GetEnum(message, F("optional_nested_enum")));
+ EXPECT_EQ(foreign_baz_,
+ reflection->GetEnum(message, F("optional_foreign_enum")));
+ EXPECT_EQ(import_baz_,
+ reflection->GetEnum(message, F("optional_import_enum")));
+
+ EXPECT_EQ("124", reflection->GetString(message, F("optional_string_piece")));
+ EXPECT_EQ("124", reflection->GetStringReference(
+ message, F("optional_string_piece"), &scratch));
+
+ EXPECT_EQ("125", reflection->GetString(message, F("optional_cord")));
+ EXPECT_EQ("125", reflection->GetStringReference(message, F("optional_cord"),
+ &scratch));
+
+ EXPECT_TRUE(reflection->HasField(message, F("oneof_bytes")));
+ EXPECT_EQ("604", reflection->GetString(message, F("oneof_bytes")));
+
+ if (base_descriptor_->name() == "TestAllTypes") {
+ EXPECT_FALSE(reflection->HasField(message, F("oneof_uint32")));
+ EXPECT_FALSE(reflection->HasField(message, F("oneof_string")));
+ } else {
+ EXPECT_TRUE(reflection->HasField(message, F("oneof_uint32")));
+ EXPECT_TRUE(reflection->HasField(message, F("oneof_string")));
+ EXPECT_EQ(601, reflection->GetUInt32(message, F("oneof_uint32")));
+ EXPECT_EQ("603", reflection->GetString(message, F("oneof_string")));
+ sub_message = &reflection->GetMessage(message, F("oneof_nested_message"));
+ EXPECT_EQ(602,
+ sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
+ }
+}
+
+inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection2(
+ const Message& message) {
+ const Reflection* reflection = message.GetReflection();
+ string scratch;
+ const Message* sub_message;
+
+ // -----------------------------------------------------------------
+
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_int32")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_int64")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_uint32")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_uint64")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sint32")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sint64")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_fixed32")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_fixed64")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sfixed32")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sfixed64")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_float")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_double")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_bool")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_string")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_bytes")));
+
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeatedgroup")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_nested_message")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_foreign_message")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_import_message")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_lazy_message")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_nested_enum")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_foreign_enum")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_import_enum")));
+
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_string_piece")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_cord")));
+
+ EXPECT_EQ(201, reflection->GetRepeatedInt32(message, F("repeated_int32"), 0));
+ EXPECT_EQ(202, reflection->GetRepeatedInt64(message, F("repeated_int64"), 0));
+ EXPECT_EQ(203,
+ reflection->GetRepeatedUInt32(message, F("repeated_uint32"), 0));
+ EXPECT_EQ(204,
+ reflection->GetRepeatedUInt64(message, F("repeated_uint64"), 0));
+ EXPECT_EQ(205,
+ reflection->GetRepeatedInt32(message, F("repeated_sint32"), 0));
+ EXPECT_EQ(206,
+ reflection->GetRepeatedInt64(message, F("repeated_sint64"), 0));
+ EXPECT_EQ(207,
+ reflection->GetRepeatedUInt32(message, F("repeated_fixed32"), 0));
+ EXPECT_EQ(208,
+ reflection->GetRepeatedUInt64(message, F("repeated_fixed64"), 0));
+ EXPECT_EQ(209,
+ reflection->GetRepeatedInt32(message, F("repeated_sfixed32"), 0));
+ EXPECT_EQ(210,
+ reflection->GetRepeatedInt64(message, F("repeated_sfixed64"), 0));
+ EXPECT_EQ(211, reflection->GetRepeatedFloat(message, F("repeated_float"), 0));
+ EXPECT_EQ(212,
+ reflection->GetRepeatedDouble(message, F("repeated_double"), 0));
+ EXPECT_TRUE(reflection->GetRepeatedBool(message, F("repeated_bool"), 0));
+ EXPECT_EQ("215",
+ reflection->GetRepeatedString(message, F("repeated_string"), 0));
+ EXPECT_EQ("216",
+ reflection->GetRepeatedString(message, F("repeated_bytes"), 0));
+
+ EXPECT_EQ("215", reflection->GetRepeatedStringReference(
+ message, F("repeated_string"), 0, &scratch));
+ EXPECT_EQ("216", reflection->GetRepeatedStringReference(
+ message, F("repeated_bytes"), 0, &scratch));
+
+ sub_message = &reflection->GetRepeatedMessage(message, F("repeatedgroup"), 0);
+ EXPECT_EQ(217, sub_message->GetReflection()->GetInt32(*sub_message,
+ repeated_group_a_));
+ sub_message =
+ &reflection->GetRepeatedMessage(message, F("repeated_nested_message"), 0);
+ EXPECT_EQ(218,
+ sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
+ sub_message = &reflection->GetRepeatedMessage(
+ message, F("repeated_foreign_message"), 0);
+ EXPECT_EQ(219,
+ sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_));
+ sub_message =
+ &reflection->GetRepeatedMessage(message, F("repeated_import_message"), 0);
+ EXPECT_EQ(220,
+ sub_message->GetReflection()->GetInt32(*sub_message, import_d_));
+ sub_message =
+ &reflection->GetRepeatedMessage(message, F("repeated_lazy_message"), 0);
+ EXPECT_EQ(227,
+ sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
+
+ EXPECT_EQ(nested_bar_,
+ reflection->GetRepeatedEnum(message, F("repeated_nested_enum"), 0));
+ EXPECT_EQ(foreign_bar_, reflection->GetRepeatedEnum(
+ message, F("repeated_foreign_enum"), 0));
+ EXPECT_EQ(import_bar_,
+ reflection->GetRepeatedEnum(message, F("repeated_import_enum"), 0));
+
+ EXPECT_EQ("224", reflection->GetRepeatedString(
+ message, F("repeated_string_piece"), 0));
+ EXPECT_EQ("224", reflection->GetRepeatedStringReference(
+ message, F("repeated_string_piece"), 0, &scratch));
+
+ EXPECT_EQ("225",
+ reflection->GetRepeatedString(message, F("repeated_cord"), 0));
+ EXPECT_EQ("225", reflection->GetRepeatedStringReference(
+ message, F("repeated_cord"), 0, &scratch));
+
+ EXPECT_EQ(301, reflection->GetRepeatedInt32(message, F("repeated_int32"), 1));
+ EXPECT_EQ(302, reflection->GetRepeatedInt64(message, F("repeated_int64"), 1));
+ EXPECT_EQ(303,
+ reflection->GetRepeatedUInt32(message, F("repeated_uint32"), 1));
+ EXPECT_EQ(304,
+ reflection->GetRepeatedUInt64(message, F("repeated_uint64"), 1));
+ EXPECT_EQ(305,
+ reflection->GetRepeatedInt32(message, F("repeated_sint32"), 1));
+ EXPECT_EQ(306,
+ reflection->GetRepeatedInt64(message, F("repeated_sint64"), 1));
+ EXPECT_EQ(307,
+ reflection->GetRepeatedUInt32(message, F("repeated_fixed32"), 1));
+ EXPECT_EQ(308,
+ reflection->GetRepeatedUInt64(message, F("repeated_fixed64"), 1));
+ EXPECT_EQ(309,
+ reflection->GetRepeatedInt32(message, F("repeated_sfixed32"), 1));
+ EXPECT_EQ(310,
+ reflection->GetRepeatedInt64(message, F("repeated_sfixed64"), 1));
+ EXPECT_EQ(311, reflection->GetRepeatedFloat(message, F("repeated_float"), 1));
+ EXPECT_EQ(312,
+ reflection->GetRepeatedDouble(message, F("repeated_double"), 1));
+ EXPECT_FALSE(reflection->GetRepeatedBool(message, F("repeated_bool"), 1));
+ EXPECT_EQ("315",
+ reflection->GetRepeatedString(message, F("repeated_string"), 1));
+ EXPECT_EQ("316",
+ reflection->GetRepeatedString(message, F("repeated_bytes"), 1));
+
+ EXPECT_EQ("315", reflection->GetRepeatedStringReference(
+ message, F("repeated_string"), 1, &scratch));
+ EXPECT_EQ("316", reflection->GetRepeatedStringReference(
+ message, F("repeated_bytes"), 1, &scratch));
+
+ sub_message = &reflection->GetRepeatedMessage(message, F("repeatedgroup"), 1);
+ EXPECT_EQ(317, sub_message->GetReflection()->GetInt32(*sub_message,
+ repeated_group_a_));
+ sub_message =
+ &reflection->GetRepeatedMessage(message, F("repeated_nested_message"), 1);
+ EXPECT_EQ(318,
+ sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
+ sub_message = &reflection->GetRepeatedMessage(
+ message, F("repeated_foreign_message"), 1);
+ EXPECT_EQ(319,
+ sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_));
+ sub_message =
+ &reflection->GetRepeatedMessage(message, F("repeated_import_message"), 1);
+ EXPECT_EQ(320,
+ sub_message->GetReflection()->GetInt32(*sub_message, import_d_));
+ sub_message =
+ &reflection->GetRepeatedMessage(message, F("repeated_lazy_message"), 1);
+ EXPECT_EQ(327,
+ sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
+
+ EXPECT_EQ(nested_baz_,
+ reflection->GetRepeatedEnum(message, F("repeated_nested_enum"), 1));
+ EXPECT_EQ(foreign_baz_, reflection->GetRepeatedEnum(
+ message, F("repeated_foreign_enum"), 1));
+ EXPECT_EQ(import_baz_,
+ reflection->GetRepeatedEnum(message, F("repeated_import_enum"), 1));
+
+ EXPECT_EQ("324", reflection->GetRepeatedString(
+ message, F("repeated_string_piece"), 1));
+ EXPECT_EQ("324", reflection->GetRepeatedStringReference(
+ message, F("repeated_string_piece"), 1, &scratch));
+
+ EXPECT_EQ("325",
+ reflection->GetRepeatedString(message, F("repeated_cord"), 1));
+ EXPECT_EQ("325", reflection->GetRepeatedStringReference(
+ message, F("repeated_cord"), 1, &scratch));
+}
+
+inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection3(
+ const Message& message) {
+ const Reflection* reflection = message.GetReflection();
+ string scratch;
+
+ // -----------------------------------------------------------------
+
+ EXPECT_TRUE(reflection->HasField(message, F("default_int32")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_int64")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_uint32")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_uint64")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_sint32")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_sint64")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_fixed32")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_fixed64")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_sfixed32")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_sfixed64")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_float")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_double")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_bool")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_string")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_bytes")));
+
+ EXPECT_TRUE(reflection->HasField(message, F("default_nested_enum")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_foreign_enum")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_import_enum")));
+
+ EXPECT_TRUE(reflection->HasField(message, F("default_string_piece")));
+ EXPECT_TRUE(reflection->HasField(message, F("default_cord")));
+
+ EXPECT_EQ(401, reflection->GetInt32(message, F("default_int32")));
+ EXPECT_EQ(402, reflection->GetInt64(message, F("default_int64")));
+ EXPECT_EQ(403, reflection->GetUInt32(message, F("default_uint32")));
+ EXPECT_EQ(404, reflection->GetUInt64(message, F("default_uint64")));
+ EXPECT_EQ(405, reflection->GetInt32(message, F("default_sint32")));
+ EXPECT_EQ(406, reflection->GetInt64(message, F("default_sint64")));
+ EXPECT_EQ(407, reflection->GetUInt32(message, F("default_fixed32")));
+ EXPECT_EQ(408, reflection->GetUInt64(message, F("default_fixed64")));
+ EXPECT_EQ(409, reflection->GetInt32(message, F("default_sfixed32")));
+ EXPECT_EQ(410, reflection->GetInt64(message, F("default_sfixed64")));
+ EXPECT_EQ(411, reflection->GetFloat(message, F("default_float")));
+ EXPECT_EQ(412, reflection->GetDouble(message, F("default_double")));
+ EXPECT_FALSE(reflection->GetBool(message, F("default_bool")));
+ EXPECT_EQ("415", reflection->GetString(message, F("default_string")));
+ EXPECT_EQ("416", reflection->GetString(message, F("default_bytes")));
+
+ EXPECT_EQ("415", reflection->GetStringReference(message, F("default_string"),
+ &scratch));
+ EXPECT_EQ("416", reflection->GetStringReference(message, F("default_bytes"),
+ &scratch));
+
+ EXPECT_EQ(nested_foo_,
+ reflection->GetEnum(message, F("default_nested_enum")));
+ EXPECT_EQ(foreign_foo_,
+ reflection->GetEnum(message, F("default_foreign_enum")));
+ EXPECT_EQ(import_foo_,
+ reflection->GetEnum(message, F("default_import_enum")));
+
+ EXPECT_EQ("424", reflection->GetString(message, F("default_string_piece")));
+ EXPECT_EQ("424", reflection->GetStringReference(
+ message, F("default_string_piece"), &scratch));
+
+ EXPECT_EQ("425", reflection->GetString(message, F("default_cord")));
+ EXPECT_EQ("425", reflection->GetStringReference(message, F("default_cord"),
+ &scratch));
+}
+
+inline void TestUtil::ReflectionTester::ExpectPackedFieldsSetViaReflection(
+ const Message& message) {
+ const Reflection* reflection = message.GetReflection();
+
+ ASSERT_EQ(2, reflection->FieldSize(message, F("packed_int32")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("packed_int64")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("packed_uint32")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("packed_uint64")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sint32")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sint64")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("packed_fixed32")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("packed_fixed64")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sfixed32")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sfixed64")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("packed_float")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("packed_double")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("packed_bool")));
+ ASSERT_EQ(2, reflection->FieldSize(message, F("packed_enum")));
+
+ EXPECT_EQ(601, reflection->GetRepeatedInt32(message, F("packed_int32"), 0));
+ EXPECT_EQ(602, reflection->GetRepeatedInt64(message, F("packed_int64"), 0));
+ EXPECT_EQ(603, reflection->GetRepeatedUInt32(message, F("packed_uint32"), 0));
+ EXPECT_EQ(604, reflection->GetRepeatedUInt64(message, F("packed_uint64"), 0));
+ EXPECT_EQ(605, reflection->GetRepeatedInt32(message, F("packed_sint32"), 0));
+ EXPECT_EQ(606, reflection->GetRepeatedInt64(message, F("packed_sint64"), 0));
+ EXPECT_EQ(607,
+ reflection->GetRepeatedUInt32(message, F("packed_fixed32"), 0));
+ EXPECT_EQ(608,
+ reflection->GetRepeatedUInt64(message, F("packed_fixed64"), 0));
+ EXPECT_EQ(609,
+ reflection->GetRepeatedInt32(message, F("packed_sfixed32"), 0));
+ EXPECT_EQ(610,
+ reflection->GetRepeatedInt64(message, F("packed_sfixed64"), 0));
+ EXPECT_EQ(611, reflection->GetRepeatedFloat(message, F("packed_float"), 0));
+ EXPECT_EQ(612, reflection->GetRepeatedDouble(message, F("packed_double"), 0));
+ EXPECT_TRUE(reflection->GetRepeatedBool(message, F("packed_bool"), 0));
+ EXPECT_EQ(foreign_bar_,
+ reflection->GetRepeatedEnum(message, F("packed_enum"), 0));
+
+ EXPECT_EQ(701, reflection->GetRepeatedInt32(message, F("packed_int32"), 1));
+ EXPECT_EQ(702, reflection->GetRepeatedInt64(message, F("packed_int64"), 1));
+ EXPECT_EQ(703, reflection->GetRepeatedUInt32(message, F("packed_uint32"), 1));
+ EXPECT_EQ(704, reflection->GetRepeatedUInt64(message, F("packed_uint64"), 1));
+ EXPECT_EQ(705, reflection->GetRepeatedInt32(message, F("packed_sint32"), 1));
+ EXPECT_EQ(706, reflection->GetRepeatedInt64(message, F("packed_sint64"), 1));
+ EXPECT_EQ(707,
+ reflection->GetRepeatedUInt32(message, F("packed_fixed32"), 1));
+ EXPECT_EQ(708,
+ reflection->GetRepeatedUInt64(message, F("packed_fixed64"), 1));
+ EXPECT_EQ(709,
+ reflection->GetRepeatedInt32(message, F("packed_sfixed32"), 1));
+ EXPECT_EQ(710,
+ reflection->GetRepeatedInt64(message, F("packed_sfixed64"), 1));
+ EXPECT_EQ(711, reflection->GetRepeatedFloat(message, F("packed_float"), 1));
+ EXPECT_EQ(712, reflection->GetRepeatedDouble(message, F("packed_double"), 1));
+ EXPECT_FALSE(reflection->GetRepeatedBool(message, F("packed_bool"), 1));
+ EXPECT_EQ(foreign_baz_,
+ reflection->GetRepeatedEnum(message, F("packed_enum"), 1));
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ReflectionTester::ExpectClearViaReflection(
+ const Message& message) {
+ const Reflection* reflection = message.GetReflection();
+ string scratch;
+ const Message* sub_message;
+
+ // has_blah() should initially be false for all optional fields.
+ EXPECT_FALSE(reflection->HasField(message, F("optional_int32")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_int64")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_uint32")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_uint64")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_sint32")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_sint64")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_fixed32")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_fixed64")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_sfixed32")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_sfixed64")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_float")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_double")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_bool")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_string")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_bytes")));
+
+ EXPECT_FALSE(reflection->HasField(message, F("optionalgroup")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_nested_message")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_foreign_message")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_import_message")));
+ EXPECT_FALSE(
+ reflection->HasField(message, F("optional_public_import_message")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_lazy_message")));
+
+ EXPECT_FALSE(reflection->HasField(message, F("optional_nested_enum")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_foreign_enum")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_import_enum")));
+
+ EXPECT_FALSE(reflection->HasField(message, F("optional_string_piece")));
+ EXPECT_FALSE(reflection->HasField(message, F("optional_cord")));
+
+ // Optional fields without defaults are set to zero or something like it.
+ EXPECT_EQ(0, reflection->GetInt32(message, F("optional_int32")));
+ EXPECT_EQ(0, reflection->GetInt64(message, F("optional_int64")));
+ EXPECT_EQ(0, reflection->GetUInt32(message, F("optional_uint32")));
+ EXPECT_EQ(0, reflection->GetUInt64(message, F("optional_uint64")));
+ EXPECT_EQ(0, reflection->GetInt32(message, F("optional_sint32")));
+ EXPECT_EQ(0, reflection->GetInt64(message, F("optional_sint64")));
+ EXPECT_EQ(0, reflection->GetUInt32(message, F("optional_fixed32")));
+ EXPECT_EQ(0, reflection->GetUInt64(message, F("optional_fixed64")));
+ EXPECT_EQ(0, reflection->GetInt32(message, F("optional_sfixed32")));
+ EXPECT_EQ(0, reflection->GetInt64(message, F("optional_sfixed64")));
+ EXPECT_EQ(0, reflection->GetFloat(message, F("optional_float")));
+ EXPECT_EQ(0, reflection->GetDouble(message, F("optional_double")));
+ EXPECT_FALSE(reflection->GetBool(message, F("optional_bool")));
+ EXPECT_EQ("", reflection->GetString(message, F("optional_string")));
+ EXPECT_EQ("", reflection->GetString(message, F("optional_bytes")));
+
+ EXPECT_EQ("", reflection->GetStringReference(message, F("optional_string"),
+ &scratch));
+ EXPECT_EQ("", reflection->GetStringReference(message, F("optional_bytes"),
+ &scratch));
+
+ // Embedded messages should also be clear.
+ sub_message = &reflection->GetMessage(message, F("optionalgroup"));
+ EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, group_a_));
+ EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, group_a_));
+ sub_message = &reflection->GetMessage(message, F("optional_nested_message"));
+ EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, nested_b_));
+ EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
+ sub_message = &reflection->GetMessage(message, F("optional_foreign_message"));
+ EXPECT_FALSE(
+ sub_message->GetReflection()->HasField(*sub_message, foreign_c_));
+ EXPECT_EQ(0,
+ sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_));
+ sub_message = &reflection->GetMessage(message, F("optional_import_message"));
+ EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, import_d_));
+ EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, import_d_));
+ sub_message =
+ &reflection->GetMessage(message, F("optional_public_import_message"));
+ EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, import_e_));
+ EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, import_e_));
+ sub_message = &reflection->GetMessage(message, F("optional_lazy_message"));
+ EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, nested_b_));
+ EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_));
+
+ // Enums without defaults are set to the first value in the enum.
+ EXPECT_EQ(nested_foo_,
+ reflection->GetEnum(message, F("optional_nested_enum")));
+ EXPECT_EQ(foreign_foo_,
+ reflection->GetEnum(message, F("optional_foreign_enum")));
+ EXPECT_EQ(import_foo_,
+ reflection->GetEnum(message, F("optional_import_enum")));
+
+ EXPECT_EQ("", reflection->GetString(message, F("optional_string_piece")));
+ EXPECT_EQ("", reflection->GetStringReference(
+ message, F("optional_string_piece"), &scratch));
+
+ EXPECT_EQ("", reflection->GetString(message, F("optional_cord")));
+ EXPECT_EQ("", reflection->GetStringReference(message, F("optional_cord"),
+ &scratch));
+
+ // Repeated fields are empty.
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_int32")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_int64")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_uint32")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_uint64")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sint32")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sint64")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_fixed32")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_fixed64")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sfixed32")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sfixed64")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_float")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_double")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_bool")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_string")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_bytes")));
+
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeatedgroup")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_nested_message")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_foreign_message")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_import_message")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_lazy_message")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_nested_enum")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_foreign_enum")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_import_enum")));
+
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_string_piece")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_cord")));
+
+ // has_blah() should also be false for all default fields.
+ EXPECT_FALSE(reflection->HasField(message, F("default_int32")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_int64")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_uint32")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_uint64")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_sint32")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_sint64")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_fixed32")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_fixed64")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_sfixed32")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_sfixed64")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_float")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_double")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_bool")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_string")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_bytes")));
+
+ EXPECT_FALSE(reflection->HasField(message, F("default_nested_enum")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_foreign_enum")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_import_enum")));
+
+ EXPECT_FALSE(reflection->HasField(message, F("default_string_piece")));
+ EXPECT_FALSE(reflection->HasField(message, F("default_cord")));
+
+ // Fields with defaults have their default values (duh).
+ EXPECT_EQ(41, reflection->GetInt32(message, F("default_int32")));
+ EXPECT_EQ(42, reflection->GetInt64(message, F("default_int64")));
+ EXPECT_EQ(43, reflection->GetUInt32(message, F("default_uint32")));
+ EXPECT_EQ(44, reflection->GetUInt64(message, F("default_uint64")));
+ EXPECT_EQ(-45, reflection->GetInt32(message, F("default_sint32")));
+ EXPECT_EQ(46, reflection->GetInt64(message, F("default_sint64")));
+ EXPECT_EQ(47, reflection->GetUInt32(message, F("default_fixed32")));
+ EXPECT_EQ(48, reflection->GetUInt64(message, F("default_fixed64")));
+ EXPECT_EQ(49, reflection->GetInt32(message, F("default_sfixed32")));
+ EXPECT_EQ(-50, reflection->GetInt64(message, F("default_sfixed64")));
+ EXPECT_EQ(51.5, reflection->GetFloat(message, F("default_float")));
+ EXPECT_EQ(52e3, reflection->GetDouble(message, F("default_double")));
+ EXPECT_TRUE(reflection->GetBool(message, F("default_bool")));
+ EXPECT_EQ("hello", reflection->GetString(message, F("default_string")));
+ EXPECT_EQ("world", reflection->GetString(message, F("default_bytes")));
+
+ EXPECT_EQ("hello", reflection->GetStringReference(
+ message, F("default_string"), &scratch));
+ EXPECT_EQ("world", reflection->GetStringReference(message, F("default_bytes"),
+ &scratch));
+
+ EXPECT_EQ(nested_bar_,
+ reflection->GetEnum(message, F("default_nested_enum")));
+ EXPECT_EQ(foreign_bar_,
+ reflection->GetEnum(message, F("default_foreign_enum")));
+ EXPECT_EQ(import_bar_,
+ reflection->GetEnum(message, F("default_import_enum")));
+
+ EXPECT_EQ("abc", reflection->GetString(message, F("default_string_piece")));
+ EXPECT_EQ("abc", reflection->GetStringReference(
+ message, F("default_string_piece"), &scratch));
+
+ EXPECT_EQ("123", reflection->GetString(message, F("default_cord")));
+ EXPECT_EQ("123", reflection->GetStringReference(message, F("default_cord"),
+ &scratch));
+}
+
+inline void TestUtil::ReflectionTester::ExpectPackedClearViaReflection(
+ const Message& message) {
+ const Reflection* reflection = message.GetReflection();
+
+ EXPECT_EQ(0, reflection->FieldSize(message, F("packed_int32")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("packed_int64")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("packed_uint32")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("packed_uint64")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sint32")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sint64")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("packed_fixed32")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("packed_fixed64")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sfixed32")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sfixed64")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("packed_float")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("packed_double")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("packed_bool")));
+ EXPECT_EQ(0, reflection->FieldSize(message, F("packed_enum")));
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ReflectionTester::ModifyRepeatedFieldsViaReflection(
+ Message* message) {
+ const Reflection* reflection = message->GetReflection();
+ Message* sub_message;
+
+ reflection->SetRepeatedInt32(message, F("repeated_int32"), 1, 501);
+ reflection->SetRepeatedInt64(message, F("repeated_int64"), 1, 502);
+ reflection->SetRepeatedUInt32(message, F("repeated_uint32"), 1, 503);
+ reflection->SetRepeatedUInt64(message, F("repeated_uint64"), 1, 504);
+ reflection->SetRepeatedInt32(message, F("repeated_sint32"), 1, 505);
+ reflection->SetRepeatedInt64(message, F("repeated_sint64"), 1, 506);
+ reflection->SetRepeatedUInt32(message, F("repeated_fixed32"), 1, 507);
+ reflection->SetRepeatedUInt64(message, F("repeated_fixed64"), 1, 508);
+ reflection->SetRepeatedInt32(message, F("repeated_sfixed32"), 1, 509);
+ reflection->SetRepeatedInt64(message, F("repeated_sfixed64"), 1, 510);
+ reflection->SetRepeatedFloat(message, F("repeated_float"), 1, 511);
+ reflection->SetRepeatedDouble(message, F("repeated_double"), 1, 512);
+ reflection->SetRepeatedBool(message, F("repeated_bool"), 1, true);
+ reflection->SetRepeatedString(message, F("repeated_string"), 1, "515");
+ reflection->SetRepeatedString(message, F("repeated_bytes"), 1, "516");
+
+ sub_message =
+ reflection->MutableRepeatedMessage(message, F("repeatedgroup"), 1);
+ sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 517);
+ sub_message = reflection->MutableRepeatedMessage(
+ message, F("repeated_nested_message"), 1);
+ sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 518);
+ sub_message = reflection->MutableRepeatedMessage(
+ message, F("repeated_foreign_message"), 1);
+ sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 519);
+ sub_message = reflection->MutableRepeatedMessage(
+ message, F("repeated_import_message"), 1);
+ sub_message->GetReflection()->SetInt32(sub_message, import_d_, 520);
+ sub_message = reflection->MutableRepeatedMessage(
+ message, F("repeated_lazy_message"), 1);
+ sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 527);
+
+ reflection->SetRepeatedEnum(message, F("repeated_nested_enum"), 1,
+ nested_foo_);
+ reflection->SetRepeatedEnum(message, F("repeated_foreign_enum"), 1,
+ foreign_foo_);
+ reflection->SetRepeatedEnum(message, F("repeated_import_enum"), 1,
+ import_foo_);
+
+ reflection->SetRepeatedString(message, F("repeated_string_piece"), 1, "524");
+ reflection->SetRepeatedString(message, F("repeated_cord"), 1, "525");
+}
+
+inline void TestUtil::ReflectionTester::ModifyPackedFieldsViaReflection(
+ Message* message) {
+ const Reflection* reflection = message->GetReflection();
+ reflection->SetRepeatedInt32(message, F("packed_int32"), 1, 801);
+ reflection->SetRepeatedInt64(message, F("packed_int64"), 1, 802);
+ reflection->SetRepeatedUInt32(message, F("packed_uint32"), 1, 803);
+ reflection->SetRepeatedUInt64(message, F("packed_uint64"), 1, 804);
+ reflection->SetRepeatedInt32(message, F("packed_sint32"), 1, 805);
+ reflection->SetRepeatedInt64(message, F("packed_sint64"), 1, 806);
+ reflection->SetRepeatedUInt32(message, F("packed_fixed32"), 1, 807);
+ reflection->SetRepeatedUInt64(message, F("packed_fixed64"), 1, 808);
+ reflection->SetRepeatedInt32(message, F("packed_sfixed32"), 1, 809);
+ reflection->SetRepeatedInt64(message, F("packed_sfixed64"), 1, 810);
+ reflection->SetRepeatedFloat(message, F("packed_float"), 1, 811);
+ reflection->SetRepeatedDouble(message, F("packed_double"), 1, 812);
+ reflection->SetRepeatedBool(message, F("packed_bool"), 1, true);
+ reflection->SetRepeatedEnum(message, F("packed_enum"), 1, foreign_foo_);
+}
+
+inline void TestUtil::ReflectionTester::RemoveLastRepeatedsViaReflection(
+ Message* message) {
+ const Reflection* reflection = message->GetReflection();
+
+ std::vector<const FieldDescriptor*> output;
+ reflection->ListFields(*message, &output);
+ for (int i = 0; i < output.size(); ++i) {
+ const FieldDescriptor* field = output[i];
+ if (!field->is_repeated()) continue;
+
+ reflection->RemoveLast(message, field);
+ }
+}
+
+inline void TestUtil::ReflectionTester::ReleaseLastRepeatedsViaReflection(
+ Message* message, bool expect_extensions_notnull) {
+ const Reflection* reflection = message->GetReflection();
+
+ std::vector<const FieldDescriptor*> output;
+ reflection->ListFields(*message, &output);
+ for (int i = 0; i < output.size(); ++i) {
+ const FieldDescriptor* field = output[i];
+ if (!field->is_repeated()) continue;
+ if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) continue;
+
+ Message* released = reflection->ReleaseLast(message, field);
+ if (!field->is_extension() || expect_extensions_notnull) {
+ ASSERT_TRUE(released != nullptr)
+ << "ReleaseLast returned nullptr for: " << field->name();
+ }
+ delete released;
+ }
+}
+
+inline void TestUtil::ReflectionTester::SwapRepeatedsViaReflection(
+ Message* message) {
+ const Reflection* reflection = message->GetReflection();
+
+ std::vector<const FieldDescriptor*> output;
+ reflection->ListFields(*message, &output);
+ for (int i = 0; i < output.size(); ++i) {
+ const FieldDescriptor* field = output[i];
+ if (!field->is_repeated()) continue;
+
+ reflection->SwapElements(message, field, 0, 1);
+ }
+}
+
+inline void TestUtil::ReflectionTester::
+ SetAllocatedOptionalMessageFieldsToNullViaReflection(Message* message) {
+ const Reflection* reflection = message->GetReflection();
+
+ std::vector<const FieldDescriptor*> fields;
+ reflection->ListFields(*message, &fields);
+
+ for (int i = 0; i < fields.size(); ++i) {
+ const FieldDescriptor* field = fields[i];
+ if (!field->is_optional() ||
+ field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE)
+ continue;
+
+ reflection->SetAllocatedMessage(message, nullptr, field);
+ }
+}
+
+inline void TestUtil::ReflectionTester::
+ SetAllocatedOptionalMessageFieldsToMessageViaReflection(
+ Message* from_message, Message* to_message) {
+ EXPECT_EQ(from_message->GetDescriptor(), to_message->GetDescriptor());
+ const Reflection* from_reflection = from_message->GetReflection();
+ const Reflection* to_reflection = to_message->GetReflection();
+
+ std::vector<const FieldDescriptor*> fields;
+ from_reflection->ListFields(*from_message, &fields);
+
+ for (int i = 0; i < fields.size(); ++i) {
+ const FieldDescriptor* field = fields[i];
+ if (!field->is_optional() ||
+ field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE)
+ continue;
+
+ Message* sub_message = from_reflection->ReleaseMessage(from_message, field);
+ to_reflection->SetAllocatedMessage(to_message, sub_message, field);
+ }
+}
+
+inline void TestUtil::ReflectionTester::ExpectMessagesReleasedViaReflection(
+ Message* message,
+ TestUtil::ReflectionTester::MessageReleaseState expected_release_state) {
+ const Reflection* reflection = message->GetReflection();
+
+ static const char* fields[] = {
+ "optionalgroup",
+ "optional_nested_message",
+ "optional_foreign_message",
+ "optional_import_message",
+ };
+ for (int i = 0; i < GOOGLE_ARRAYSIZE(fields); i++) {
+ const Message& sub_message = reflection->GetMessage(*message, F(fields[i]));
+ Message* released = reflection->ReleaseMessage(message, F(fields[i]));
+ switch (expected_release_state) {
+ case IS_NULL:
+ EXPECT_TRUE(released == nullptr);
+ break;
+ case NOT_NULL:
+ EXPECT_TRUE(released != nullptr);
+ if (message->GetArena() == nullptr) {
+ // released message must be same as sub_message if source message is
+ // not on arena.
+ EXPECT_EQ(&sub_message, released);
+ }
+ break;
+ case CAN_BE_NULL:
+ break;
+ }
+ delete released;
+ EXPECT_FALSE(reflection->HasField(*message, F(fields[i])));
+ }
+}
+
+// Check that the passed-in serialization is the canonical serialization we
+// expect for a TestFieldOrderings message filled in by
+// SetAllFieldsAndExtensions().
+inline void ExpectAllFieldsAndExtensionsInOrder(
+ const string& serialized) {
+ // We set each field individually, serialize separately, and concatenate all
+ // the strings in canonical order to determine the expected serialization.
+ string expected;
+ unittest::TestFieldOrderings message;
+ message.set_my_int(1); // Field 1.
+ message.AppendToString(&expected);
+ message.Clear();
+ message.SetExtension(unittest::my_extension_int, 23); // Field 5.
+ message.AppendToString(&expected);
+ message.Clear();
+ message.set_my_string("foo"); // Field 11.
+ message.AppendToString(&expected);
+ message.Clear();
+ message.SetExtension(unittest::my_extension_string, "bar"); // Field 50.
+ message.AppendToString(&expected);
+ message.Clear();
+ message.set_my_float(1.0); // Field 101.
+ message.AppendToString(&expected);
+ message.Clear();
+
+ // We don't EXPECT_EQ() since we don't want to print raw bytes to stdout.
+ EXPECT_TRUE(serialized == expected);
+}
+
+} // namespace TestUtil
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/test_util.inc b/src/google/protobuf/test_util.inc
new file mode 100644
index 00000000..185f68d9
--- /dev/null
+++ b/src/google/protobuf/test_util.inc
@@ -0,0 +1,2600 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: kenton@google.com (Kenton Varda)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+//
+// This file needs to be included as .inc as it depends on the namespaces
+// (unittest and unittest_import) being set up properly. It is also included
+// within an enclosing namespace and requires header files to be included
+// out of this file.
+
+#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/message.h>
+#include <google/protobuf/testing/googletest.h>
+#include <gtest/gtest.h>
+
+namespace google {
+namespace protobuf {
+namespace TestUtil {
+
+// Set every field in the message to a unique value.
+inline void SetAllFields(UNITTEST::TestAllTypes* message);
+inline void SetOptionalFields(UNITTEST::TestAllTypes* message);
+inline void AddRepeatedFields1(UNITTEST::TestAllTypes* message);
+inline void AddRepeatedFields2(UNITTEST::TestAllTypes* message);
+inline void SetDefaultFields(UNITTEST::TestAllTypes* message);
+inline void SetOneofFields(UNITTEST::TestAllTypes* message);
+inline void SetAllExtensions(UNITTEST::TestAllExtensions* message);
+inline void SetOneofFields(UNITTEST::TestAllExtensions* message);
+inline void SetAllFieldsAndExtensions(UNITTEST::TestFieldOrderings* message);
+inline void SetPackedFields(UNITTEST::TestPackedTypes* message);
+inline void SetPackedExtensions(UNITTEST::TestPackedExtensions* message);
+inline void SetUnpackedFields(UNITTEST::TestUnpackedTypes* message);
+inline void SetOneof1(UNITTEST::TestOneof2* message);
+inline void SetOneof2(UNITTEST::TestOneof2* message);
+
+// Use the repeated versions of the set_*() accessors to modify all the
+// repeated fields of the message (which should already have been
+// initialized with Set*Fields()). Set*Fields() itself only tests
+// the add_*() accessors.
+inline void ModifyRepeatedFields(UNITTEST::TestAllTypes* message);
+inline void ModifyRepeatedExtensions(UNITTEST::TestAllExtensions* message);
+inline void ModifyPackedFields(UNITTEST::TestPackedTypes* message);
+inline void ModifyPackedExtensions(UNITTEST::TestPackedExtensions* message);
+
+// Check that all fields have the values that they should have after
+// Set*Fields() is called.
+inline void ExpectAllFieldsSet(const UNITTEST::TestAllTypes& message);
+inline void ExpectAllExtensionsSet(const UNITTEST::TestAllExtensions& message);
+inline void ExpectPackedFieldsSet(const UNITTEST::TestPackedTypes& message);
+inline void ExpectPackedExtensionsSet(
+ const UNITTEST::TestPackedExtensions& message);
+inline void ExpectUnpackedFieldsSet(const UNITTEST::TestUnpackedTypes& message);
+inline void ExpectUnpackedExtensionsSet(
+ const UNITTEST::TestUnpackedExtensions& message);
+inline void ExpectOneofSet1(const UNITTEST::TestOneof2& message);
+inline void ExpectOneofSet2(const UNITTEST::TestOneof2& message);
+
+// Expect that the message is modified as would be expected from
+// Modify*Fields().
+inline void ExpectRepeatedFieldsModified(const UNITTEST::TestAllTypes& message);
+inline void ExpectRepeatedExtensionsModified(
+ const UNITTEST::TestAllExtensions& message);
+inline void ExpectPackedFieldsModified(
+ const UNITTEST::TestPackedTypes& message);
+inline void ExpectPackedExtensionsModified(
+ const UNITTEST::TestPackedExtensions& message);
+
+// Check that all fields have their default values.
+inline void ExpectClear(const UNITTEST::TestAllTypes& message);
+inline void ExpectExtensionsClear(const UNITTEST::TestAllExtensions& message);
+inline void ExpectPackedClear(const UNITTEST::TestPackedTypes& message);
+inline void ExpectPackedExtensionsClear(
+ const UNITTEST::TestPackedExtensions& message);
+inline void ExpectOneofClear(const UNITTEST::TestOneof2& message);
+
+// Check that all repeated fields have had their last elements removed.
+inline void ExpectLastRepeatedsRemoved(const UNITTEST::TestAllTypes& message);
+inline void ExpectLastRepeatedExtensionsRemoved(
+ const UNITTEST::TestAllExtensions& message);
+inline void ExpectLastRepeatedsReleased(const UNITTEST::TestAllTypes& message);
+inline void ExpectLastRepeatedExtensionsReleased(
+ const UNITTEST::TestAllExtensions& message);
+
+// Check that all repeated fields have had their first and last elements
+// swapped.
+inline void ExpectRepeatedsSwapped(const UNITTEST::TestAllTypes& message);
+inline void ExpectRepeatedExtensionsSwapped(
+ const UNITTEST::TestAllExtensions& message);
+
+inline void ExpectAtMostOneFieldSetInOneof(const UNITTEST::TestOneof2& message);
+
+} // namespace TestUtil
+
+inline void TestUtil::SetAllFields(UNITTEST::TestAllTypes* message) {
+ SetOptionalFields(message);
+ AddRepeatedFields1(message);
+ AddRepeatedFields2(message);
+ SetDefaultFields(message);
+ SetOneofFields(message);
+}
+
+inline void TestUtil::SetOptionalFields(UNITTEST::TestAllTypes* message) {
+ message->set_optional_int32(101);
+ message->set_optional_int64(102);
+ message->set_optional_uint32(103);
+ message->set_optional_uint64(104);
+ message->set_optional_sint32(105);
+ message->set_optional_sint64(106);
+ message->set_optional_fixed32(107);
+ message->set_optional_fixed64(108);
+ message->set_optional_sfixed32(109);
+ message->set_optional_sfixed64(110);
+ message->set_optional_float(111);
+ message->set_optional_double(112);
+ message->set_optional_bool(true);
+ message->set_optional_string("115");
+ message->set_optional_bytes("116");
+
+ message->mutable_optionalgroup()->set_a(117);
+ message->mutable_optional_nested_message()->set_bb(118);
+ message->mutable_optional_foreign_message()->set_c(119);
+ message->mutable_optional_import_message()->set_d(120);
+ message->mutable_optional_public_import_message()->set_e(126);
+ message->mutable_optional_lazy_message()->set_bb(127);
+
+ message->set_optional_nested_enum(UNITTEST::TestAllTypes::BAZ);
+ message->set_optional_foreign_enum(UNITTEST::FOREIGN_BAZ);
+ message->set_optional_import_enum(UNITTEST_IMPORT::IMPORT_BAZ);
+
+ // StringPiece and Cord fields are only accessible via reflection in the
+ // open source release; see comments in compiler/cpp/string_field.cc.
+#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
+ message->GetReflection()->SetString(
+ message,
+ message->GetDescriptor()->FindFieldByName("optional_string_piece"),
+ "124");
+ message->GetReflection()->SetString(
+ message, message->GetDescriptor()->FindFieldByName("optional_cord"),
+ "125");
+#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::AddRepeatedFields1(UNITTEST::TestAllTypes* message) {
+ message->add_repeated_int32(201);
+ message->add_repeated_int64(202);
+ message->add_repeated_uint32(203);
+ message->add_repeated_uint64(204);
+ message->add_repeated_sint32(205);
+ message->add_repeated_sint64(206);
+ message->add_repeated_fixed32(207);
+ message->add_repeated_fixed64(208);
+ message->add_repeated_sfixed32(209);
+ message->add_repeated_sfixed64(210);
+ message->add_repeated_float(211);
+ message->add_repeated_double(212);
+ message->add_repeated_bool(true);
+ message->add_repeated_string("215");
+ message->add_repeated_bytes("216");
+
+ message->add_repeatedgroup()->set_a(217);
+ message->add_repeated_nested_message()->set_bb(218);
+ message->add_repeated_foreign_message()->set_c(219);
+ message->add_repeated_import_message()->set_d(220);
+ message->add_repeated_lazy_message()->set_bb(227);
+
+ message->add_repeated_nested_enum(UNITTEST::TestAllTypes::BAR);
+ message->add_repeated_foreign_enum(UNITTEST::FOREIGN_BAR);
+ message->add_repeated_import_enum(UNITTEST_IMPORT::IMPORT_BAR);
+
+#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
+ message->GetReflection()->AddString(
+ message,
+ message->GetDescriptor()->FindFieldByName("repeated_string_piece"),
+ "224");
+ message->GetReflection()->AddString(
+ message, message->GetDescriptor()->FindFieldByName("repeated_cord"),
+ "225");
+#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
+}
+
+inline void TestUtil::AddRepeatedFields2(UNITTEST::TestAllTypes* message) {
+ // Add a second one of each field.
+ message->add_repeated_int32(301);
+ message->add_repeated_int64(302);
+ message->add_repeated_uint32(303);
+ message->add_repeated_uint64(304);
+ message->add_repeated_sint32(305);
+ message->add_repeated_sint64(306);
+ message->add_repeated_fixed32(307);
+ message->add_repeated_fixed64(308);
+ message->add_repeated_sfixed32(309);
+ message->add_repeated_sfixed64(310);
+ message->add_repeated_float(311);
+ message->add_repeated_double(312);
+ message->add_repeated_bool(false);
+ message->add_repeated_string("315");
+ message->add_repeated_bytes("316");
+
+ message->add_repeatedgroup()->set_a(317);
+ message->add_repeated_nested_message()->set_bb(318);
+ message->add_repeated_foreign_message()->set_c(319);
+ message->add_repeated_import_message()->set_d(320);
+ message->add_repeated_lazy_message()->set_bb(327);
+
+ message->add_repeated_nested_enum(UNITTEST::TestAllTypes::BAZ);
+ message->add_repeated_foreign_enum(UNITTEST::FOREIGN_BAZ);
+ message->add_repeated_import_enum(UNITTEST_IMPORT::IMPORT_BAZ);
+
+#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
+ message->GetReflection()->AddString(
+ message,
+ message->GetDescriptor()->FindFieldByName("repeated_string_piece"),
+ "324");
+ message->GetReflection()->AddString(
+ message, message->GetDescriptor()->FindFieldByName("repeated_cord"),
+ "325");
+#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::SetDefaultFields(UNITTEST::TestAllTypes* message) {
+ message->set_default_int32(401);
+ message->set_default_int64(402);
+ message->set_default_uint32(403);
+ message->set_default_uint64(404);
+ message->set_default_sint32(405);
+ message->set_default_sint64(406);
+ message->set_default_fixed32(407);
+ message->set_default_fixed64(408);
+ message->set_default_sfixed32(409);
+ message->set_default_sfixed64(410);
+ message->set_default_float(411);
+ message->set_default_double(412);
+ message->set_default_bool(false);
+ message->set_default_string("415");
+ message->set_default_bytes("416");
+
+ message->set_default_nested_enum(UNITTEST::TestAllTypes::FOO);
+ message->set_default_foreign_enum(UNITTEST::FOREIGN_FOO);
+ message->set_default_import_enum(UNITTEST_IMPORT::IMPORT_FOO);
+
+#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
+ message->GetReflection()->SetString(
+ message,
+ message->GetDescriptor()->FindFieldByName("default_string_piece"), "424");
+ message->GetReflection()->SetString(
+ message, message->GetDescriptor()->FindFieldByName("default_cord"),
+ "425");
+#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ModifyRepeatedFields(UNITTEST::TestAllTypes* message) {
+ message->set_repeated_int32(1, 501);
+ message->set_repeated_int64(1, 502);
+ message->set_repeated_uint32(1, 503);
+ message->set_repeated_uint64(1, 504);
+ message->set_repeated_sint32(1, 505);
+ message->set_repeated_sint64(1, 506);
+ message->set_repeated_fixed32(1, 507);
+ message->set_repeated_fixed64(1, 508);
+ message->set_repeated_sfixed32(1, 509);
+ message->set_repeated_sfixed64(1, 510);
+ message->set_repeated_float(1, 511);
+ message->set_repeated_double(1, 512);
+ message->set_repeated_bool(1, true);
+ message->set_repeated_string(1, "515");
+ message->set_repeated_bytes(1, "516");
+
+ message->mutable_repeatedgroup(1)->set_a(517);
+ message->mutable_repeated_nested_message(1)->set_bb(518);
+ message->mutable_repeated_foreign_message(1)->set_c(519);
+ message->mutable_repeated_import_message(1)->set_d(520);
+ message->mutable_repeated_lazy_message(1)->set_bb(527);
+
+ message->set_repeated_nested_enum(1, UNITTEST::TestAllTypes::FOO);
+ message->set_repeated_foreign_enum(1, UNITTEST::FOREIGN_FOO);
+ message->set_repeated_import_enum(1, UNITTEST_IMPORT::IMPORT_FOO);
+
+#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
+ message->GetReflection()->SetRepeatedString(
+ message,
+ message->GetDescriptor()->FindFieldByName("repeated_string_piece"), 1,
+ "524");
+ message->GetReflection()->SetRepeatedString(
+ message, message->GetDescriptor()->FindFieldByName("repeated_cord"), 1,
+ "525");
+#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
+}
+
+// ------------------------------------------------------------------
+inline void TestUtil::SetOneofFields(UNITTEST::TestAllTypes* message) {
+ message->set_oneof_uint32(601);
+ message->mutable_oneof_nested_message()->set_bb(602);
+ message->set_oneof_string("603");
+ message->set_oneof_bytes("604");
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ExpectAllFieldsSet(
+ const UNITTEST::TestAllTypes& message) {
+ EXPECT_TRUE(message.has_optional_int32());
+ EXPECT_TRUE(message.has_optional_int64());
+ EXPECT_TRUE(message.has_optional_uint32());
+ EXPECT_TRUE(message.has_optional_uint64());
+ EXPECT_TRUE(message.has_optional_sint32());
+ EXPECT_TRUE(message.has_optional_sint64());
+ EXPECT_TRUE(message.has_optional_fixed32());
+ EXPECT_TRUE(message.has_optional_fixed64());
+ EXPECT_TRUE(message.has_optional_sfixed32());
+ EXPECT_TRUE(message.has_optional_sfixed64());
+ EXPECT_TRUE(message.has_optional_float());
+ EXPECT_TRUE(message.has_optional_double());
+ EXPECT_TRUE(message.has_optional_bool());
+ EXPECT_TRUE(message.has_optional_string());
+ EXPECT_TRUE(message.has_optional_bytes());
+
+ EXPECT_TRUE(message.has_optionalgroup());
+ EXPECT_TRUE(message.has_optional_nested_message());
+ EXPECT_TRUE(message.has_optional_foreign_message());
+ EXPECT_TRUE(message.has_optional_import_message());
+ EXPECT_TRUE(message.has_optional_public_import_message());
+ EXPECT_TRUE(message.has_optional_lazy_message());
+
+ EXPECT_TRUE(message.optionalgroup().has_a());
+ EXPECT_TRUE(message.optional_nested_message().has_bb());
+ EXPECT_TRUE(message.optional_foreign_message().has_c());
+ EXPECT_TRUE(message.optional_import_message().has_d());
+ EXPECT_TRUE(message.optional_public_import_message().has_e());
+ EXPECT_TRUE(message.optional_lazy_message().has_bb());
+
+ EXPECT_TRUE(message.has_optional_nested_enum());
+ EXPECT_TRUE(message.has_optional_foreign_enum());
+ EXPECT_TRUE(message.has_optional_import_enum());
+
+#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
+ EXPECT_TRUE(message.has_optional_string_piece());
+ EXPECT_TRUE(message.has_optional_cord());
+#endif
+
+ EXPECT_EQ(101, message.optional_int32());
+ EXPECT_EQ(102, message.optional_int64());
+ EXPECT_EQ(103, message.optional_uint32());
+ EXPECT_EQ(104, message.optional_uint64());
+ EXPECT_EQ(105, message.optional_sint32());
+ EXPECT_EQ(106, message.optional_sint64());
+ EXPECT_EQ(107, message.optional_fixed32());
+ EXPECT_EQ(108, message.optional_fixed64());
+ EXPECT_EQ(109, message.optional_sfixed32());
+ EXPECT_EQ(110, message.optional_sfixed64());
+ EXPECT_EQ(111, message.optional_float());
+ EXPECT_EQ(112, message.optional_double());
+ EXPECT_TRUE(message.optional_bool());
+ EXPECT_EQ("115", message.optional_string());
+ EXPECT_EQ("116", message.optional_bytes());
+
+ EXPECT_EQ(117, message.optionalgroup().a());
+ EXPECT_EQ(118, message.optional_nested_message().bb());
+ EXPECT_EQ(119, message.optional_foreign_message().c());
+ EXPECT_EQ(120, message.optional_import_message().d());
+ EXPECT_EQ(126, message.optional_public_import_message().e());
+ EXPECT_EQ(127, message.optional_lazy_message().bb());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, message.optional_nested_enum());
+ EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.optional_foreign_enum());
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ, message.optional_import_enum());
+
+
+ // -----------------------------------------------------------------
+
+ ASSERT_EQ(2, message.repeated_int32_size());
+ ASSERT_EQ(2, message.repeated_int64_size());
+ ASSERT_EQ(2, message.repeated_uint32_size());
+ ASSERT_EQ(2, message.repeated_uint64_size());
+ ASSERT_EQ(2, message.repeated_sint32_size());
+ ASSERT_EQ(2, message.repeated_sint64_size());
+ ASSERT_EQ(2, message.repeated_fixed32_size());
+ ASSERT_EQ(2, message.repeated_fixed64_size());
+ ASSERT_EQ(2, message.repeated_sfixed32_size());
+ ASSERT_EQ(2, message.repeated_sfixed64_size());
+ ASSERT_EQ(2, message.repeated_float_size());
+ ASSERT_EQ(2, message.repeated_double_size());
+ ASSERT_EQ(2, message.repeated_bool_size());
+ ASSERT_EQ(2, message.repeated_string_size());
+ ASSERT_EQ(2, message.repeated_bytes_size());
+
+ ASSERT_EQ(2, message.repeatedgroup_size());
+ ASSERT_EQ(2, message.repeated_nested_message_size());
+ ASSERT_EQ(2, message.repeated_foreign_message_size());
+ ASSERT_EQ(2, message.repeated_import_message_size());
+ ASSERT_EQ(2, message.repeated_lazy_message_size());
+ ASSERT_EQ(2, message.repeated_nested_enum_size());
+ ASSERT_EQ(2, message.repeated_foreign_enum_size());
+ ASSERT_EQ(2, message.repeated_import_enum_size());
+
+#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
+ ASSERT_EQ(2, message.repeated_string_piece_size());
+ ASSERT_EQ(2, message.repeated_cord_size());
+#endif
+
+ EXPECT_EQ(201, message.repeated_int32(0));
+ EXPECT_EQ(202, message.repeated_int64(0));
+ EXPECT_EQ(203, message.repeated_uint32(0));
+ EXPECT_EQ(204, message.repeated_uint64(0));
+ EXPECT_EQ(205, message.repeated_sint32(0));
+ EXPECT_EQ(206, message.repeated_sint64(0));
+ EXPECT_EQ(207, message.repeated_fixed32(0));
+ EXPECT_EQ(208, message.repeated_fixed64(0));
+ EXPECT_EQ(209, message.repeated_sfixed32(0));
+ EXPECT_EQ(210, message.repeated_sfixed64(0));
+ EXPECT_EQ(211, message.repeated_float(0));
+ EXPECT_EQ(212, message.repeated_double(0));
+ EXPECT_TRUE(message.repeated_bool(0));
+ EXPECT_EQ("215", message.repeated_string(0));
+ EXPECT_EQ("216", message.repeated_bytes(0));
+
+ EXPECT_EQ(217, message.repeatedgroup(0).a());
+ EXPECT_EQ(218, message.repeated_nested_message(0).bb());
+ EXPECT_EQ(219, message.repeated_foreign_message(0).c());
+ EXPECT_EQ(220, message.repeated_import_message(0).d());
+ EXPECT_EQ(227, message.repeated_lazy_message(0).bb());
+
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message.repeated_nested_enum(0));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeated_foreign_enum(0));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, message.repeated_import_enum(0));
+
+ EXPECT_EQ(301, message.repeated_int32(1));
+ EXPECT_EQ(302, message.repeated_int64(1));
+ EXPECT_EQ(303, message.repeated_uint32(1));
+ EXPECT_EQ(304, message.repeated_uint64(1));
+ EXPECT_EQ(305, message.repeated_sint32(1));
+ EXPECT_EQ(306, message.repeated_sint64(1));
+ EXPECT_EQ(307, message.repeated_fixed32(1));
+ EXPECT_EQ(308, message.repeated_fixed64(1));
+ EXPECT_EQ(309, message.repeated_sfixed32(1));
+ EXPECT_EQ(310, message.repeated_sfixed64(1));
+ EXPECT_EQ(311, message.repeated_float(1));
+ EXPECT_EQ(312, message.repeated_double(1));
+ EXPECT_FALSE(message.repeated_bool(1));
+ EXPECT_EQ("315", message.repeated_string(1));
+ EXPECT_EQ("316", message.repeated_bytes(1));
+
+ EXPECT_EQ(317, message.repeatedgroup(1).a());
+ EXPECT_EQ(318, message.repeated_nested_message(1).bb());
+ EXPECT_EQ(319, message.repeated_foreign_message(1).c());
+ EXPECT_EQ(320, message.repeated_import_message(1).d());
+ EXPECT_EQ(327, message.repeated_lazy_message(1).bb());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, message.repeated_nested_enum(1));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.repeated_foreign_enum(1));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ, message.repeated_import_enum(1));
+
+
+ // -----------------------------------------------------------------
+
+ EXPECT_TRUE(message.has_default_int32());
+ EXPECT_TRUE(message.has_default_int64());
+ EXPECT_TRUE(message.has_default_uint32());
+ EXPECT_TRUE(message.has_default_uint64());
+ EXPECT_TRUE(message.has_default_sint32());
+ EXPECT_TRUE(message.has_default_sint64());
+ EXPECT_TRUE(message.has_default_fixed32());
+ EXPECT_TRUE(message.has_default_fixed64());
+ EXPECT_TRUE(message.has_default_sfixed32());
+ EXPECT_TRUE(message.has_default_sfixed64());
+ EXPECT_TRUE(message.has_default_float());
+ EXPECT_TRUE(message.has_default_double());
+ EXPECT_TRUE(message.has_default_bool());
+ EXPECT_TRUE(message.has_default_string());
+ EXPECT_TRUE(message.has_default_bytes());
+
+ EXPECT_TRUE(message.has_default_nested_enum());
+ EXPECT_TRUE(message.has_default_foreign_enum());
+ EXPECT_TRUE(message.has_default_import_enum());
+
+
+ EXPECT_EQ(401, message.default_int32());
+ EXPECT_EQ(402, message.default_int64());
+ EXPECT_EQ(403, message.default_uint32());
+ EXPECT_EQ(404, message.default_uint64());
+ EXPECT_EQ(405, message.default_sint32());
+ EXPECT_EQ(406, message.default_sint64());
+ EXPECT_EQ(407, message.default_fixed32());
+ EXPECT_EQ(408, message.default_fixed64());
+ EXPECT_EQ(409, message.default_sfixed32());
+ EXPECT_EQ(410, message.default_sfixed64());
+ EXPECT_EQ(411, message.default_float());
+ EXPECT_EQ(412, message.default_double());
+ EXPECT_FALSE(message.default_bool());
+ EXPECT_EQ("415", message.default_string());
+ EXPECT_EQ("416", message.default_bytes());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message.default_nested_enum());
+ EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.default_foreign_enum());
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO, message.default_import_enum());
+
+
+ EXPECT_FALSE(message.has_oneof_uint32());
+ EXPECT_FALSE(message.has_oneof_nested_message());
+ EXPECT_FALSE(message.has_oneof_string());
+ EXPECT_TRUE(message.has_oneof_bytes());
+
+ EXPECT_EQ("604", message.oneof_bytes());
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ExpectClear(const UNITTEST::TestAllTypes& message) {
+ // has_blah() should initially be false for all optional fields.
+ EXPECT_FALSE(message.has_optional_int32());
+ EXPECT_FALSE(message.has_optional_int64());
+ EXPECT_FALSE(message.has_optional_uint32());
+ EXPECT_FALSE(message.has_optional_uint64());
+ EXPECT_FALSE(message.has_optional_sint32());
+ EXPECT_FALSE(message.has_optional_sint64());
+ EXPECT_FALSE(message.has_optional_fixed32());
+ EXPECT_FALSE(message.has_optional_fixed64());
+ EXPECT_FALSE(message.has_optional_sfixed32());
+ EXPECT_FALSE(message.has_optional_sfixed64());
+ EXPECT_FALSE(message.has_optional_float());
+ EXPECT_FALSE(message.has_optional_double());
+ EXPECT_FALSE(message.has_optional_bool());
+ EXPECT_FALSE(message.has_optional_string());
+ EXPECT_FALSE(message.has_optional_bytes());
+
+ EXPECT_FALSE(message.has_optionalgroup());
+ EXPECT_FALSE(message.has_optional_nested_message());
+ EXPECT_FALSE(message.has_optional_foreign_message());
+ EXPECT_FALSE(message.has_optional_import_message());
+ EXPECT_FALSE(message.has_optional_public_import_message());
+ EXPECT_FALSE(message.has_optional_lazy_message());
+
+ EXPECT_FALSE(message.has_optional_nested_enum());
+ EXPECT_FALSE(message.has_optional_foreign_enum());
+ EXPECT_FALSE(message.has_optional_import_enum());
+
+ EXPECT_FALSE(message.has_optional_string_piece());
+ EXPECT_FALSE(message.has_optional_cord());
+
+ // Optional fields without defaults are set to zero or something like it.
+ EXPECT_EQ(0, message.optional_int32());
+ EXPECT_EQ(0, message.optional_int64());
+ EXPECT_EQ(0, message.optional_uint32());
+ EXPECT_EQ(0, message.optional_uint64());
+ EXPECT_EQ(0, message.optional_sint32());
+ EXPECT_EQ(0, message.optional_sint64());
+ EXPECT_EQ(0, message.optional_fixed32());
+ EXPECT_EQ(0, message.optional_fixed64());
+ EXPECT_EQ(0, message.optional_sfixed32());
+ EXPECT_EQ(0, message.optional_sfixed64());
+ EXPECT_EQ(0, message.optional_float());
+ EXPECT_EQ(0, message.optional_double());
+ EXPECT_FALSE(message.optional_bool());
+ EXPECT_EQ("", message.optional_string());
+ EXPECT_EQ("", message.optional_bytes());
+
+ // Embedded messages should also be clear.
+ EXPECT_FALSE(message.optionalgroup().has_a());
+ EXPECT_FALSE(message.optional_nested_message().has_bb());
+ EXPECT_FALSE(message.optional_foreign_message().has_c());
+ EXPECT_FALSE(message.optional_import_message().has_d());
+ EXPECT_FALSE(message.optional_public_import_message().has_e());
+ EXPECT_FALSE(message.optional_lazy_message().has_bb());
+
+ EXPECT_EQ(0, message.optionalgroup().a());
+ EXPECT_EQ(0, message.optional_nested_message().bb());
+ EXPECT_EQ(0, message.optional_foreign_message().c());
+ EXPECT_EQ(0, message.optional_import_message().d());
+ EXPECT_EQ(0, message.optional_public_import_message().e());
+ EXPECT_EQ(0, message.optional_lazy_message().bb());
+
+ // Enums without defaults are set to the first value in the enum.
+ EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message.optional_nested_enum());
+ EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.optional_foreign_enum());
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO, message.optional_import_enum());
+
+
+ // Repeated fields are empty.
+ EXPECT_EQ(0, message.repeated_int32_size());
+ EXPECT_EQ(0, message.repeated_int64_size());
+ EXPECT_EQ(0, message.repeated_uint32_size());
+ EXPECT_EQ(0, message.repeated_uint64_size());
+ EXPECT_EQ(0, message.repeated_sint32_size());
+ EXPECT_EQ(0, message.repeated_sint64_size());
+ EXPECT_EQ(0, message.repeated_fixed32_size());
+ EXPECT_EQ(0, message.repeated_fixed64_size());
+ EXPECT_EQ(0, message.repeated_sfixed32_size());
+ EXPECT_EQ(0, message.repeated_sfixed64_size());
+ EXPECT_EQ(0, message.repeated_float_size());
+ EXPECT_EQ(0, message.repeated_double_size());
+ EXPECT_EQ(0, message.repeated_bool_size());
+ EXPECT_EQ(0, message.repeated_string_size());
+ EXPECT_EQ(0, message.repeated_bytes_size());
+
+ EXPECT_EQ(0, message.repeatedgroup_size());
+ EXPECT_EQ(0, message.repeated_nested_message_size());
+ EXPECT_EQ(0, message.repeated_foreign_message_size());
+ EXPECT_EQ(0, message.repeated_import_message_size());
+ EXPECT_EQ(0, message.repeated_lazy_message_size());
+ EXPECT_EQ(0, message.repeated_nested_enum_size());
+ EXPECT_EQ(0, message.repeated_foreign_enum_size());
+ EXPECT_EQ(0, message.repeated_import_enum_size());
+
+ EXPECT_EQ(0, message.repeated_string_piece_size());
+ EXPECT_EQ(0, message.repeated_cord_size());
+
+ // has_blah() should also be false for all default fields.
+ EXPECT_FALSE(message.has_default_int32());
+ EXPECT_FALSE(message.has_default_int64());
+ EXPECT_FALSE(message.has_default_uint32());
+ EXPECT_FALSE(message.has_default_uint64());
+ EXPECT_FALSE(message.has_default_sint32());
+ EXPECT_FALSE(message.has_default_sint64());
+ EXPECT_FALSE(message.has_default_fixed32());
+ EXPECT_FALSE(message.has_default_fixed64());
+ EXPECT_FALSE(message.has_default_sfixed32());
+ EXPECT_FALSE(message.has_default_sfixed64());
+ EXPECT_FALSE(message.has_default_float());
+ EXPECT_FALSE(message.has_default_double());
+ EXPECT_FALSE(message.has_default_bool());
+ EXPECT_FALSE(message.has_default_string());
+ EXPECT_FALSE(message.has_default_bytes());
+
+ EXPECT_FALSE(message.has_default_nested_enum());
+ EXPECT_FALSE(message.has_default_foreign_enum());
+ EXPECT_FALSE(message.has_default_import_enum());
+
+
+ // Fields with defaults have their default values (duh).
+ EXPECT_EQ(41, message.default_int32());
+ EXPECT_EQ(42, message.default_int64());
+ EXPECT_EQ(43, message.default_uint32());
+ EXPECT_EQ(44, message.default_uint64());
+ EXPECT_EQ(-45, message.default_sint32());
+ EXPECT_EQ(46, message.default_sint64());
+ EXPECT_EQ(47, message.default_fixed32());
+ EXPECT_EQ(48, message.default_fixed64());
+ EXPECT_EQ(49, message.default_sfixed32());
+ EXPECT_EQ(-50, message.default_sfixed64());
+ EXPECT_EQ(51.5, message.default_float());
+ EXPECT_EQ(52e3, message.default_double());
+ EXPECT_TRUE(message.default_bool());
+ EXPECT_EQ("hello", message.default_string());
+ EXPECT_EQ("world", message.default_bytes());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message.default_nested_enum());
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.default_foreign_enum());
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, message.default_import_enum());
+
+
+ EXPECT_FALSE(message.has_oneof_uint32());
+ EXPECT_FALSE(message.has_oneof_nested_message());
+ EXPECT_FALSE(message.has_oneof_string());
+ EXPECT_FALSE(message.has_oneof_bytes());
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ExpectRepeatedFieldsModified(
+ const UNITTEST::TestAllTypes& 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_EQ(2, message.repeated_int32_size());
+ ASSERT_EQ(2, message.repeated_int64_size());
+ ASSERT_EQ(2, message.repeated_uint32_size());
+ ASSERT_EQ(2, message.repeated_uint64_size());
+ ASSERT_EQ(2, message.repeated_sint32_size());
+ ASSERT_EQ(2, message.repeated_sint64_size());
+ ASSERT_EQ(2, message.repeated_fixed32_size());
+ ASSERT_EQ(2, message.repeated_fixed64_size());
+ ASSERT_EQ(2, message.repeated_sfixed32_size());
+ ASSERT_EQ(2, message.repeated_sfixed64_size());
+ ASSERT_EQ(2, message.repeated_float_size());
+ ASSERT_EQ(2, message.repeated_double_size());
+ ASSERT_EQ(2, message.repeated_bool_size());
+ ASSERT_EQ(2, message.repeated_string_size());
+ ASSERT_EQ(2, message.repeated_bytes_size());
+
+ ASSERT_EQ(2, message.repeatedgroup_size());
+ ASSERT_EQ(2, message.repeated_nested_message_size());
+ ASSERT_EQ(2, message.repeated_foreign_message_size());
+ ASSERT_EQ(2, message.repeated_import_message_size());
+ ASSERT_EQ(2, message.repeated_lazy_message_size());
+ ASSERT_EQ(2, message.repeated_nested_enum_size());
+ ASSERT_EQ(2, message.repeated_foreign_enum_size());
+ ASSERT_EQ(2, message.repeated_import_enum_size());
+
+#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
+ ASSERT_EQ(2, message.repeated_string_piece_size());
+ ASSERT_EQ(2, message.repeated_cord_size());
+#endif
+
+ EXPECT_EQ(201, message.repeated_int32(0));
+ EXPECT_EQ(202, message.repeated_int64(0));
+ EXPECT_EQ(203, message.repeated_uint32(0));
+ EXPECT_EQ(204, message.repeated_uint64(0));
+ EXPECT_EQ(205, message.repeated_sint32(0));
+ EXPECT_EQ(206, message.repeated_sint64(0));
+ EXPECT_EQ(207, message.repeated_fixed32(0));
+ EXPECT_EQ(208, message.repeated_fixed64(0));
+ EXPECT_EQ(209, message.repeated_sfixed32(0));
+ EXPECT_EQ(210, message.repeated_sfixed64(0));
+ EXPECT_EQ(211, message.repeated_float(0));
+ EXPECT_EQ(212, message.repeated_double(0));
+ EXPECT_TRUE(message.repeated_bool(0));
+ EXPECT_EQ("215", message.repeated_string(0));
+ EXPECT_EQ("216", message.repeated_bytes(0));
+
+ EXPECT_EQ(217, message.repeatedgroup(0).a());
+ EXPECT_EQ(218, message.repeated_nested_message(0).bb());
+ EXPECT_EQ(219, message.repeated_foreign_message(0).c());
+ EXPECT_EQ(220, message.repeated_import_message(0).d());
+ EXPECT_EQ(227, message.repeated_lazy_message(0).bb());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message.repeated_nested_enum(0));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeated_foreign_enum(0));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, message.repeated_import_enum(0));
+
+
+ // Actually verify the second (modified) elements now.
+ EXPECT_EQ(501, message.repeated_int32(1));
+ EXPECT_EQ(502, message.repeated_int64(1));
+ EXPECT_EQ(503, message.repeated_uint32(1));
+ EXPECT_EQ(504, message.repeated_uint64(1));
+ EXPECT_EQ(505, message.repeated_sint32(1));
+ EXPECT_EQ(506, message.repeated_sint64(1));
+ EXPECT_EQ(507, message.repeated_fixed32(1));
+ EXPECT_EQ(508, message.repeated_fixed64(1));
+ EXPECT_EQ(509, message.repeated_sfixed32(1));
+ EXPECT_EQ(510, message.repeated_sfixed64(1));
+ EXPECT_EQ(511, message.repeated_float(1));
+ EXPECT_EQ(512, message.repeated_double(1));
+ EXPECT_TRUE(message.repeated_bool(1));
+ EXPECT_EQ("515", message.repeated_string(1));
+ EXPECT_EQ("516", message.repeated_bytes(1));
+
+ EXPECT_EQ(517, message.repeatedgroup(1).a());
+ EXPECT_EQ(518, message.repeated_nested_message(1).bb());
+ EXPECT_EQ(519, message.repeated_foreign_message(1).c());
+ EXPECT_EQ(520, message.repeated_import_message(1).d());
+ EXPECT_EQ(527, message.repeated_lazy_message(1).bb());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message.repeated_nested_enum(1));
+ EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.repeated_foreign_enum(1));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO, message.repeated_import_enum(1));
+
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::SetPackedFields(UNITTEST::TestPackedTypes* message) {
+ message->add_packed_int32(601);
+ message->add_packed_int64(602);
+ message->add_packed_uint32(603);
+ message->add_packed_uint64(604);
+ message->add_packed_sint32(605);
+ message->add_packed_sint64(606);
+ message->add_packed_fixed32(607);
+ message->add_packed_fixed64(608);
+ message->add_packed_sfixed32(609);
+ message->add_packed_sfixed64(610);
+ message->add_packed_float(611);
+ message->add_packed_double(612);
+ message->add_packed_bool(true);
+ message->add_packed_enum(UNITTEST::FOREIGN_BAR);
+ // add a second one of each field
+ message->add_packed_int32(701);
+ message->add_packed_int64(702);
+ message->add_packed_uint32(703);
+ message->add_packed_uint64(704);
+ message->add_packed_sint32(705);
+ message->add_packed_sint64(706);
+ message->add_packed_fixed32(707);
+ message->add_packed_fixed64(708);
+ message->add_packed_sfixed32(709);
+ message->add_packed_sfixed64(710);
+ message->add_packed_float(711);
+ message->add_packed_double(712);
+ message->add_packed_bool(false);
+ message->add_packed_enum(UNITTEST::FOREIGN_BAZ);
+}
+
+inline void TestUtil::SetUnpackedFields(UNITTEST::TestUnpackedTypes* message) {
+ // The values applied here must match those of SetPackedFields.
+
+ message->add_unpacked_int32(601);
+ message->add_unpacked_int64(602);
+ message->add_unpacked_uint32(603);
+ message->add_unpacked_uint64(604);
+ message->add_unpacked_sint32(605);
+ message->add_unpacked_sint64(606);
+ message->add_unpacked_fixed32(607);
+ message->add_unpacked_fixed64(608);
+ message->add_unpacked_sfixed32(609);
+ message->add_unpacked_sfixed64(610);
+ message->add_unpacked_float(611);
+ message->add_unpacked_double(612);
+ message->add_unpacked_bool(true);
+ message->add_unpacked_enum(UNITTEST::FOREIGN_BAR);
+ // add a second one of each field
+ message->add_unpacked_int32(701);
+ message->add_unpacked_int64(702);
+ message->add_unpacked_uint32(703);
+ message->add_unpacked_uint64(704);
+ message->add_unpacked_sint32(705);
+ message->add_unpacked_sint64(706);
+ message->add_unpacked_fixed32(707);
+ message->add_unpacked_fixed64(708);
+ message->add_unpacked_sfixed32(709);
+ message->add_unpacked_sfixed64(710);
+ message->add_unpacked_float(711);
+ message->add_unpacked_double(712);
+ message->add_unpacked_bool(false);
+ message->add_unpacked_enum(UNITTEST::FOREIGN_BAZ);
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ModifyPackedFields(UNITTEST::TestPackedTypes* message) {
+ message->set_packed_int32(1, 801);
+ message->set_packed_int64(1, 802);
+ message->set_packed_uint32(1, 803);
+ message->set_packed_uint64(1, 804);
+ message->set_packed_sint32(1, 805);
+ message->set_packed_sint64(1, 806);
+ message->set_packed_fixed32(1, 807);
+ message->set_packed_fixed64(1, 808);
+ message->set_packed_sfixed32(1, 809);
+ message->set_packed_sfixed64(1, 810);
+ message->set_packed_float(1, 811);
+ message->set_packed_double(1, 812);
+ message->set_packed_bool(1, true);
+ message->set_packed_enum(1, UNITTEST::FOREIGN_FOO);
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ExpectPackedFieldsSet(
+ const UNITTEST::TestPackedTypes& message) {
+ ASSERT_EQ(2, message.packed_int32_size());
+ ASSERT_EQ(2, message.packed_int64_size());
+ ASSERT_EQ(2, message.packed_uint32_size());
+ ASSERT_EQ(2, message.packed_uint64_size());
+ ASSERT_EQ(2, message.packed_sint32_size());
+ ASSERT_EQ(2, message.packed_sint64_size());
+ ASSERT_EQ(2, message.packed_fixed32_size());
+ ASSERT_EQ(2, message.packed_fixed64_size());
+ ASSERT_EQ(2, message.packed_sfixed32_size());
+ ASSERT_EQ(2, message.packed_sfixed64_size());
+ ASSERT_EQ(2, message.packed_float_size());
+ ASSERT_EQ(2, message.packed_double_size());
+ ASSERT_EQ(2, message.packed_bool_size());
+ ASSERT_EQ(2, message.packed_enum_size());
+
+ EXPECT_EQ(601, message.packed_int32(0));
+ EXPECT_EQ(602, message.packed_int64(0));
+ EXPECT_EQ(603, message.packed_uint32(0));
+ EXPECT_EQ(604, message.packed_uint64(0));
+ EXPECT_EQ(605, message.packed_sint32(0));
+ EXPECT_EQ(606, message.packed_sint64(0));
+ EXPECT_EQ(607, message.packed_fixed32(0));
+ EXPECT_EQ(608, message.packed_fixed64(0));
+ EXPECT_EQ(609, message.packed_sfixed32(0));
+ EXPECT_EQ(610, message.packed_sfixed64(0));
+ EXPECT_EQ(611, message.packed_float(0));
+ EXPECT_EQ(612, message.packed_double(0));
+ EXPECT_TRUE(message.packed_bool(0));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.packed_enum(0));
+
+ EXPECT_EQ(701, message.packed_int32(1));
+ EXPECT_EQ(702, message.packed_int64(1));
+ EXPECT_EQ(703, message.packed_uint32(1));
+ EXPECT_EQ(704, message.packed_uint64(1));
+ EXPECT_EQ(705, message.packed_sint32(1));
+ EXPECT_EQ(706, message.packed_sint64(1));
+ EXPECT_EQ(707, message.packed_fixed32(1));
+ EXPECT_EQ(708, message.packed_fixed64(1));
+ EXPECT_EQ(709, message.packed_sfixed32(1));
+ EXPECT_EQ(710, message.packed_sfixed64(1));
+ EXPECT_EQ(711, message.packed_float(1));
+ EXPECT_EQ(712, message.packed_double(1));
+ EXPECT_FALSE(message.packed_bool(1));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.packed_enum(1));
+}
+
+inline void TestUtil::ExpectUnpackedFieldsSet(
+ const UNITTEST::TestUnpackedTypes& message) {
+ // The values expected here must match those of ExpectPackedFieldsSet.
+
+ ASSERT_EQ(2, message.unpacked_int32_size());
+ ASSERT_EQ(2, message.unpacked_int64_size());
+ ASSERT_EQ(2, message.unpacked_uint32_size());
+ ASSERT_EQ(2, message.unpacked_uint64_size());
+ ASSERT_EQ(2, message.unpacked_sint32_size());
+ ASSERT_EQ(2, message.unpacked_sint64_size());
+ ASSERT_EQ(2, message.unpacked_fixed32_size());
+ ASSERT_EQ(2, message.unpacked_fixed64_size());
+ ASSERT_EQ(2, message.unpacked_sfixed32_size());
+ ASSERT_EQ(2, message.unpacked_sfixed64_size());
+ ASSERT_EQ(2, message.unpacked_float_size());
+ ASSERT_EQ(2, message.unpacked_double_size());
+ ASSERT_EQ(2, message.unpacked_bool_size());
+ ASSERT_EQ(2, message.unpacked_enum_size());
+
+ EXPECT_EQ(601, message.unpacked_int32(0));
+ EXPECT_EQ(602, message.unpacked_int64(0));
+ EXPECT_EQ(603, message.unpacked_uint32(0));
+ EXPECT_EQ(604, message.unpacked_uint64(0));
+ EXPECT_EQ(605, message.unpacked_sint32(0));
+ EXPECT_EQ(606, message.unpacked_sint64(0));
+ EXPECT_EQ(607, message.unpacked_fixed32(0));
+ EXPECT_EQ(608, message.unpacked_fixed64(0));
+ EXPECT_EQ(609, message.unpacked_sfixed32(0));
+ EXPECT_EQ(610, message.unpacked_sfixed64(0));
+ EXPECT_EQ(611, message.unpacked_float(0));
+ EXPECT_EQ(612, message.unpacked_double(0));
+ EXPECT_TRUE(message.unpacked_bool(0));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.unpacked_enum(0));
+
+ EXPECT_EQ(701, message.unpacked_int32(1));
+ EXPECT_EQ(702, message.unpacked_int64(1));
+ EXPECT_EQ(703, message.unpacked_uint32(1));
+ EXPECT_EQ(704, message.unpacked_uint64(1));
+ EXPECT_EQ(705, message.unpacked_sint32(1));
+ EXPECT_EQ(706, message.unpacked_sint64(1));
+ EXPECT_EQ(707, message.unpacked_fixed32(1));
+ EXPECT_EQ(708, message.unpacked_fixed64(1));
+ EXPECT_EQ(709, message.unpacked_sfixed32(1));
+ EXPECT_EQ(710, message.unpacked_sfixed64(1));
+ EXPECT_EQ(711, message.unpacked_float(1));
+ EXPECT_EQ(712, message.unpacked_double(1));
+ EXPECT_FALSE(message.unpacked_bool(1));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.unpacked_enum(1));
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ExpectPackedClear(
+ const UNITTEST::TestPackedTypes& message) {
+ // Packed repeated fields are empty.
+ EXPECT_EQ(0, message.packed_int32_size());
+ EXPECT_EQ(0, message.packed_int64_size());
+ EXPECT_EQ(0, message.packed_uint32_size());
+ EXPECT_EQ(0, message.packed_uint64_size());
+ EXPECT_EQ(0, message.packed_sint32_size());
+ EXPECT_EQ(0, message.packed_sint64_size());
+ EXPECT_EQ(0, message.packed_fixed32_size());
+ EXPECT_EQ(0, message.packed_fixed64_size());
+ EXPECT_EQ(0, message.packed_sfixed32_size());
+ EXPECT_EQ(0, message.packed_sfixed64_size());
+ EXPECT_EQ(0, message.packed_float_size());
+ EXPECT_EQ(0, message.packed_double_size());
+ EXPECT_EQ(0, message.packed_bool_size());
+ EXPECT_EQ(0, message.packed_enum_size());
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ExpectPackedFieldsModified(
+ const UNITTEST::TestPackedTypes& message) {
+ // Do the same for packed repeated fields.
+ ASSERT_EQ(2, message.packed_int32_size());
+ ASSERT_EQ(2, message.packed_int64_size());
+ ASSERT_EQ(2, message.packed_uint32_size());
+ ASSERT_EQ(2, message.packed_uint64_size());
+ ASSERT_EQ(2, message.packed_sint32_size());
+ ASSERT_EQ(2, message.packed_sint64_size());
+ ASSERT_EQ(2, message.packed_fixed32_size());
+ ASSERT_EQ(2, message.packed_fixed64_size());
+ ASSERT_EQ(2, message.packed_sfixed32_size());
+ ASSERT_EQ(2, message.packed_sfixed64_size());
+ ASSERT_EQ(2, message.packed_float_size());
+ ASSERT_EQ(2, message.packed_double_size());
+ ASSERT_EQ(2, message.packed_bool_size());
+ ASSERT_EQ(2, message.packed_enum_size());
+
+ EXPECT_EQ(601, message.packed_int32(0));
+ EXPECT_EQ(602, message.packed_int64(0));
+ EXPECT_EQ(603, message.packed_uint32(0));
+ EXPECT_EQ(604, message.packed_uint64(0));
+ EXPECT_EQ(605, message.packed_sint32(0));
+ EXPECT_EQ(606, message.packed_sint64(0));
+ EXPECT_EQ(607, message.packed_fixed32(0));
+ EXPECT_EQ(608, message.packed_fixed64(0));
+ EXPECT_EQ(609, message.packed_sfixed32(0));
+ EXPECT_EQ(610, message.packed_sfixed64(0));
+ EXPECT_EQ(611, message.packed_float(0));
+ EXPECT_EQ(612, message.packed_double(0));
+ EXPECT_TRUE(message.packed_bool(0));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.packed_enum(0));
+ // Actually verify the second (modified) elements now.
+ EXPECT_EQ(801, message.packed_int32(1));
+ EXPECT_EQ(802, message.packed_int64(1));
+ EXPECT_EQ(803, message.packed_uint32(1));
+ EXPECT_EQ(804, message.packed_uint64(1));
+ EXPECT_EQ(805, message.packed_sint32(1));
+ EXPECT_EQ(806, message.packed_sint64(1));
+ EXPECT_EQ(807, message.packed_fixed32(1));
+ EXPECT_EQ(808, message.packed_fixed64(1));
+ EXPECT_EQ(809, message.packed_sfixed32(1));
+ EXPECT_EQ(810, message.packed_sfixed64(1));
+ EXPECT_EQ(811, message.packed_float(1));
+ EXPECT_EQ(812, message.packed_double(1));
+ EXPECT_TRUE(message.packed_bool(1));
+ EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.packed_enum(1));
+}
+
+// ===================================================================
+// Extensions
+//
+// All this code is exactly equivalent to the above code except that it's
+// manipulating extension fields instead of normal ones.
+
+inline void TestUtil::SetAllExtensions(UNITTEST::TestAllExtensions* message) {
+ message->SetExtension(UNITTEST::optional_int32_extension, 101);
+ message->SetExtension(UNITTEST::optional_int64_extension, 102);
+ message->SetExtension(UNITTEST::optional_uint32_extension, 103);
+ message->SetExtension(UNITTEST::optional_uint64_extension, 104);
+ message->SetExtension(UNITTEST::optional_sint32_extension, 105);
+ message->SetExtension(UNITTEST::optional_sint64_extension, 106);
+ message->SetExtension(UNITTEST::optional_fixed32_extension, 107);
+ message->SetExtension(UNITTEST::optional_fixed64_extension, 108);
+ message->SetExtension(UNITTEST::optional_sfixed32_extension, 109);
+ message->SetExtension(UNITTEST::optional_sfixed64_extension, 110);
+ message->SetExtension(UNITTEST::optional_float_extension, 111);
+ message->SetExtension(UNITTEST::optional_double_extension, 112);
+ message->SetExtension(UNITTEST::optional_bool_extension, true);
+ message->SetExtension(UNITTEST::optional_string_extension, "115");
+ message->SetExtension(UNITTEST::optional_bytes_extension, "116");
+
+ message->MutableExtension(UNITTEST::optionalgroup_extension)->set_a(117);
+ message->MutableExtension(UNITTEST::optional_nested_message_extension)
+ ->set_bb(118);
+ message->MutableExtension(UNITTEST::optional_foreign_message_extension)
+ ->set_c(119);
+ message->MutableExtension(UNITTEST::optional_import_message_extension)
+ ->set_d(120);
+
+ message->SetExtension(UNITTEST::optional_nested_enum_extension,
+ UNITTEST::TestAllTypes::BAZ);
+ message->SetExtension(UNITTEST::optional_foreign_enum_extension,
+ UNITTEST::FOREIGN_BAZ);
+ message->SetExtension(UNITTEST::optional_import_enum_extension,
+ UNITTEST_IMPORT::IMPORT_BAZ);
+
+ message->SetExtension(UNITTEST::optional_string_piece_extension, "124");
+ message->SetExtension(UNITTEST::optional_cord_extension, "125");
+
+ message->MutableExtension(UNITTEST::optional_public_import_message_extension)
+ ->set_e(126);
+ message->MutableExtension(UNITTEST::optional_lazy_message_extension)
+ ->set_bb(127);
+
+ // -----------------------------------------------------------------
+
+ message->AddExtension(UNITTEST::repeated_int32_extension, 201);
+ message->AddExtension(UNITTEST::repeated_int64_extension, 202);
+ message->AddExtension(UNITTEST::repeated_uint32_extension, 203);
+ message->AddExtension(UNITTEST::repeated_uint64_extension, 204);
+ message->AddExtension(UNITTEST::repeated_sint32_extension, 205);
+ message->AddExtension(UNITTEST::repeated_sint64_extension, 206);
+ message->AddExtension(UNITTEST::repeated_fixed32_extension, 207);
+ message->AddExtension(UNITTEST::repeated_fixed64_extension, 208);
+ message->AddExtension(UNITTEST::repeated_sfixed32_extension, 209);
+ message->AddExtension(UNITTEST::repeated_sfixed64_extension, 210);
+ message->AddExtension(UNITTEST::repeated_float_extension, 211);
+ message->AddExtension(UNITTEST::repeated_double_extension, 212);
+ message->AddExtension(UNITTEST::repeated_bool_extension, true);
+ message->AddExtension(UNITTEST::repeated_string_extension, "215");
+ message->AddExtension(UNITTEST::repeated_bytes_extension, "216");
+
+ message->AddExtension(UNITTEST::repeatedgroup_extension)->set_a(217);
+ message->AddExtension(UNITTEST::repeated_nested_message_extension)
+ ->set_bb(218);
+ message->AddExtension(UNITTEST::repeated_foreign_message_extension)
+ ->set_c(219);
+ message->AddExtension(UNITTEST::repeated_import_message_extension)
+ ->set_d(220);
+ message->AddExtension(UNITTEST::repeated_lazy_message_extension)->set_bb(227);
+
+ message->AddExtension(UNITTEST::repeated_nested_enum_extension,
+ UNITTEST::TestAllTypes::BAR);
+ message->AddExtension(UNITTEST::repeated_foreign_enum_extension,
+ UNITTEST::FOREIGN_BAR);
+ message->AddExtension(UNITTEST::repeated_import_enum_extension,
+ UNITTEST_IMPORT::IMPORT_BAR);
+
+ message->AddExtension(UNITTEST::repeated_string_piece_extension, "224");
+ message->AddExtension(UNITTEST::repeated_cord_extension, "225");
+
+ // Add a second one of each field.
+ message->AddExtension(UNITTEST::repeated_int32_extension, 301);
+ message->AddExtension(UNITTEST::repeated_int64_extension, 302);
+ message->AddExtension(UNITTEST::repeated_uint32_extension, 303);
+ message->AddExtension(UNITTEST::repeated_uint64_extension, 304);
+ message->AddExtension(UNITTEST::repeated_sint32_extension, 305);
+ message->AddExtension(UNITTEST::repeated_sint64_extension, 306);
+ message->AddExtension(UNITTEST::repeated_fixed32_extension, 307);
+ message->AddExtension(UNITTEST::repeated_fixed64_extension, 308);
+ message->AddExtension(UNITTEST::repeated_sfixed32_extension, 309);
+ message->AddExtension(UNITTEST::repeated_sfixed64_extension, 310);
+ message->AddExtension(UNITTEST::repeated_float_extension, 311);
+ message->AddExtension(UNITTEST::repeated_double_extension, 312);
+ message->AddExtension(UNITTEST::repeated_bool_extension, false);
+ message->AddExtension(UNITTEST::repeated_string_extension, "315");
+ message->AddExtension(UNITTEST::repeated_bytes_extension, "316");
+
+ message->AddExtension(UNITTEST::repeatedgroup_extension)->set_a(317);
+ message->AddExtension(UNITTEST::repeated_nested_message_extension)
+ ->set_bb(318);
+ message->AddExtension(UNITTEST::repeated_foreign_message_extension)
+ ->set_c(319);
+ message->AddExtension(UNITTEST::repeated_import_message_extension)
+ ->set_d(320);
+ message->AddExtension(UNITTEST::repeated_lazy_message_extension)->set_bb(327);
+
+ message->AddExtension(UNITTEST::repeated_nested_enum_extension,
+ UNITTEST::TestAllTypes::BAZ);
+ message->AddExtension(UNITTEST::repeated_foreign_enum_extension,
+ UNITTEST::FOREIGN_BAZ);
+ message->AddExtension(UNITTEST::repeated_import_enum_extension,
+ UNITTEST_IMPORT::IMPORT_BAZ);
+
+ message->AddExtension(UNITTEST::repeated_string_piece_extension, "324");
+ message->AddExtension(UNITTEST::repeated_cord_extension, "325");
+
+ // -----------------------------------------------------------------
+
+ message->SetExtension(UNITTEST::default_int32_extension, 401);
+ message->SetExtension(UNITTEST::default_int64_extension, 402);
+ message->SetExtension(UNITTEST::default_uint32_extension, 403);
+ message->SetExtension(UNITTEST::default_uint64_extension, 404);
+ message->SetExtension(UNITTEST::default_sint32_extension, 405);
+ message->SetExtension(UNITTEST::default_sint64_extension, 406);
+ message->SetExtension(UNITTEST::default_fixed32_extension, 407);
+ message->SetExtension(UNITTEST::default_fixed64_extension, 408);
+ message->SetExtension(UNITTEST::default_sfixed32_extension, 409);
+ message->SetExtension(UNITTEST::default_sfixed64_extension, 410);
+ message->SetExtension(UNITTEST::default_float_extension, 411);
+ message->SetExtension(UNITTEST::default_double_extension, 412);
+ message->SetExtension(UNITTEST::default_bool_extension, false);
+ message->SetExtension(UNITTEST::default_string_extension, "415");
+ message->SetExtension(UNITTEST::default_bytes_extension, "416");
+
+ message->SetExtension(UNITTEST::default_nested_enum_extension,
+ UNITTEST::TestAllTypes::FOO);
+ message->SetExtension(UNITTEST::default_foreign_enum_extension,
+ UNITTEST::FOREIGN_FOO);
+ message->SetExtension(UNITTEST::default_import_enum_extension,
+ UNITTEST_IMPORT::IMPORT_FOO);
+
+ message->SetExtension(UNITTEST::default_string_piece_extension, "424");
+ message->SetExtension(UNITTEST::default_cord_extension, "425");
+
+ SetOneofFields(message);
+}
+
+inline void TestUtil::SetOneofFields(UNITTEST::TestAllExtensions* message) {
+ message->SetExtension(UNITTEST::oneof_uint32_extension, 601);
+ message->MutableExtension(UNITTEST::oneof_nested_message_extension)
+ ->set_bb(602);
+ message->SetExtension(UNITTEST::oneof_string_extension, "603");
+ message->SetExtension(UNITTEST::oneof_bytes_extension, "604");
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::SetAllFieldsAndExtensions(
+ UNITTEST::TestFieldOrderings* message) {
+ GOOGLE_CHECK(message);
+ message->set_my_int(1);
+ message->set_my_string("foo");
+ message->set_my_float(1.0);
+ message->SetExtension(UNITTEST::my_extension_int, 23);
+ message->SetExtension(UNITTEST::my_extension_string, "bar");
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ModifyRepeatedExtensions(
+ UNITTEST::TestAllExtensions* message) {
+ message->SetExtension(UNITTEST::repeated_int32_extension, 1, 501);
+ message->SetExtension(UNITTEST::repeated_int64_extension, 1, 502);
+ message->SetExtension(UNITTEST::repeated_uint32_extension, 1, 503);
+ message->SetExtension(UNITTEST::repeated_uint64_extension, 1, 504);
+ message->SetExtension(UNITTEST::repeated_sint32_extension, 1, 505);
+ message->SetExtension(UNITTEST::repeated_sint64_extension, 1, 506);
+ message->SetExtension(UNITTEST::repeated_fixed32_extension, 1, 507);
+ message->SetExtension(UNITTEST::repeated_fixed64_extension, 1, 508);
+ message->SetExtension(UNITTEST::repeated_sfixed32_extension, 1, 509);
+ message->SetExtension(UNITTEST::repeated_sfixed64_extension, 1, 510);
+ message->SetExtension(UNITTEST::repeated_float_extension, 1, 511);
+ message->SetExtension(UNITTEST::repeated_double_extension, 1, 512);
+ message->SetExtension(UNITTEST::repeated_bool_extension, 1, true);
+ message->SetExtension(UNITTEST::repeated_string_extension, 1, "515");
+ message->SetExtension(UNITTEST::repeated_bytes_extension, 1, "516");
+
+ message->MutableExtension(UNITTEST::repeatedgroup_extension, 1)->set_a(517);
+ message->MutableExtension(UNITTEST::repeated_nested_message_extension, 1)
+ ->set_bb(518);
+ message->MutableExtension(UNITTEST::repeated_foreign_message_extension, 1)
+ ->set_c(519);
+ message->MutableExtension(UNITTEST::repeated_import_message_extension, 1)
+ ->set_d(520);
+ message->MutableExtension(UNITTEST::repeated_lazy_message_extension, 1)
+ ->set_bb(527);
+
+ message->SetExtension(UNITTEST::repeated_nested_enum_extension, 1,
+ UNITTEST::TestAllTypes::FOO);
+ message->SetExtension(UNITTEST::repeated_foreign_enum_extension, 1,
+ UNITTEST::FOREIGN_FOO);
+ message->SetExtension(UNITTEST::repeated_import_enum_extension, 1,
+ UNITTEST_IMPORT::IMPORT_FOO);
+
+ message->SetExtension(UNITTEST::repeated_string_piece_extension, 1, "524");
+ message->SetExtension(UNITTEST::repeated_cord_extension, 1, "525");
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ExpectAllExtensionsSet(
+ const UNITTEST::TestAllExtensions& message) {
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_int32_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_int64_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_uint32_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_uint64_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_sint32_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_sint64_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_fixed32_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_fixed64_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_sfixed32_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_sfixed64_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_float_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_double_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_bool_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_string_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_bytes_extension));
+
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optionalgroup_extension));
+ EXPECT_TRUE(
+ message.HasExtension(UNITTEST::optional_nested_message_extension));
+ EXPECT_TRUE(
+ message.HasExtension(UNITTEST::optional_foreign_message_extension));
+ EXPECT_TRUE(
+ message.HasExtension(UNITTEST::optional_import_message_extension));
+ EXPECT_TRUE(
+ message.HasExtension(UNITTEST::optional_public_import_message_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_lazy_message_extension));
+
+ EXPECT_TRUE(message.GetExtension(UNITTEST::optionalgroup_extension).has_a());
+ EXPECT_TRUE(message.GetExtension(UNITTEST::optional_nested_message_extension)
+ .has_bb());
+ EXPECT_TRUE(message.GetExtension(UNITTEST::optional_foreign_message_extension)
+ .has_c());
+ EXPECT_TRUE(message.GetExtension(UNITTEST::optional_import_message_extension)
+ .has_d());
+ EXPECT_TRUE(
+ message.GetExtension(UNITTEST::optional_public_import_message_extension)
+ .has_e());
+ EXPECT_TRUE(
+ message.GetExtension(UNITTEST::optional_lazy_message_extension).has_bb());
+
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_nested_enum_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_foreign_enum_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_import_enum_extension));
+
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_string_piece_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::optional_cord_extension));
+
+ EXPECT_EQ(101, message.GetExtension(UNITTEST::optional_int32_extension));
+ EXPECT_EQ(102, message.GetExtension(UNITTEST::optional_int64_extension));
+ EXPECT_EQ(103, message.GetExtension(UNITTEST::optional_uint32_extension));
+ EXPECT_EQ(104, message.GetExtension(UNITTEST::optional_uint64_extension));
+ EXPECT_EQ(105, message.GetExtension(UNITTEST::optional_sint32_extension));
+ EXPECT_EQ(106, message.GetExtension(UNITTEST::optional_sint64_extension));
+ EXPECT_EQ(107, message.GetExtension(UNITTEST::optional_fixed32_extension));
+ EXPECT_EQ(108, message.GetExtension(UNITTEST::optional_fixed64_extension));
+ EXPECT_EQ(109, message.GetExtension(UNITTEST::optional_sfixed32_extension));
+ EXPECT_EQ(110, message.GetExtension(UNITTEST::optional_sfixed64_extension));
+ EXPECT_EQ(111, message.GetExtension(UNITTEST::optional_float_extension));
+ EXPECT_EQ(112, message.GetExtension(UNITTEST::optional_double_extension));
+ EXPECT_TRUE(message.GetExtension(UNITTEST::optional_bool_extension));
+ EXPECT_EQ("115", message.GetExtension(UNITTEST::optional_string_extension));
+ EXPECT_EQ("116", message.GetExtension(UNITTEST::optional_bytes_extension));
+
+ EXPECT_EQ(117, message.GetExtension(UNITTEST::optionalgroup_extension).a());
+ EXPECT_EQ(
+ 118,
+ message.GetExtension(UNITTEST::optional_nested_message_extension).bb());
+ EXPECT_EQ(
+ 119,
+ message.GetExtension(UNITTEST::optional_foreign_message_extension).c());
+ EXPECT_EQ(
+ 120,
+ message.GetExtension(UNITTEST::optional_import_message_extension).d());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAZ,
+ message.GetExtension(UNITTEST::optional_nested_enum_extension));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAZ,
+ message.GetExtension(UNITTEST::optional_foreign_enum_extension));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ,
+ message.GetExtension(UNITTEST::optional_import_enum_extension));
+
+ EXPECT_EQ("124",
+ message.GetExtension(UNITTEST::optional_string_piece_extension));
+ EXPECT_EQ("125", message.GetExtension(UNITTEST::optional_cord_extension));
+ EXPECT_EQ(
+ 126,
+ message.GetExtension(UNITTEST::optional_public_import_message_extension)
+ .e());
+ EXPECT_EQ(
+ 127,
+ message.GetExtension(UNITTEST::optional_lazy_message_extension).bb());
+
+ // -----------------------------------------------------------------
+
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_float_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_double_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bool_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_string_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bytes_extension));
+
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeatedgroup_extension));
+ ASSERT_EQ(2,
+ message.ExtensionSize(UNITTEST::repeated_nested_message_extension));
+ ASSERT_EQ(
+ 2, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension));
+ ASSERT_EQ(2,
+ message.ExtensionSize(UNITTEST::repeated_import_message_extension));
+ ASSERT_EQ(2,
+ message.ExtensionSize(UNITTEST::repeated_lazy_message_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_nested_enum_extension));
+ ASSERT_EQ(2,
+ message.ExtensionSize(UNITTEST::repeated_foreign_enum_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_import_enum_extension));
+
+ ASSERT_EQ(2,
+ message.ExtensionSize(UNITTEST::repeated_string_piece_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_cord_extension));
+
+ EXPECT_EQ(201, message.GetExtension(UNITTEST::repeated_int32_extension, 0));
+ EXPECT_EQ(202, message.GetExtension(UNITTEST::repeated_int64_extension, 0));
+ EXPECT_EQ(203, message.GetExtension(UNITTEST::repeated_uint32_extension, 0));
+ EXPECT_EQ(204, message.GetExtension(UNITTEST::repeated_uint64_extension, 0));
+ EXPECT_EQ(205, message.GetExtension(UNITTEST::repeated_sint32_extension, 0));
+ EXPECT_EQ(206, message.GetExtension(UNITTEST::repeated_sint64_extension, 0));
+ EXPECT_EQ(207, message.GetExtension(UNITTEST::repeated_fixed32_extension, 0));
+ EXPECT_EQ(208, message.GetExtension(UNITTEST::repeated_fixed64_extension, 0));
+ EXPECT_EQ(209,
+ message.GetExtension(UNITTEST::repeated_sfixed32_extension, 0));
+ EXPECT_EQ(210,
+ message.GetExtension(UNITTEST::repeated_sfixed64_extension, 0));
+ EXPECT_EQ(211, message.GetExtension(UNITTEST::repeated_float_extension, 0));
+ EXPECT_EQ(212, message.GetExtension(UNITTEST::repeated_double_extension, 0));
+ EXPECT_TRUE(message.GetExtension(UNITTEST::repeated_bool_extension, 0));
+ EXPECT_EQ("215",
+ message.GetExtension(UNITTEST::repeated_string_extension, 0));
+ EXPECT_EQ("216", message.GetExtension(UNITTEST::repeated_bytes_extension, 0));
+
+ EXPECT_EQ(217,
+ message.GetExtension(UNITTEST::repeatedgroup_extension, 0).a());
+ EXPECT_EQ(218,
+ message.GetExtension(UNITTEST::repeated_nested_message_extension, 0)
+ .bb());
+ EXPECT_EQ(
+ 219, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 0)
+ .c());
+ EXPECT_EQ(
+ 220,
+ message.GetExtension(UNITTEST::repeated_import_message_extension, 0).d());
+ EXPECT_EQ(
+ 227,
+ message.GetExtension(UNITTEST::repeated_lazy_message_extension, 0).bb());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAR,
+ message.GetExtension(UNITTEST::repeated_nested_enum_extension, 0));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR,
+ message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 0));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR,
+ message.GetExtension(UNITTEST::repeated_import_enum_extension, 0));
+
+ EXPECT_EQ("224",
+ message.GetExtension(UNITTEST::repeated_string_piece_extension, 0));
+ EXPECT_EQ("225", message.GetExtension(UNITTEST::repeated_cord_extension, 0));
+
+ EXPECT_EQ(301, message.GetExtension(UNITTEST::repeated_int32_extension, 1));
+ EXPECT_EQ(302, message.GetExtension(UNITTEST::repeated_int64_extension, 1));
+ EXPECT_EQ(303, message.GetExtension(UNITTEST::repeated_uint32_extension, 1));
+ EXPECT_EQ(304, message.GetExtension(UNITTEST::repeated_uint64_extension, 1));
+ EXPECT_EQ(305, message.GetExtension(UNITTEST::repeated_sint32_extension, 1));
+ EXPECT_EQ(306, message.GetExtension(UNITTEST::repeated_sint64_extension, 1));
+ EXPECT_EQ(307, message.GetExtension(UNITTEST::repeated_fixed32_extension, 1));
+ EXPECT_EQ(308, message.GetExtension(UNITTEST::repeated_fixed64_extension, 1));
+ EXPECT_EQ(309,
+ message.GetExtension(UNITTEST::repeated_sfixed32_extension, 1));
+ EXPECT_EQ(310,
+ message.GetExtension(UNITTEST::repeated_sfixed64_extension, 1));
+ EXPECT_EQ(311, message.GetExtension(UNITTEST::repeated_float_extension, 1));
+ EXPECT_EQ(312, message.GetExtension(UNITTEST::repeated_double_extension, 1));
+ EXPECT_FALSE(message.GetExtension(UNITTEST::repeated_bool_extension, 1));
+ EXPECT_EQ("315",
+ message.GetExtension(UNITTEST::repeated_string_extension, 1));
+ EXPECT_EQ("316", message.GetExtension(UNITTEST::repeated_bytes_extension, 1));
+
+ EXPECT_EQ(317,
+ message.GetExtension(UNITTEST::repeatedgroup_extension, 1).a());
+ EXPECT_EQ(318,
+ message.GetExtension(UNITTEST::repeated_nested_message_extension, 1)
+ .bb());
+ EXPECT_EQ(
+ 319, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 1)
+ .c());
+ EXPECT_EQ(
+ 320,
+ message.GetExtension(UNITTEST::repeated_import_message_extension, 1).d());
+ EXPECT_EQ(
+ 327,
+ message.GetExtension(UNITTEST::repeated_lazy_message_extension, 1).bb());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAZ,
+ message.GetExtension(UNITTEST::repeated_nested_enum_extension, 1));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAZ,
+ message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 1));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ,
+ message.GetExtension(UNITTEST::repeated_import_enum_extension, 1));
+
+ EXPECT_EQ("324",
+ message.GetExtension(UNITTEST::repeated_string_piece_extension, 1));
+ EXPECT_EQ("325", message.GetExtension(UNITTEST::repeated_cord_extension, 1));
+
+ // -----------------------------------------------------------------
+
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_int32_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_int64_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_uint32_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_uint64_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_sint32_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_sint64_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_fixed32_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_fixed64_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_sfixed32_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_sfixed64_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_float_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_double_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_bool_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_string_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_bytes_extension));
+
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_nested_enum_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_foreign_enum_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_import_enum_extension));
+
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_string_piece_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::default_cord_extension));
+
+ EXPECT_EQ(401, message.GetExtension(UNITTEST::default_int32_extension));
+ EXPECT_EQ(402, message.GetExtension(UNITTEST::default_int64_extension));
+ EXPECT_EQ(403, message.GetExtension(UNITTEST::default_uint32_extension));
+ EXPECT_EQ(404, message.GetExtension(UNITTEST::default_uint64_extension));
+ EXPECT_EQ(405, message.GetExtension(UNITTEST::default_sint32_extension));
+ EXPECT_EQ(406, message.GetExtension(UNITTEST::default_sint64_extension));
+ EXPECT_EQ(407, message.GetExtension(UNITTEST::default_fixed32_extension));
+ EXPECT_EQ(408, message.GetExtension(UNITTEST::default_fixed64_extension));
+ EXPECT_EQ(409, message.GetExtension(UNITTEST::default_sfixed32_extension));
+ EXPECT_EQ(410, message.GetExtension(UNITTEST::default_sfixed64_extension));
+ EXPECT_EQ(411, message.GetExtension(UNITTEST::default_float_extension));
+ EXPECT_EQ(412, message.GetExtension(UNITTEST::default_double_extension));
+ EXPECT_FALSE(message.GetExtension(UNITTEST::default_bool_extension));
+ EXPECT_EQ("415", message.GetExtension(UNITTEST::default_string_extension));
+ EXPECT_EQ("416", message.GetExtension(UNITTEST::default_bytes_extension));
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::FOO,
+ message.GetExtension(UNITTEST::default_nested_enum_extension));
+ EXPECT_EQ(UNITTEST::FOREIGN_FOO,
+ message.GetExtension(UNITTEST::default_foreign_enum_extension));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO,
+ message.GetExtension(UNITTEST::default_import_enum_extension));
+
+ EXPECT_EQ("424",
+ message.GetExtension(UNITTEST::default_string_piece_extension));
+ EXPECT_EQ("425", message.GetExtension(UNITTEST::default_cord_extension));
+
+ EXPECT_TRUE(message.HasExtension(UNITTEST::oneof_uint32_extension));
+ EXPECT_TRUE(
+ message.GetExtension(UNITTEST::oneof_nested_message_extension).has_bb());
+ EXPECT_TRUE(message.HasExtension(UNITTEST::oneof_string_extension));
+ EXPECT_TRUE(message.HasExtension(UNITTEST::oneof_bytes_extension));
+
+ EXPECT_EQ(601, message.GetExtension(UNITTEST::oneof_uint32_extension));
+ EXPECT_EQ(
+ 602, message.GetExtension(UNITTEST::oneof_nested_message_extension).bb());
+ EXPECT_EQ("603", message.GetExtension(UNITTEST::oneof_string_extension));
+ EXPECT_EQ("604", message.GetExtension(UNITTEST::oneof_bytes_extension));
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ExpectExtensionsClear(
+ const UNITTEST::TestAllExtensions& message) {
+ string serialized;
+ ASSERT_TRUE(message.SerializeToString(&serialized));
+ EXPECT_EQ("", serialized);
+ EXPECT_EQ(0, message.ByteSizeLong());
+
+ // has_blah() should initially be false for all optional fields.
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_int32_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_int64_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_uint32_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_uint64_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_sint32_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_sint64_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_fixed32_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_fixed64_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_sfixed32_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_sfixed64_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_float_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_double_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_bool_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_string_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_bytes_extension));
+
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optionalgroup_extension));
+ EXPECT_FALSE(
+ message.HasExtension(UNITTEST::optional_nested_message_extension));
+ EXPECT_FALSE(
+ message.HasExtension(UNITTEST::optional_foreign_message_extension));
+ EXPECT_FALSE(
+ message.HasExtension(UNITTEST::optional_import_message_extension));
+ EXPECT_FALSE(
+ message.HasExtension(UNITTEST::optional_public_import_message_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_lazy_message_extension));
+
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_nested_enum_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_foreign_enum_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_import_enum_extension));
+
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_string_piece_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::optional_cord_extension));
+
+ // Optional fields without defaults are set to zero or something like it.
+ EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_int32_extension));
+ EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_int64_extension));
+ EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_uint32_extension));
+ EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_uint64_extension));
+ EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_sint32_extension));
+ EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_sint64_extension));
+ EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_fixed32_extension));
+ EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_fixed64_extension));
+ EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_sfixed32_extension));
+ EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_sfixed64_extension));
+ EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_float_extension));
+ EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_double_extension));
+ EXPECT_FALSE(message.GetExtension(UNITTEST::optional_bool_extension));
+ EXPECT_EQ("", message.GetExtension(UNITTEST::optional_string_extension));
+ EXPECT_EQ("", message.GetExtension(UNITTEST::optional_bytes_extension));
+
+ // Embedded messages should also be clear.
+ EXPECT_FALSE(message.GetExtension(UNITTEST::optionalgroup_extension).has_a());
+ EXPECT_FALSE(message.GetExtension(UNITTEST::optional_nested_message_extension)
+ .has_bb());
+ EXPECT_FALSE(
+ message.GetExtension(UNITTEST::optional_foreign_message_extension)
+ .has_c());
+ EXPECT_FALSE(message.GetExtension(UNITTEST::optional_import_message_extension)
+ .has_d());
+ EXPECT_FALSE(
+ message.GetExtension(UNITTEST::optional_public_import_message_extension)
+ .has_e());
+ EXPECT_FALSE(
+ message.GetExtension(UNITTEST::optional_lazy_message_extension).has_bb());
+
+ EXPECT_EQ(0, message.GetExtension(UNITTEST::optionalgroup_extension).a());
+ EXPECT_EQ(
+ 0,
+ message.GetExtension(UNITTEST::optional_nested_message_extension).bb());
+ EXPECT_EQ(
+ 0,
+ message.GetExtension(UNITTEST::optional_foreign_message_extension).c());
+ EXPECT_EQ(
+ 0, message.GetExtension(UNITTEST::optional_import_message_extension).d());
+ EXPECT_EQ(
+ 0,
+ message.GetExtension(UNITTEST::optional_public_import_message_extension)
+ .e());
+ EXPECT_EQ(
+ 0, message.GetExtension(UNITTEST::optional_lazy_message_extension).bb());
+
+ // Enums without defaults are set to the first value in the enum.
+ EXPECT_EQ(UNITTEST::TestAllTypes::FOO,
+ message.GetExtension(UNITTEST::optional_nested_enum_extension));
+ EXPECT_EQ(UNITTEST::FOREIGN_FOO,
+ message.GetExtension(UNITTEST::optional_foreign_enum_extension));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO,
+ message.GetExtension(UNITTEST::optional_import_enum_extension));
+
+ EXPECT_EQ("",
+ message.GetExtension(UNITTEST::optional_string_piece_extension));
+ EXPECT_EQ("", message.GetExtension(UNITTEST::optional_cord_extension));
+
+ // Repeated fields are empty.
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_int32_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_int64_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_uint32_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_uint64_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_sint32_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_sint64_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_fixed32_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_fixed64_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_sfixed32_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_sfixed64_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_float_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_double_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_bool_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_string_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_bytes_extension));
+
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeatedgroup_extension));
+ EXPECT_EQ(0,
+ message.ExtensionSize(UNITTEST::repeated_nested_message_extension));
+ EXPECT_EQ(
+ 0, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension));
+ EXPECT_EQ(0,
+ message.ExtensionSize(UNITTEST::repeated_import_message_extension));
+ EXPECT_EQ(0,
+ message.ExtensionSize(UNITTEST::repeated_lazy_message_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_nested_enum_extension));
+ EXPECT_EQ(0,
+ message.ExtensionSize(UNITTEST::repeated_foreign_enum_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_import_enum_extension));
+
+ EXPECT_EQ(0,
+ message.ExtensionSize(UNITTEST::repeated_string_piece_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_cord_extension));
+
+ // has_blah() should also be false for all default fields.
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_int32_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_int64_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_uint32_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_uint64_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_sint32_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_sint64_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_fixed32_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_fixed64_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_sfixed32_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_sfixed64_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_float_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_double_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_bool_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_string_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_bytes_extension));
+
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_nested_enum_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_foreign_enum_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_import_enum_extension));
+
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_string_piece_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::default_cord_extension));
+
+ // Fields with defaults have their default values (duh).
+ EXPECT_EQ(41, message.GetExtension(UNITTEST::default_int32_extension));
+ EXPECT_EQ(42, message.GetExtension(UNITTEST::default_int64_extension));
+ EXPECT_EQ(43, message.GetExtension(UNITTEST::default_uint32_extension));
+ EXPECT_EQ(44, message.GetExtension(UNITTEST::default_uint64_extension));
+ EXPECT_EQ(-45, message.GetExtension(UNITTEST::default_sint32_extension));
+ EXPECT_EQ(46, message.GetExtension(UNITTEST::default_sint64_extension));
+ EXPECT_EQ(47, message.GetExtension(UNITTEST::default_fixed32_extension));
+ EXPECT_EQ(48, message.GetExtension(UNITTEST::default_fixed64_extension));
+ EXPECT_EQ(49, message.GetExtension(UNITTEST::default_sfixed32_extension));
+ EXPECT_EQ(-50, message.GetExtension(UNITTEST::default_sfixed64_extension));
+ EXPECT_EQ(51.5, message.GetExtension(UNITTEST::default_float_extension));
+ EXPECT_EQ(52e3, message.GetExtension(UNITTEST::default_double_extension));
+ EXPECT_TRUE(message.GetExtension(UNITTEST::default_bool_extension));
+ EXPECT_EQ("hello", message.GetExtension(UNITTEST::default_string_extension));
+ EXPECT_EQ("world", message.GetExtension(UNITTEST::default_bytes_extension));
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAR,
+ message.GetExtension(UNITTEST::default_nested_enum_extension));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR,
+ message.GetExtension(UNITTEST::default_foreign_enum_extension));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR,
+ message.GetExtension(UNITTEST::default_import_enum_extension));
+
+ EXPECT_EQ("abc",
+ message.GetExtension(UNITTEST::default_string_piece_extension));
+ EXPECT_EQ("123", message.GetExtension(UNITTEST::default_cord_extension));
+
+ EXPECT_FALSE(message.HasExtension(UNITTEST::oneof_uint32_extension));
+ EXPECT_FALSE(
+ message.GetExtension(UNITTEST::oneof_nested_message_extension).has_bb());
+ EXPECT_FALSE(message.HasExtension(UNITTEST::oneof_string_extension));
+ EXPECT_FALSE(message.HasExtension(UNITTEST::oneof_bytes_extension));
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ExpectRepeatedExtensionsModified(
+ const UNITTEST::TestAllExtensions& 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_EQ(2, message.ExtensionSize(UNITTEST::repeated_int32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_float_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_double_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bool_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_string_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bytes_extension));
+
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeatedgroup_extension));
+ ASSERT_EQ(2,
+ message.ExtensionSize(UNITTEST::repeated_nested_message_extension));
+ ASSERT_EQ(
+ 2, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension));
+ ASSERT_EQ(2,
+ message.ExtensionSize(UNITTEST::repeated_import_message_extension));
+ ASSERT_EQ(2,
+ message.ExtensionSize(UNITTEST::repeated_lazy_message_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_nested_enum_extension));
+ ASSERT_EQ(2,
+ message.ExtensionSize(UNITTEST::repeated_foreign_enum_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_import_enum_extension));
+
+ ASSERT_EQ(2,
+ message.ExtensionSize(UNITTEST::repeated_string_piece_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_cord_extension));
+
+ EXPECT_EQ(201, message.GetExtension(UNITTEST::repeated_int32_extension, 0));
+ EXPECT_EQ(202, message.GetExtension(UNITTEST::repeated_int64_extension, 0));
+ EXPECT_EQ(203, message.GetExtension(UNITTEST::repeated_uint32_extension, 0));
+ EXPECT_EQ(204, message.GetExtension(UNITTEST::repeated_uint64_extension, 0));
+ EXPECT_EQ(205, message.GetExtension(UNITTEST::repeated_sint32_extension, 0));
+ EXPECT_EQ(206, message.GetExtension(UNITTEST::repeated_sint64_extension, 0));
+ EXPECT_EQ(207, message.GetExtension(UNITTEST::repeated_fixed32_extension, 0));
+ EXPECT_EQ(208, message.GetExtension(UNITTEST::repeated_fixed64_extension, 0));
+ EXPECT_EQ(209,
+ message.GetExtension(UNITTEST::repeated_sfixed32_extension, 0));
+ EXPECT_EQ(210,
+ message.GetExtension(UNITTEST::repeated_sfixed64_extension, 0));
+ EXPECT_EQ(211, message.GetExtension(UNITTEST::repeated_float_extension, 0));
+ EXPECT_EQ(212, message.GetExtension(UNITTEST::repeated_double_extension, 0));
+ EXPECT_TRUE(message.GetExtension(UNITTEST::repeated_bool_extension, 0));
+ EXPECT_EQ("215",
+ message.GetExtension(UNITTEST::repeated_string_extension, 0));
+ EXPECT_EQ("216", message.GetExtension(UNITTEST::repeated_bytes_extension, 0));
+
+ EXPECT_EQ(217,
+ message.GetExtension(UNITTEST::repeatedgroup_extension, 0).a());
+ EXPECT_EQ(218,
+ message.GetExtension(UNITTEST::repeated_nested_message_extension, 0)
+ .bb());
+ EXPECT_EQ(
+ 219, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 0)
+ .c());
+ EXPECT_EQ(
+ 220,
+ message.GetExtension(UNITTEST::repeated_import_message_extension, 0).d());
+ EXPECT_EQ(
+ 227,
+ message.GetExtension(UNITTEST::repeated_lazy_message_extension, 0).bb());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAR,
+ message.GetExtension(UNITTEST::repeated_nested_enum_extension, 0));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR,
+ message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 0));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR,
+ message.GetExtension(UNITTEST::repeated_import_enum_extension, 0));
+
+ EXPECT_EQ("224",
+ message.GetExtension(UNITTEST::repeated_string_piece_extension, 0));
+ EXPECT_EQ("225", message.GetExtension(UNITTEST::repeated_cord_extension, 0));
+
+ // Actually verify the second (modified) elements now.
+ EXPECT_EQ(501, message.GetExtension(UNITTEST::repeated_int32_extension, 1));
+ EXPECT_EQ(502, message.GetExtension(UNITTEST::repeated_int64_extension, 1));
+ EXPECT_EQ(503, message.GetExtension(UNITTEST::repeated_uint32_extension, 1));
+ EXPECT_EQ(504, message.GetExtension(UNITTEST::repeated_uint64_extension, 1));
+ EXPECT_EQ(505, message.GetExtension(UNITTEST::repeated_sint32_extension, 1));
+ EXPECT_EQ(506, message.GetExtension(UNITTEST::repeated_sint64_extension, 1));
+ EXPECT_EQ(507, message.GetExtension(UNITTEST::repeated_fixed32_extension, 1));
+ EXPECT_EQ(508, message.GetExtension(UNITTEST::repeated_fixed64_extension, 1));
+ EXPECT_EQ(509,
+ message.GetExtension(UNITTEST::repeated_sfixed32_extension, 1));
+ EXPECT_EQ(510,
+ message.GetExtension(UNITTEST::repeated_sfixed64_extension, 1));
+ EXPECT_EQ(511, message.GetExtension(UNITTEST::repeated_float_extension, 1));
+ EXPECT_EQ(512, message.GetExtension(UNITTEST::repeated_double_extension, 1));
+ EXPECT_TRUE(message.GetExtension(UNITTEST::repeated_bool_extension, 1));
+ EXPECT_EQ("515",
+ message.GetExtension(UNITTEST::repeated_string_extension, 1));
+ EXPECT_EQ("516", message.GetExtension(UNITTEST::repeated_bytes_extension, 1));
+
+ EXPECT_EQ(517,
+ message.GetExtension(UNITTEST::repeatedgroup_extension, 1).a());
+ EXPECT_EQ(518,
+ message.GetExtension(UNITTEST::repeated_nested_message_extension, 1)
+ .bb());
+ EXPECT_EQ(
+ 519, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 1)
+ .c());
+ EXPECT_EQ(
+ 520,
+ message.GetExtension(UNITTEST::repeated_import_message_extension, 1).d());
+ EXPECT_EQ(
+ 527,
+ message.GetExtension(UNITTEST::repeated_lazy_message_extension, 1).bb());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::FOO,
+ message.GetExtension(UNITTEST::repeated_nested_enum_extension, 1));
+ EXPECT_EQ(UNITTEST::FOREIGN_FOO,
+ message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 1));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO,
+ message.GetExtension(UNITTEST::repeated_import_enum_extension, 1));
+
+ EXPECT_EQ("524",
+ message.GetExtension(UNITTEST::repeated_string_piece_extension, 1));
+ EXPECT_EQ("525", message.GetExtension(UNITTEST::repeated_cord_extension, 1));
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::SetPackedExtensions(
+ UNITTEST::TestPackedExtensions* message) {
+ message->AddExtension(UNITTEST::packed_int32_extension, 601);
+ message->AddExtension(UNITTEST::packed_int64_extension, 602);
+ message->AddExtension(UNITTEST::packed_uint32_extension, 603);
+ message->AddExtension(UNITTEST::packed_uint64_extension, 604);
+ message->AddExtension(UNITTEST::packed_sint32_extension, 605);
+ message->AddExtension(UNITTEST::packed_sint64_extension, 606);
+ message->AddExtension(UNITTEST::packed_fixed32_extension, 607);
+ message->AddExtension(UNITTEST::packed_fixed64_extension, 608);
+ message->AddExtension(UNITTEST::packed_sfixed32_extension, 609);
+ message->AddExtension(UNITTEST::packed_sfixed64_extension, 610);
+ message->AddExtension(UNITTEST::packed_float_extension, 611);
+ message->AddExtension(UNITTEST::packed_double_extension, 612);
+ message->AddExtension(UNITTEST::packed_bool_extension, true);
+ message->AddExtension(UNITTEST::packed_enum_extension, UNITTEST::FOREIGN_BAR);
+ // add a second one of each field
+ message->AddExtension(UNITTEST::packed_int32_extension, 701);
+ message->AddExtension(UNITTEST::packed_int64_extension, 702);
+ message->AddExtension(UNITTEST::packed_uint32_extension, 703);
+ message->AddExtension(UNITTEST::packed_uint64_extension, 704);
+ message->AddExtension(UNITTEST::packed_sint32_extension, 705);
+ message->AddExtension(UNITTEST::packed_sint64_extension, 706);
+ message->AddExtension(UNITTEST::packed_fixed32_extension, 707);
+ message->AddExtension(UNITTEST::packed_fixed64_extension, 708);
+ message->AddExtension(UNITTEST::packed_sfixed32_extension, 709);
+ message->AddExtension(UNITTEST::packed_sfixed64_extension, 710);
+ message->AddExtension(UNITTEST::packed_float_extension, 711);
+ message->AddExtension(UNITTEST::packed_double_extension, 712);
+ message->AddExtension(UNITTEST::packed_bool_extension, false);
+ message->AddExtension(UNITTEST::packed_enum_extension, UNITTEST::FOREIGN_BAZ);
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ModifyPackedExtensions(
+ UNITTEST::TestPackedExtensions* message) {
+ message->SetExtension(UNITTEST::packed_int32_extension, 1, 801);
+ message->SetExtension(UNITTEST::packed_int64_extension, 1, 802);
+ message->SetExtension(UNITTEST::packed_uint32_extension, 1, 803);
+ message->SetExtension(UNITTEST::packed_uint64_extension, 1, 804);
+ message->SetExtension(UNITTEST::packed_sint32_extension, 1, 805);
+ message->SetExtension(UNITTEST::packed_sint64_extension, 1, 806);
+ message->SetExtension(UNITTEST::packed_fixed32_extension, 1, 807);
+ message->SetExtension(UNITTEST::packed_fixed64_extension, 1, 808);
+ message->SetExtension(UNITTEST::packed_sfixed32_extension, 1, 809);
+ message->SetExtension(UNITTEST::packed_sfixed64_extension, 1, 810);
+ message->SetExtension(UNITTEST::packed_float_extension, 1, 811);
+ message->SetExtension(UNITTEST::packed_double_extension, 1, 812);
+ message->SetExtension(UNITTEST::packed_bool_extension, 1, true);
+ message->SetExtension(UNITTEST::packed_enum_extension, 1,
+ UNITTEST::FOREIGN_FOO);
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ExpectPackedExtensionsSet(
+ const UNITTEST::TestPackedExtensions& message) {
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_int32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_int64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_uint32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_uint64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sint32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sint64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_fixed32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_fixed64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sfixed32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sfixed64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_float_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_double_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_bool_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_enum_extension));
+
+ EXPECT_EQ(601, message.GetExtension(UNITTEST::packed_int32_extension, 0));
+ EXPECT_EQ(602, message.GetExtension(UNITTEST::packed_int64_extension, 0));
+ EXPECT_EQ(603, message.GetExtension(UNITTEST::packed_uint32_extension, 0));
+ EXPECT_EQ(604, message.GetExtension(UNITTEST::packed_uint64_extension, 0));
+ EXPECT_EQ(605, message.GetExtension(UNITTEST::packed_sint32_extension, 0));
+ EXPECT_EQ(606, message.GetExtension(UNITTEST::packed_sint64_extension, 0));
+ EXPECT_EQ(607, message.GetExtension(UNITTEST::packed_fixed32_extension, 0));
+ EXPECT_EQ(608, message.GetExtension(UNITTEST::packed_fixed64_extension, 0));
+ EXPECT_EQ(609, message.GetExtension(UNITTEST::packed_sfixed32_extension, 0));
+ EXPECT_EQ(610, message.GetExtension(UNITTEST::packed_sfixed64_extension, 0));
+ EXPECT_EQ(611, message.GetExtension(UNITTEST::packed_float_extension, 0));
+ EXPECT_EQ(612, message.GetExtension(UNITTEST::packed_double_extension, 0));
+ EXPECT_TRUE(message.GetExtension(UNITTEST::packed_bool_extension, 0));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR,
+ message.GetExtension(UNITTEST::packed_enum_extension, 0));
+ EXPECT_EQ(701, message.GetExtension(UNITTEST::packed_int32_extension, 1));
+ EXPECT_EQ(702, message.GetExtension(UNITTEST::packed_int64_extension, 1));
+ EXPECT_EQ(703, message.GetExtension(UNITTEST::packed_uint32_extension, 1));
+ EXPECT_EQ(704, message.GetExtension(UNITTEST::packed_uint64_extension, 1));
+ EXPECT_EQ(705, message.GetExtension(UNITTEST::packed_sint32_extension, 1));
+ EXPECT_EQ(706, message.GetExtension(UNITTEST::packed_sint64_extension, 1));
+ EXPECT_EQ(707, message.GetExtension(UNITTEST::packed_fixed32_extension, 1));
+ EXPECT_EQ(708, message.GetExtension(UNITTEST::packed_fixed64_extension, 1));
+ EXPECT_EQ(709, message.GetExtension(UNITTEST::packed_sfixed32_extension, 1));
+ EXPECT_EQ(710, message.GetExtension(UNITTEST::packed_sfixed64_extension, 1));
+ EXPECT_EQ(711, message.GetExtension(UNITTEST::packed_float_extension, 1));
+ EXPECT_EQ(712, message.GetExtension(UNITTEST::packed_double_extension, 1));
+ EXPECT_FALSE(message.GetExtension(UNITTEST::packed_bool_extension, 1));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAZ,
+ message.GetExtension(UNITTEST::packed_enum_extension, 1));
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ExpectPackedExtensionsClear(
+ const UNITTEST::TestPackedExtensions& message) {
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_int32_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_int64_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_uint32_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_uint64_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_sint32_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_sint64_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_fixed32_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_fixed64_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_sfixed32_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_sfixed64_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_float_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_double_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_bool_extension));
+ EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_enum_extension));
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ExpectPackedExtensionsModified(
+ const UNITTEST::TestPackedExtensions& message) {
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_int32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_int64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_uint32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_uint64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sint32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sint64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_fixed32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_fixed64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sfixed32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sfixed64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_float_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_double_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_bool_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_enum_extension));
+ EXPECT_EQ(601, message.GetExtension(UNITTEST::packed_int32_extension, 0));
+ EXPECT_EQ(602, message.GetExtension(UNITTEST::packed_int64_extension, 0));
+ EXPECT_EQ(603, message.GetExtension(UNITTEST::packed_uint32_extension, 0));
+ EXPECT_EQ(604, message.GetExtension(UNITTEST::packed_uint64_extension, 0));
+ EXPECT_EQ(605, message.GetExtension(UNITTEST::packed_sint32_extension, 0));
+ EXPECT_EQ(606, message.GetExtension(UNITTEST::packed_sint64_extension, 0));
+ EXPECT_EQ(607, message.GetExtension(UNITTEST::packed_fixed32_extension, 0));
+ EXPECT_EQ(608, message.GetExtension(UNITTEST::packed_fixed64_extension, 0));
+ EXPECT_EQ(609, message.GetExtension(UNITTEST::packed_sfixed32_extension, 0));
+ EXPECT_EQ(610, message.GetExtension(UNITTEST::packed_sfixed64_extension, 0));
+ EXPECT_EQ(611, message.GetExtension(UNITTEST::packed_float_extension, 0));
+ EXPECT_EQ(612, message.GetExtension(UNITTEST::packed_double_extension, 0));
+ EXPECT_TRUE(message.GetExtension(UNITTEST::packed_bool_extension, 0));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR,
+ message.GetExtension(UNITTEST::packed_enum_extension, 0));
+
+ // Actually verify the second (modified) elements now.
+ EXPECT_EQ(801, message.GetExtension(UNITTEST::packed_int32_extension, 1));
+ EXPECT_EQ(802, message.GetExtension(UNITTEST::packed_int64_extension, 1));
+ EXPECT_EQ(803, message.GetExtension(UNITTEST::packed_uint32_extension, 1));
+ EXPECT_EQ(804, message.GetExtension(UNITTEST::packed_uint64_extension, 1));
+ EXPECT_EQ(805, message.GetExtension(UNITTEST::packed_sint32_extension, 1));
+ EXPECT_EQ(806, message.GetExtension(UNITTEST::packed_sint64_extension, 1));
+ EXPECT_EQ(807, message.GetExtension(UNITTEST::packed_fixed32_extension, 1));
+ EXPECT_EQ(808, message.GetExtension(UNITTEST::packed_fixed64_extension, 1));
+ EXPECT_EQ(809, message.GetExtension(UNITTEST::packed_sfixed32_extension, 1));
+ EXPECT_EQ(810, message.GetExtension(UNITTEST::packed_sfixed64_extension, 1));
+ EXPECT_EQ(811, message.GetExtension(UNITTEST::packed_float_extension, 1));
+ EXPECT_EQ(812, message.GetExtension(UNITTEST::packed_double_extension, 1));
+ EXPECT_TRUE(message.GetExtension(UNITTEST::packed_bool_extension, 1));
+ EXPECT_EQ(UNITTEST::FOREIGN_FOO,
+ message.GetExtension(UNITTEST::packed_enum_extension, 1));
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ExpectUnpackedExtensionsSet(
+ const UNITTEST::TestUnpackedExtensions& message) {
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_int32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_int64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_uint32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_uint64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_sint32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_sint64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_fixed32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_fixed64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_sfixed32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_sfixed64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_float_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_double_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_bool_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_enum_extension));
+
+ EXPECT_EQ(601, message.GetExtension(UNITTEST::unpacked_int32_extension, 0));
+ EXPECT_EQ(602, message.GetExtension(UNITTEST::unpacked_int64_extension, 0));
+ EXPECT_EQ(603, message.GetExtension(UNITTEST::unpacked_uint32_extension, 0));
+ EXPECT_EQ(604, message.GetExtension(UNITTEST::unpacked_uint64_extension, 0));
+ EXPECT_EQ(605, message.GetExtension(UNITTEST::unpacked_sint32_extension, 0));
+ EXPECT_EQ(606, message.GetExtension(UNITTEST::unpacked_sint64_extension, 0));
+ EXPECT_EQ(607, message.GetExtension(UNITTEST::unpacked_fixed32_extension, 0));
+ EXPECT_EQ(608, message.GetExtension(UNITTEST::unpacked_fixed64_extension, 0));
+ EXPECT_EQ(609,
+ message.GetExtension(UNITTEST::unpacked_sfixed32_extension, 0));
+ EXPECT_EQ(610,
+ message.GetExtension(UNITTEST::unpacked_sfixed64_extension, 0));
+ EXPECT_EQ(611, message.GetExtension(UNITTEST::unpacked_float_extension, 0));
+ EXPECT_EQ(612, message.GetExtension(UNITTEST::unpacked_double_extension, 0));
+ EXPECT_EQ(true, message.GetExtension(UNITTEST::unpacked_bool_extension, 0));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR,
+ message.GetExtension(UNITTEST::unpacked_enum_extension, 0));
+ EXPECT_EQ(701, message.GetExtension(UNITTEST::unpacked_int32_extension, 1));
+ EXPECT_EQ(702, message.GetExtension(UNITTEST::unpacked_int64_extension, 1));
+ EXPECT_EQ(703, message.GetExtension(UNITTEST::unpacked_uint32_extension, 1));
+ EXPECT_EQ(704, message.GetExtension(UNITTEST::unpacked_uint64_extension, 1));
+ EXPECT_EQ(705, message.GetExtension(UNITTEST::unpacked_sint32_extension, 1));
+ EXPECT_EQ(706, message.GetExtension(UNITTEST::unpacked_sint64_extension, 1));
+ EXPECT_EQ(707, message.GetExtension(UNITTEST::unpacked_fixed32_extension, 1));
+ EXPECT_EQ(708, message.GetExtension(UNITTEST::unpacked_fixed64_extension, 1));
+ EXPECT_EQ(709,
+ message.GetExtension(UNITTEST::unpacked_sfixed32_extension, 1));
+ EXPECT_EQ(710,
+ message.GetExtension(UNITTEST::unpacked_sfixed64_extension, 1));
+ EXPECT_EQ(711, message.GetExtension(UNITTEST::unpacked_float_extension, 1));
+ EXPECT_EQ(712, message.GetExtension(UNITTEST::unpacked_double_extension, 1));
+ EXPECT_EQ(false, message.GetExtension(UNITTEST::unpacked_bool_extension, 1));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAZ,
+ message.GetExtension(UNITTEST::unpacked_enum_extension, 1));
+}
+
+// -------------------------------------------------------------------
+
+inline void TestUtil::ExpectLastRepeatedsRemoved(
+ const UNITTEST::TestAllTypes& message) {
+ ASSERT_EQ(1, message.repeated_int32_size());
+ ASSERT_EQ(1, message.repeated_int64_size());
+ ASSERT_EQ(1, message.repeated_uint32_size());
+ ASSERT_EQ(1, message.repeated_uint64_size());
+ ASSERT_EQ(1, message.repeated_sint32_size());
+ ASSERT_EQ(1, message.repeated_sint64_size());
+ ASSERT_EQ(1, message.repeated_fixed32_size());
+ ASSERT_EQ(1, message.repeated_fixed64_size());
+ ASSERT_EQ(1, message.repeated_sfixed32_size());
+ ASSERT_EQ(1, message.repeated_sfixed64_size());
+ ASSERT_EQ(1, message.repeated_float_size());
+ ASSERT_EQ(1, message.repeated_double_size());
+ ASSERT_EQ(1, message.repeated_bool_size());
+ ASSERT_EQ(1, message.repeated_string_size());
+ ASSERT_EQ(1, message.repeated_bytes_size());
+
+ ASSERT_EQ(1, message.repeatedgroup_size());
+ ASSERT_EQ(1, message.repeated_nested_message_size());
+ ASSERT_EQ(1, message.repeated_foreign_message_size());
+ ASSERT_EQ(1, message.repeated_import_message_size());
+ ASSERT_EQ(1, message.repeated_import_message_size());
+ ASSERT_EQ(1, message.repeated_nested_enum_size());
+ ASSERT_EQ(1, message.repeated_foreign_enum_size());
+ ASSERT_EQ(1, message.repeated_import_enum_size());
+
+#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
+ ASSERT_EQ(1, message.repeated_string_piece_size());
+ ASSERT_EQ(1, message.repeated_cord_size());
+#endif
+
+ // Test that the remaining element is the correct one.
+ EXPECT_EQ(201, message.repeated_int32(0));
+ EXPECT_EQ(202, message.repeated_int64(0));
+ EXPECT_EQ(203, message.repeated_uint32(0));
+ EXPECT_EQ(204, message.repeated_uint64(0));
+ EXPECT_EQ(205, message.repeated_sint32(0));
+ EXPECT_EQ(206, message.repeated_sint64(0));
+ EXPECT_EQ(207, message.repeated_fixed32(0));
+ EXPECT_EQ(208, message.repeated_fixed64(0));
+ EXPECT_EQ(209, message.repeated_sfixed32(0));
+ EXPECT_EQ(210, message.repeated_sfixed64(0));
+ EXPECT_EQ(211, message.repeated_float(0));
+ EXPECT_EQ(212, message.repeated_double(0));
+ EXPECT_TRUE(message.repeated_bool(0));
+ EXPECT_EQ("215", message.repeated_string(0));
+ EXPECT_EQ("216", message.repeated_bytes(0));
+
+ EXPECT_EQ(217, message.repeatedgroup(0).a());
+ EXPECT_EQ(218, message.repeated_nested_message(0).bb());
+ EXPECT_EQ(219, message.repeated_foreign_message(0).c());
+ EXPECT_EQ(220, message.repeated_import_message(0).d());
+ EXPECT_EQ(220, message.repeated_import_message(0).d());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message.repeated_nested_enum(0));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeated_foreign_enum(0));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, message.repeated_import_enum(0));
+}
+
+inline void TestUtil::ExpectLastRepeatedExtensionsRemoved(
+ const UNITTEST::TestAllExtensions& message) {
+ // Test that one element was removed.
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_int32_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_int64_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_uint32_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_uint64_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_sint32_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_sint64_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_fixed32_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_fixed64_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_sfixed32_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_sfixed64_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_float_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_double_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_bool_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_string_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_bytes_extension));
+
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeatedgroup_extension));
+ ASSERT_EQ(1,
+ message.ExtensionSize(UNITTEST::repeated_nested_message_extension));
+ ASSERT_EQ(
+ 1, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension));
+ ASSERT_EQ(1,
+ message.ExtensionSize(UNITTEST::repeated_import_message_extension));
+ ASSERT_EQ(1,
+ message.ExtensionSize(UNITTEST::repeated_lazy_message_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_nested_enum_extension));
+ ASSERT_EQ(1,
+ message.ExtensionSize(UNITTEST::repeated_foreign_enum_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_import_enum_extension));
+
+ ASSERT_EQ(1,
+ message.ExtensionSize(UNITTEST::repeated_string_piece_extension));
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_cord_extension));
+
+ // Test that the remaining element is the correct one.
+ EXPECT_EQ(201, message.GetExtension(UNITTEST::repeated_int32_extension, 0));
+ EXPECT_EQ(202, message.GetExtension(UNITTEST::repeated_int64_extension, 0));
+ EXPECT_EQ(203, message.GetExtension(UNITTEST::repeated_uint32_extension, 0));
+ EXPECT_EQ(204, message.GetExtension(UNITTEST::repeated_uint64_extension, 0));
+ EXPECT_EQ(205, message.GetExtension(UNITTEST::repeated_sint32_extension, 0));
+ EXPECT_EQ(206, message.GetExtension(UNITTEST::repeated_sint64_extension, 0));
+ EXPECT_EQ(207, message.GetExtension(UNITTEST::repeated_fixed32_extension, 0));
+ EXPECT_EQ(208, message.GetExtension(UNITTEST::repeated_fixed64_extension, 0));
+ EXPECT_EQ(209,
+ message.GetExtension(UNITTEST::repeated_sfixed32_extension, 0));
+ EXPECT_EQ(210,
+ message.GetExtension(UNITTEST::repeated_sfixed64_extension, 0));
+ EXPECT_EQ(211, message.GetExtension(UNITTEST::repeated_float_extension, 0));
+ EXPECT_EQ(212, message.GetExtension(UNITTEST::repeated_double_extension, 0));
+ EXPECT_TRUE(message.GetExtension(UNITTEST::repeated_bool_extension, 0));
+ EXPECT_EQ("215",
+ message.GetExtension(UNITTEST::repeated_string_extension, 0));
+ EXPECT_EQ("216", message.GetExtension(UNITTEST::repeated_bytes_extension, 0));
+
+ EXPECT_EQ(217,
+ message.GetExtension(UNITTEST::repeatedgroup_extension, 0).a());
+ EXPECT_EQ(218,
+ message.GetExtension(UNITTEST::repeated_nested_message_extension, 0)
+ .bb());
+ EXPECT_EQ(
+ 219, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 0)
+ .c());
+ EXPECT_EQ(
+ 220,
+ message.GetExtension(UNITTEST::repeated_import_message_extension, 0).d());
+ EXPECT_EQ(
+ 227,
+ message.GetExtension(UNITTEST::repeated_lazy_message_extension, 0).bb());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAR,
+ message.GetExtension(UNITTEST::repeated_nested_enum_extension, 0));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR,
+ message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 0));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR,
+ message.GetExtension(UNITTEST::repeated_import_enum_extension, 0));
+
+ EXPECT_EQ("224",
+ message.GetExtension(UNITTEST::repeated_string_piece_extension, 0));
+ EXPECT_EQ("225", message.GetExtension(UNITTEST::repeated_cord_extension, 0));
+}
+
+inline void TestUtil::ExpectLastRepeatedsReleased(
+ const UNITTEST::TestAllTypes& message) {
+ ASSERT_EQ(1, message.repeatedgroup_size());
+ ASSERT_EQ(1, message.repeated_nested_message_size());
+ ASSERT_EQ(1, message.repeated_foreign_message_size());
+ ASSERT_EQ(1, message.repeated_import_message_size());
+ ASSERT_EQ(1, message.repeated_import_message_size());
+
+ EXPECT_EQ(217, message.repeatedgroup(0).a());
+ EXPECT_EQ(218, message.repeated_nested_message(0).bb());
+ EXPECT_EQ(219, message.repeated_foreign_message(0).c());
+ EXPECT_EQ(220, message.repeated_import_message(0).d());
+ EXPECT_EQ(220, message.repeated_import_message(0).d());
+}
+
+inline void TestUtil::ExpectLastRepeatedExtensionsReleased(
+ const UNITTEST::TestAllExtensions& message) {
+ ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeatedgroup_extension));
+ ASSERT_EQ(1,
+ message.ExtensionSize(UNITTEST::repeated_nested_message_extension));
+ ASSERT_EQ(
+ 1, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension));
+ ASSERT_EQ(1,
+ message.ExtensionSize(UNITTEST::repeated_import_message_extension));
+ ASSERT_EQ(1,
+ message.ExtensionSize(UNITTEST::repeated_lazy_message_extension));
+
+ EXPECT_EQ(217,
+ message.GetExtension(UNITTEST::repeatedgroup_extension, 0).a());
+ EXPECT_EQ(218,
+ message.GetExtension(UNITTEST::repeated_nested_message_extension, 0)
+ .bb());
+ EXPECT_EQ(
+ 219, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 0)
+ .c());
+ EXPECT_EQ(
+ 220,
+ message.GetExtension(UNITTEST::repeated_import_message_extension, 0).d());
+ EXPECT_EQ(
+ 227,
+ message.GetExtension(UNITTEST::repeated_lazy_message_extension, 0).bb());
+}
+
+inline void TestUtil::ExpectRepeatedsSwapped(
+ const UNITTEST::TestAllTypes& message) {
+ ASSERT_EQ(2, message.repeated_int32_size());
+ ASSERT_EQ(2, message.repeated_int64_size());
+ ASSERT_EQ(2, message.repeated_uint32_size());
+ ASSERT_EQ(2, message.repeated_uint64_size());
+ ASSERT_EQ(2, message.repeated_sint32_size());
+ ASSERT_EQ(2, message.repeated_sint64_size());
+ ASSERT_EQ(2, message.repeated_fixed32_size());
+ ASSERT_EQ(2, message.repeated_fixed64_size());
+ ASSERT_EQ(2, message.repeated_sfixed32_size());
+ ASSERT_EQ(2, message.repeated_sfixed64_size());
+ ASSERT_EQ(2, message.repeated_float_size());
+ ASSERT_EQ(2, message.repeated_double_size());
+ ASSERT_EQ(2, message.repeated_bool_size());
+ ASSERT_EQ(2, message.repeated_string_size());
+ ASSERT_EQ(2, message.repeated_bytes_size());
+
+ ASSERT_EQ(2, message.repeatedgroup_size());
+ ASSERT_EQ(2, message.repeated_nested_message_size());
+ ASSERT_EQ(2, message.repeated_foreign_message_size());
+ ASSERT_EQ(2, message.repeated_import_message_size());
+ ASSERT_EQ(2, message.repeated_import_message_size());
+ ASSERT_EQ(2, message.repeated_nested_enum_size());
+ ASSERT_EQ(2, message.repeated_foreign_enum_size());
+ ASSERT_EQ(2, message.repeated_import_enum_size());
+
+#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
+ ASSERT_EQ(2, message.repeated_string_piece_size());
+ ASSERT_EQ(2, message.repeated_cord_size());
+#endif
+
+ // Test that the first element and second element are flipped.
+ EXPECT_EQ(201, message.repeated_int32(1));
+ EXPECT_EQ(202, message.repeated_int64(1));
+ EXPECT_EQ(203, message.repeated_uint32(1));
+ EXPECT_EQ(204, message.repeated_uint64(1));
+ EXPECT_EQ(205, message.repeated_sint32(1));
+ EXPECT_EQ(206, message.repeated_sint64(1));
+ EXPECT_EQ(207, message.repeated_fixed32(1));
+ EXPECT_EQ(208, message.repeated_fixed64(1));
+ EXPECT_EQ(209, message.repeated_sfixed32(1));
+ EXPECT_EQ(210, message.repeated_sfixed64(1));
+ EXPECT_EQ(211, message.repeated_float(1));
+ EXPECT_EQ(212, message.repeated_double(1));
+ EXPECT_TRUE(message.repeated_bool(1));
+ EXPECT_EQ("215", message.repeated_string(1));
+ EXPECT_EQ("216", message.repeated_bytes(1));
+
+ EXPECT_EQ(217, message.repeatedgroup(1).a());
+ EXPECT_EQ(218, message.repeated_nested_message(1).bb());
+ EXPECT_EQ(219, message.repeated_foreign_message(1).c());
+ EXPECT_EQ(220, message.repeated_import_message(1).d());
+ EXPECT_EQ(220, message.repeated_import_message(1).d());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message.repeated_nested_enum(1));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeated_foreign_enum(1));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, message.repeated_import_enum(1));
+
+ EXPECT_EQ(301, message.repeated_int32(0));
+ EXPECT_EQ(302, message.repeated_int64(0));
+ EXPECT_EQ(303, message.repeated_uint32(0));
+ EXPECT_EQ(304, message.repeated_uint64(0));
+ EXPECT_EQ(305, message.repeated_sint32(0));
+ EXPECT_EQ(306, message.repeated_sint64(0));
+ EXPECT_EQ(307, message.repeated_fixed32(0));
+ EXPECT_EQ(308, message.repeated_fixed64(0));
+ EXPECT_EQ(309, message.repeated_sfixed32(0));
+ EXPECT_EQ(310, message.repeated_sfixed64(0));
+ EXPECT_EQ(311, message.repeated_float(0));
+ EXPECT_EQ(312, message.repeated_double(0));
+ EXPECT_FALSE(message.repeated_bool(0));
+ EXPECT_EQ("315", message.repeated_string(0));
+ EXPECT_EQ("316", message.repeated_bytes(0));
+
+ EXPECT_EQ(317, message.repeatedgroup(0).a());
+ EXPECT_EQ(318, message.repeated_nested_message(0).bb());
+ EXPECT_EQ(319, message.repeated_foreign_message(0).c());
+ EXPECT_EQ(320, message.repeated_import_message(0).d());
+ EXPECT_EQ(320, message.repeated_import_message(0).d());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, message.repeated_nested_enum(0));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.repeated_foreign_enum(0));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ, message.repeated_import_enum(0));
+}
+
+inline void TestUtil::ExpectRepeatedExtensionsSwapped(
+ const UNITTEST::TestAllExtensions& message) {
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed32_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed64_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_float_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_double_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bool_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_string_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bytes_extension));
+
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeatedgroup_extension));
+ ASSERT_EQ(2,
+ message.ExtensionSize(UNITTEST::repeated_nested_message_extension));
+ ASSERT_EQ(
+ 2, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension));
+ ASSERT_EQ(2,
+ message.ExtensionSize(UNITTEST::repeated_import_message_extension));
+ ASSERT_EQ(2,
+ message.ExtensionSize(UNITTEST::repeated_lazy_message_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_nested_enum_extension));
+ ASSERT_EQ(2,
+ message.ExtensionSize(UNITTEST::repeated_foreign_enum_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_import_enum_extension));
+
+ ASSERT_EQ(2,
+ message.ExtensionSize(UNITTEST::repeated_string_piece_extension));
+ ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_cord_extension));
+
+ EXPECT_EQ(201, message.GetExtension(UNITTEST::repeated_int32_extension, 1));
+ EXPECT_EQ(202, message.GetExtension(UNITTEST::repeated_int64_extension, 1));
+ EXPECT_EQ(203, message.GetExtension(UNITTEST::repeated_uint32_extension, 1));
+ EXPECT_EQ(204, message.GetExtension(UNITTEST::repeated_uint64_extension, 1));
+ EXPECT_EQ(205, message.GetExtension(UNITTEST::repeated_sint32_extension, 1));
+ EXPECT_EQ(206, message.GetExtension(UNITTEST::repeated_sint64_extension, 1));
+ EXPECT_EQ(207, message.GetExtension(UNITTEST::repeated_fixed32_extension, 1));
+ EXPECT_EQ(208, message.GetExtension(UNITTEST::repeated_fixed64_extension, 1));
+ EXPECT_EQ(209,
+ message.GetExtension(UNITTEST::repeated_sfixed32_extension, 1));
+ EXPECT_EQ(210,
+ message.GetExtension(UNITTEST::repeated_sfixed64_extension, 1));
+ EXPECT_EQ(211, message.GetExtension(UNITTEST::repeated_float_extension, 1));
+ EXPECT_EQ(212, message.GetExtension(UNITTEST::repeated_double_extension, 1));
+ EXPECT_TRUE(message.GetExtension(UNITTEST::repeated_bool_extension, 1));
+ EXPECT_EQ("215",
+ message.GetExtension(UNITTEST::repeated_string_extension, 1));
+ EXPECT_EQ("216", message.GetExtension(UNITTEST::repeated_bytes_extension, 1));
+
+ EXPECT_EQ(217,
+ message.GetExtension(UNITTEST::repeatedgroup_extension, 1).a());
+ EXPECT_EQ(218,
+ message.GetExtension(UNITTEST::repeated_nested_message_extension, 1)
+ .bb());
+ EXPECT_EQ(
+ 219, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 1)
+ .c());
+ EXPECT_EQ(
+ 220,
+ message.GetExtension(UNITTEST::repeated_import_message_extension, 1).d());
+ EXPECT_EQ(
+ 227,
+ message.GetExtension(UNITTEST::repeated_lazy_message_extension, 1).bb());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAR,
+ message.GetExtension(UNITTEST::repeated_nested_enum_extension, 1));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAR,
+ message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 1));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR,
+ message.GetExtension(UNITTEST::repeated_import_enum_extension, 1));
+
+ EXPECT_EQ("224",
+ message.GetExtension(UNITTEST::repeated_string_piece_extension, 1));
+ EXPECT_EQ("225", message.GetExtension(UNITTEST::repeated_cord_extension, 1));
+
+ EXPECT_EQ(301, message.GetExtension(UNITTEST::repeated_int32_extension, 0));
+ EXPECT_EQ(302, message.GetExtension(UNITTEST::repeated_int64_extension, 0));
+ EXPECT_EQ(303, message.GetExtension(UNITTEST::repeated_uint32_extension, 0));
+ EXPECT_EQ(304, message.GetExtension(UNITTEST::repeated_uint64_extension, 0));
+ EXPECT_EQ(305, message.GetExtension(UNITTEST::repeated_sint32_extension, 0));
+ EXPECT_EQ(306, message.GetExtension(UNITTEST::repeated_sint64_extension, 0));
+ EXPECT_EQ(307, message.GetExtension(UNITTEST::repeated_fixed32_extension, 0));
+ EXPECT_EQ(308, message.GetExtension(UNITTEST::repeated_fixed64_extension, 0));
+ EXPECT_EQ(309,
+ message.GetExtension(UNITTEST::repeated_sfixed32_extension, 0));
+ EXPECT_EQ(310,
+ message.GetExtension(UNITTEST::repeated_sfixed64_extension, 0));
+ EXPECT_EQ(311, message.GetExtension(UNITTEST::repeated_float_extension, 0));
+ EXPECT_EQ(312, message.GetExtension(UNITTEST::repeated_double_extension, 0));
+ EXPECT_FALSE(message.GetExtension(UNITTEST::repeated_bool_extension, 0));
+ EXPECT_EQ("315",
+ message.GetExtension(UNITTEST::repeated_string_extension, 0));
+ EXPECT_EQ("316", message.GetExtension(UNITTEST::repeated_bytes_extension, 0));
+
+ EXPECT_EQ(317,
+ message.GetExtension(UNITTEST::repeatedgroup_extension, 0).a());
+ EXPECT_EQ(318,
+ message.GetExtension(UNITTEST::repeated_nested_message_extension, 0)
+ .bb());
+ EXPECT_EQ(
+ 319, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 0)
+ .c());
+ EXPECT_EQ(
+ 320,
+ message.GetExtension(UNITTEST::repeated_import_message_extension, 0).d());
+ EXPECT_EQ(
+ 327,
+ message.GetExtension(UNITTEST::repeated_lazy_message_extension, 0).bb());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::BAZ,
+ message.GetExtension(UNITTEST::repeated_nested_enum_extension, 0));
+ EXPECT_EQ(UNITTEST::FOREIGN_BAZ,
+ message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 0));
+ EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ,
+ message.GetExtension(UNITTEST::repeated_import_enum_extension, 0));
+
+ EXPECT_EQ("324",
+ message.GetExtension(UNITTEST::repeated_string_piece_extension, 0));
+ EXPECT_EQ("325", message.GetExtension(UNITTEST::repeated_cord_extension, 0));
+}
+
+inline void TestUtil::SetOneof1(UNITTEST::TestOneof2* message) {
+ message->mutable_foo_lazy_message()->set_qux_int(100);
+ message->set_bar_string("101");
+ message->set_baz_int(102);
+ message->set_baz_string("103");
+}
+
+inline void TestUtil::SetOneof2(UNITTEST::TestOneof2* message) {
+ message->set_foo_int(200);
+ message->set_bar_enum(UNITTEST::TestOneof2::BAZ);
+ message->set_baz_int(202);
+ message->set_baz_string("203");
+}
+
+inline void TestUtil::ExpectOneofSet1(const UNITTEST::TestOneof2& message) {
+ ExpectAtMostOneFieldSetInOneof(message);
+
+ EXPECT_TRUE(message.has_foo_lazy_message());
+ EXPECT_TRUE(message.foo_lazy_message().has_qux_int());
+
+ EXPECT_TRUE(message.has_bar_string());
+ EXPECT_TRUE(message.has_baz_int());
+ EXPECT_TRUE(message.has_baz_string());
+
+ ASSERT_EQ(0, message.foo_lazy_message().corge_int_size());
+
+ EXPECT_EQ(100, message.foo_lazy_message().qux_int());
+ EXPECT_EQ("101", message.bar_string());
+ EXPECT_EQ(102, message.baz_int());
+ EXPECT_EQ("103", message.baz_string());
+}
+
+inline void TestUtil::ExpectOneofSet2(const UNITTEST::TestOneof2& message) {
+ ExpectAtMostOneFieldSetInOneof(message);
+
+ EXPECT_TRUE(message.has_foo_int());
+ EXPECT_TRUE(message.has_bar_enum());
+ EXPECT_TRUE(message.has_baz_int());
+ EXPECT_TRUE(message.has_baz_string());
+
+ EXPECT_EQ(200, message.foo_int());
+ EXPECT_EQ(UNITTEST::TestOneof2::BAZ, message.bar_enum());
+ EXPECT_EQ(202, message.baz_int());
+ EXPECT_EQ("203", message.baz_string());
+}
+
+inline void TestUtil::ExpectOneofClear(const UNITTEST::TestOneof2& message) {
+ EXPECT_FALSE(message.has_foo_int());
+ EXPECT_FALSE(message.has_foo_string());
+ EXPECT_FALSE(message.has_foo_bytes());
+ EXPECT_FALSE(message.has_foo_enum());
+ EXPECT_FALSE(message.has_foo_message());
+ EXPECT_FALSE(message.has_foogroup());
+ EXPECT_FALSE(message.has_foo_lazy_message());
+
+ EXPECT_FALSE(message.has_bar_int());
+ EXPECT_FALSE(message.has_bar_string());
+ EXPECT_FALSE(message.has_bar_bytes());
+ EXPECT_FALSE(message.has_bar_enum());
+
+ EXPECT_FALSE(message.has_baz_int());
+ EXPECT_FALSE(message.has_baz_string());
+
+ EXPECT_EQ(UNITTEST::TestOneof2::FOO_NOT_SET, message.foo_case());
+ EXPECT_EQ(UNITTEST::TestOneof2::BAR_NOT_SET, message.bar_case());
+}
+
+inline void TestUtil::ExpectAtMostOneFieldSetInOneof(
+ const UNITTEST::TestOneof2& message) {
+ int count = 0;
+ if (message.has_foo_int()) count++;
+ if (message.has_foo_string()) count++;
+ if (message.has_foo_bytes()) count++;
+ if (message.has_foo_enum()) count++;
+ if (message.has_foo_message()) count++;
+ if (message.has_foogroup()) count++;
+ if (message.has_foo_lazy_message()) count++;
+ EXPECT_LE(count, 1);
+ count = 0;
+ if (message.has_bar_int()) count++;
+ if (message.has_bar_string()) count++;
+ if (message.has_bar_bytes()) count++;
+ if (message.has_bar_enum()) count++;
+ EXPECT_TRUE(count == 0 || count == 1);
+}
+
+// ===================================================================
+
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/text_format.cc b/src/google/protobuf/text_format.cc
index eed2a768..a9c062eb 100644
--- a/src/google/protobuf/text_format.cc
+++ b/src/google/protobuf/text_format.cc
@@ -57,6 +57,7 @@
#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>
@@ -189,6 +190,24 @@ TextFormat::ParseInfoTree* TextFormat::ParseInfoTree::GetTreeForNested(
return (*trees)[index];
}
+namespace {
+// These functions implement the behavior of the "default" TextFormat::Finder,
+// they are defined as standalone to be called when finder_ is NULL.
+const FieldDescriptor* DefaultFinderFindExtension(Message* message,
+ const string& name) {
+ return message->GetReflection()->FindKnownExtensionByName(name);
+}
+
+const Descriptor* DefaultFinderFindAnyType(const Message& message,
+ const string& prefix,
+ const string& name) {
+ if (prefix != internal::kTypeGoogleApisComPrefix &&
+ prefix != internal::kTypeGoogleProdComPrefix) {
+ return NULL;
+ }
+ return message.GetDescriptor()->file()->pool()->FindMessageTypeByName(name);
+}
+} // namespace
// ===========================================================================
// Internal class for parsing an ASCII representation of a Protocol Message.
@@ -217,7 +236,7 @@ class TextFormat::Parser::ParserImpl {
ParserImpl(const Descriptor* root_message_type,
io::ZeroCopyInputStream* input_stream,
io::ErrorCollector* error_collector,
- TextFormat::Finder* finder,
+ const TextFormat::Finder* finder,
ParseInfoTree* parse_info_tree,
SingularOverwritePolicy singular_overwrite_policy,
bool allow_case_insensitive_field,
@@ -380,9 +399,15 @@ class TextFormat::Parser::ParserImpl {
DO(Consume("]"));
TryConsume(":"); // ':' is optional between message labels and values.
string serialized_value;
- DO(ConsumeAnyValue(full_type_name,
- message->GetDescriptor()->file()->pool(),
- &serialized_value));
+ const Descriptor* value_descriptor =
+ finder_ ? finder_->FindAnyType(*message, prefix, full_type_name)
+ : DefaultFinderFindAnyType(*message, prefix, full_type_name);
+ if (value_descriptor == NULL) {
+ ReportError("Could not find type \"" + prefix + full_type_name +
+ "\" stored in google.protobuf.Any.");
+ return false;
+ }
+ DO(ConsumeAnyValue(value_descriptor, &serialized_value));
if (singular_overwrite_policy_ == FORBID_SINGULAR_OVERWRITES) {
// Fail if any_type_url_field has already been specified.
if ((!any_type_url_field->is_repeated() &&
@@ -404,9 +429,8 @@ class TextFormat::Parser::ParserImpl {
DO(ConsumeFullTypeName(&field_name));
DO(Consume("]"));
- field = (finder_ != NULL
- ? finder_->FindExtension(message, field_name)
- : reflection->FindKnownExtensionByName(field_name));
+ field = finder_ ? finder_->FindExtension(message, field_name)
+ : DefaultFinderFindExtension(message, field_name);
if (field == NULL) {
if (!allow_unknown_field_) {
@@ -572,12 +596,12 @@ label_skip_parsing:
// Skips the next field including the field's name and value.
bool SkipField() {
- string field_name;
if (TryConsume("[")) {
- // Extension name.
- DO(ConsumeFullTypeName(&field_name));
+ // Extension name or type URL.
+ DO(ConsumeTypeUrlOrFullTypeName());
DO(Consume("]"));
} else {
+ string field_name;
DO(ConsumeIdentifier(&field_name));
}
@@ -881,6 +905,15 @@ label_skip_parsing:
return true;
}
+ bool ConsumeTypeUrlOrFullTypeName() {
+ string discarded;
+ DO(ConsumeIdentifier(&discarded));
+ while (TryConsume(".") || TryConsume("/")) {
+ DO(ConsumeIdentifier(&discarded));
+ }
+ return true;
+ }
+
// Consumes a string and saves its value in the text parameter.
// Returns false if the token is not of type STRING.
bool ConsumeString(string* text) {
@@ -1029,44 +1062,29 @@ label_skip_parsing:
bool ConsumeAnyTypeUrl(string* full_type_name, string* prefix) {
// TODO(saito) Extend Consume() to consume multiple tokens at once, so that
// this code can be written as just DO(Consume(kGoogleApisTypePrefix)).
- string url1, url2, url3;
- DO(ConsumeIdentifier(&url1)); // type
- DO(Consume("."));
- DO(ConsumeIdentifier(&url2)); // googleapis
- DO(Consume("."));
- DO(ConsumeIdentifier(&url3)); // com
+ DO(ConsumeIdentifier(prefix));
+ while (TryConsume(".")) {
+ string url;
+ DO(ConsumeIdentifier(&url));
+ *prefix += "." + url;
+ }
DO(Consume("/"));
+ *prefix += "/";
DO(ConsumeFullTypeName(full_type_name));
- *prefix = url1 + "." + url2 + "." + url3 + "/";
- if (*prefix != internal::kTypeGoogleApisComPrefix &&
- *prefix != internal::kTypeGoogleProdComPrefix) {
- ReportError("TextFormat::Parser for Any supports only "
- "type.googleapis.com and type.googleprod.com, "
- "but found \"" + *prefix + "\"");
- return false;
- }
return true;
}
// A helper function for reconstructing Any::value. Consumes a text of
- // full_type_name, then serializes it into serialized_value. "pool" is used to
- // look up and create a temporary object with full_type_name.
- bool ConsumeAnyValue(const string& full_type_name, const DescriptorPool* pool,
+ // full_type_name, then serializes it into serialized_value.
+ bool ConsumeAnyValue(const Descriptor* value_descriptor,
string* serialized_value) {
- const Descriptor* value_descriptor =
- pool->FindMessageTypeByName(full_type_name);
- if (value_descriptor == NULL) {
- ReportError("Could not find type \"" + full_type_name +
- "\" stored in google.protobuf.Any.");
- return false;
- }
DynamicMessageFactory factory;
const Message* value_prototype = factory.GetPrototype(value_descriptor);
if (value_prototype == NULL) {
return false;
}
- google::protobuf::scoped_ptr<Message> value(value_prototype->New());
+ std::unique_ptr<Message> value(value_prototype->New());
string sub_delimiter;
DO(ConsumeMessageDelimiter(&sub_delimiter));
DO(ConsumeMessage(value.get(), sub_delimiter));
@@ -1076,7 +1094,7 @@ label_skip_parsing:
} else {
if (!value->IsInitialized()) {
ReportError(
- "Value of type \"" + full_type_name +
+ "Value of type \"" + value_descriptor->full_name() +
"\" stored in google.protobuf.Any has missing required fields");
return false;
}
@@ -1120,13 +1138,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);
}
@@ -1136,7 +1154,7 @@ label_skip_parsing:
};
io::ErrorCollector* error_collector_;
- TextFormat::Finder* finder_;
+ const TextFormat::Finder* finder_;
ParseInfoTree* parse_info_tree_;
ParserErrorCollector tokenizer_error_collector_;
io::Tokenizer tokenizer_;
@@ -1180,13 +1198,11 @@ class TextFormat::Printer::TextGenerator
// 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.
- void Indent() {
- ++indent_level_;
- }
+ void Indent() override { ++indent_level_; }
// Reduces the current indent level by two spaces, or crashes if the indent
// level is zero.
- void Outdent() {
+ void Outdent() override {
if (indent_level_ == 0 ||
indent_level_ < initial_indent_level_) {
GOOGLE_LOG(DFATAL) << " Outdent() without matching Indent().";
@@ -1197,7 +1213,7 @@ class TextFormat::Printer::TextGenerator
}
// Print text to the output stream.
- void Print(const char* text, size_t size) {
+ void Print(const char* text, size_t size) override {
if (indent_level_ > 0) {
size_t pos = 0; // The number of bytes we've written so far.
for (size_t i = 0; i < size; i++) {
@@ -1294,10 +1310,23 @@ class TextFormat::Printer::TextGenerator
};
// ===========================================================================
-
+// Implementation of the default Finder for extensions.
TextFormat::Finder::~Finder() {
}
+const FieldDescriptor* TextFormat::Finder::FindExtension(
+ Message* message, const string& name) const {
+ return DefaultFinderFindExtension(message, name);
+}
+
+const Descriptor* TextFormat::Finder::FindAnyType(const Message& message,
+ const string& prefix,
+ const string& name) const {
+ return DefaultFinderFindAnyType(message, prefix, name);
+}
+
+// ===========================================================================
+
TextFormat::Parser::Parser()
: error_collector_(NULL),
finder_(NULL),
@@ -1363,8 +1392,9 @@ bool TextFormat::Parser::MergeUsingImpl(io::ZeroCopyInputStream* /* input */,
if (!allow_partial_ && !output->IsInitialized()) {
std::vector<string> missing_fields;
output->FindInitializationErrors(&missing_fields);
- parser_impl->ReportError(-1, 0, "Message missing required fields: " +
- Join(missing_fields, ", "));
+ parser_impl->ReportError(-1, 0,
+ "Message missing required fields: " +
+ Join(missing_fields, ", "));
return false;
}
return true;
@@ -1414,7 +1444,7 @@ 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.
@@ -1553,6 +1583,12 @@ void TextFormat::FastFieldValuePrinter::PrintBytes(
PrintString(val, generator);
}
void TextFormat::FastFieldValuePrinter::PrintFieldName(
+ const Message& message, int field_index, int field_count,
+ const Reflection* reflection, const FieldDescriptor* field,
+ BaseTextGenerator* generator) const {
+ PrintFieldName(message, reflection, field, generator);
+}
+void TextFormat::FastFieldValuePrinter::PrintFieldName(
const Message& message, const Reflection* reflection,
const FieldDescriptor* field, BaseTextGenerator* generator) const {
if (field->is_extension()) {
@@ -1606,60 +1642,67 @@ 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, const Reflection* reflection,
+ 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));
+ }
+ void PrintFieldName(const Message& message, const Reflection* reflection,
+ const FieldDescriptor* field,
+ 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 {
+ 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 {
+ TextFormat::BaseTextGenerator* generator) const override {
generator->PrintString(delegate_->PrintMessageEnd(
message, field_index, field_count, single_line_mode));
}
private:
- google::protobuf::scoped_ptr<const TextFormat::FieldValuePrinter> delegate_;
+ std::unique_ptr<const TextFormat::FieldValuePrinter> delegate_;
};
// Our own specialization: for UTF8 escaped strings.
@@ -1667,13 +1710,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);
}
};
@@ -1688,12 +1731,14 @@ TextFormat::Printer::Printer()
hide_unknown_fields_(false),
print_message_fields_in_index_order_(false),
expand_any_(false),
- truncate_string_field_longer_than_(0LL) {
+ truncate_string_field_longer_than_(0LL),
+ finder_(NULL) {
SetUseUtf8StringEscaping(false);
}
TextFormat::Printer::~Printer() {
STLDeleteValues(&custom_printers_);
+ STLDeleteValues(&custom_message_printers_);
}
void TextFormat::Printer::SetUseUtf8StringEscaping(bool as_utf8) {
@@ -1718,7 +1763,7 @@ bool TextFormat::Printer::RegisterFieldValuePrinter(
return false;
}
FieldValuePrinterWrapper* const wrapper =
- new FieldValuePrinterWrapper(NULL);
+ new FieldValuePrinterWrapper(nullptr);
if (custom_printers_.insert(std::make_pair(field, wrapper)).second) {
wrapper->SetDelegate(printer);
return true;
@@ -1734,6 +1779,13 @@ bool TextFormat::Printer::RegisterFieldValuePrinter(
custom_printers_.insert(std::make_pair(field, printer)).second;
}
+bool TextFormat::Printer::RegisterMessagePrinter(
+ const Descriptor* descriptor, const MessagePrinter* printer) {
+ return descriptor != nullptr && printer != nullptr &&
+ custom_message_printers_.insert(std::make_pair(descriptor, printer))
+ .second;
+}
+
bool TextFormat::Printer::PrintToString(const Message& message,
string* output) const {
GOOGLE_DCHECK(output) << "output specified is NULL";
@@ -1777,10 +1829,19 @@ bool TextFormat::Printer::PrintUnknownFields(
namespace {
// Comparison functor for sorting FieldDescriptors by field index.
+// Normal fields have higher precedence than extensions.
struct FieldIndexSorter {
bool operator()(const FieldDescriptor* left,
const FieldDescriptor* right) const {
- return left->index() < right->index();
+ if (left->is_extension() && right->is_extension()) {
+ return left->number() < right->number();
+ } else if (left->is_extension()) {
+ return false;
+ } else if (right->is_extension()) {
+ return true;
+ } else {
+ return left->index() < right->index();
+ }
}
};
@@ -1799,21 +1860,22 @@ bool TextFormat::Printer::PrintAny(const Message& message,
// Extract the full type name from the type_url field.
const string& type_url = reflection->GetString(message, type_url_field);
+ string url_prefix;
string full_type_name;
- if (!internal::ParseAnyTypeUrl(type_url, &full_type_name)) {
+ if (!internal::ParseAnyTypeUrl(type_url, &url_prefix, &full_type_name)) {
return false;
}
// Print the "value" in text.
const google::protobuf::Descriptor* value_descriptor =
- message.GetDescriptor()->file()->pool()->FindMessageTypeByName(
- full_type_name);
+ finder_ ? finder_->FindAnyType(message, url_prefix, full_type_name)
+ : DefaultFinderFindAnyType(message, url_prefix, full_type_name);
if (value_descriptor == NULL) {
GOOGLE_LOG(WARNING) << "Proto type " << type_url << " not found";
return false;
}
DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<google::protobuf::Message> value_message(
+ std::unique_ptr<google::protobuf::Message> value_message(
factory.GetPrototype(value_descriptor)->New());
string serialized_value = reflection->GetString(message, value_field);
if (!value_message->ParseFromString(serialized_value)) {
@@ -1836,6 +1898,11 @@ bool TextFormat::Printer::PrintAny(const Message& message,
void TextFormat::Printer::Print(const Message& message,
TextGenerator* generator) const {
const Descriptor* descriptor = message.GetDescriptor();
+ auto itr = custom_message_printers_.find(descriptor);
+ if (itr != custom_message_printers_.end()) {
+ itr->second->Print(message, single_line_mode_, generator);
+ return;
+ }
const Reflection* reflection = message.GetReflection();
if (descriptor->full_name() == internal::kAnyFullTypeName && expand_any_ &&
PrintAny(message, generator)) {
@@ -1859,7 +1926,6 @@ void TextFormat::Printer::PrintFieldValueToString(
const FieldDescriptor* field,
int index,
string* output) const {
-
GOOGLE_DCHECK(output) << "output specified is NULL";
output->clear();
@@ -1898,7 +1964,7 @@ void TextFormat::Printer::PrintField(const Message& message,
for (int j = 0; j < count; ++j) {
const int field_index = field->is_repeated() ? j : -1;
- PrintFieldName(message, reflection, field, generator);
+ PrintFieldName(message, field_index, count, reflection, field, generator);
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
const FastFieldValuePrinter* printer = FindWithDefault(
@@ -1932,9 +1998,9 @@ void TextFormat::Printer::PrintShortRepeatedField(
const Message& message, const Reflection* reflection,
const FieldDescriptor* field, TextGenerator* generator) const {
// Print primitive repeated field in short form.
- PrintFieldName(message, reflection, field, generator);
-
int size = reflection->FieldSize(message, field);
+ PrintFieldName(message, /*field_index=*/-1, /*field_count=*/size, reflection,
+ field, generator);
generator->PrintLiteral(": [");
for (int i = 0; i < size; i++) {
if (i > 0) generator->PrintLiteral(", ");
@@ -1948,6 +2014,7 @@ void TextFormat::Printer::PrintShortRepeatedField(
}
void TextFormat::Printer::PrintFieldName(const Message& message,
+ int field_index, int field_count,
const Reflection* reflection,
const FieldDescriptor* field,
TextGenerator* generator) const {
@@ -1960,7 +2027,8 @@ void TextFormat::Printer::PrintFieldName(const Message& message,
const FastFieldValuePrinter* printer = FindWithDefault(
custom_printers_, field, default_field_value_printer_.get());
- printer->PrintFieldName(message, reflection, field, generator);
+ printer->PrintFieldName(message, field_index, field_count, reflection, field,
+ generator);
}
void TextFormat::Printer::PrintFieldValue(const Message& message,
diff --git a/src/google/protobuf/text_format.h b/src/google/protobuf/text_format.h
index a2670d6b..d6f3e16b 100644
--- a/src/google/protobuf/text_format.h
+++ b/src/google/protobuf/text_format.h
@@ -40,9 +40,6 @@
#include <map>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
#include <vector>
@@ -97,6 +94,10 @@ class LIBPROTOBUF_EXPORT TextFormat {
class LIBPROTOBUF_EXPORT BaseTextGenerator {
public:
virtual ~BaseTextGenerator();
+
+ virtual void Indent() {}
+ virtual void Outdent() {}
+
// Print text to the output stream.
virtual void Print(const char* text, size_t size) = 0;
@@ -129,6 +130,10 @@ class LIBPROTOBUF_EXPORT TextFormat {
BaseTextGenerator* generator) const;
virtual void PrintEnum(int32 val, const string& name,
BaseTextGenerator* generator) const;
+ virtual void PrintFieldName(const Message& message, int field_index,
+ int field_count, const Reflection* reflection,
+ const FieldDescriptor* field,
+ BaseTextGenerator* generator) const;
virtual void PrintFieldName(const Message& message,
const Reflection* reflection,
const FieldDescriptor* field,
@@ -176,6 +181,40 @@ class LIBPROTOBUF_EXPORT TextFormat {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldValuePrinter);
};
+ class LIBPROTOBUF_EXPORT MessagePrinter {
+ public:
+ MessagePrinter() {}
+ virtual ~MessagePrinter() {}
+ virtual void Print(const Message& message, bool single_line_mode,
+ BaseTextGenerator* generator) const = 0;
+
+ private:
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessagePrinter);
+ };
+
+ // Interface that Printers or Parsers can use to find extensions, or types
+ // referenced in Any messages.
+ class LIBPROTOBUF_EXPORT Finder {
+ public:
+ virtual ~Finder();
+
+ // Try to find an extension of *message by fully-qualified field
+ // name. Returns NULL if no extension is known for this name or number.
+ // The base implementation uses the extensions already known by the message.
+ virtual const FieldDescriptor* FindExtension(
+ Message* message,
+ const string& name) const;
+
+ // Find the message type for an Any proto.
+ // Returns NULL if no message is known for this name.
+ // The base implementation only accepts prefixes of type.googleprod.com/ or
+ // 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;
+ };
+
// Class for those users which require more fine-grained control over how
// a protobuffer message is printed out.
class LIBPROTOBUF_EXPORT Printer {
@@ -251,9 +290,11 @@ class LIBPROTOBUF_EXPORT TextFormat {
hide_unknown_fields_ = hide;
}
- // If print_message_fields_in_index_order is true, print fields of a proto
- // message using the order defined in source code instead of the field
- // number. By default, use the field number order.
+ // If print_message_fields_in_index_order is true, fields of a proto message
+ // will be printed using the order defined in source code instead of the
+ // field number, extensions will be printed at the end of the message
+ // and their relative order is determined by the extension number.
+ // By default, use the field number order.
void SetPrintMessageFieldsInIndexOrder(
bool print_message_fields_in_index_order) {
print_message_fields_in_index_order_ =
@@ -271,6 +312,11 @@ class LIBPROTOBUF_EXPORT TextFormat {
expand_any_ = expand;
}
+ // Set how parser finds message for Any payloads.
+ void SetFinder(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,
// e.g., dump of encoded image file.
@@ -293,6 +339,13 @@ class LIBPROTOBUF_EXPORT TextFormat {
bool RegisterFieldValuePrinter(const FieldDescriptor* field,
const FastFieldValuePrinter* printer);
+ // Register a custom message-specific MessagePrinter for messages with a
+ // particular Descriptor.
+ // Returns "true" if the registration succeeded, or "false" if there is
+ // already a printer for that Descriptor.
+ bool RegisterMessagePrinter(const Descriptor* descriptor,
+ const MessagePrinter* printer);
+
private:
// Forward declaration of an internal class used to print the text
// output to the OutputStream (see text_format.cc for implementation).
@@ -315,7 +368,8 @@ class LIBPROTOBUF_EXPORT TextFormat {
// Print the name of a field -- i.e. everything that comes before the
// ':' for a single name/value pair.
- void PrintFieldName(const Message& message, const Reflection* reflection,
+ void PrintFieldName(const Message& message, int field_index,
+ int field_count, const Reflection* reflection,
const FieldDescriptor* field,
TextGenerator* generator) const;
@@ -349,10 +403,16 @@ class LIBPROTOBUF_EXPORT TextFormat {
int64 truncate_string_field_longer_than_;
- google::protobuf::scoped_ptr<const FastFieldValuePrinter> default_field_value_printer_;
+ std::unique_ptr<const FastFieldValuePrinter> default_field_value_printer_;
typedef std::map<const FieldDescriptor*, const FastFieldValuePrinter*>
CustomPrinterMap;
CustomPrinterMap custom_printers_;
+
+ typedef std::map<const Descriptor*, const MessagePrinter*>
+ CustomMessagePrinterMap;
+ CustomMessagePrinterMap custom_message_printers_;
+
+ const Finder* finder_;
};
// Parses a text-format protocol message from the given input stream to
@@ -387,20 +447,6 @@ class LIBPROTOBUF_EXPORT TextFormat {
const FieldDescriptor* field,
Message* message);
- // Interface that TextFormat::Parser can use to find extensions.
- // This class may be extended in the future to find more information
- // like fields, etc.
- class LIBPROTOBUF_EXPORT Finder {
- public:
- virtual ~Finder();
-
- // Try to find an extension of *message by fully-qualified field
- // name. Returns NULL if no extension is known for this name or number.
- virtual const FieldDescriptor* FindExtension(
- Message* message,
- const string& name) const = 0;
- };
-
// A location in the parsed text.
struct ParseLocation {
int line;
@@ -524,7 +570,7 @@ class LIBPROTOBUF_EXPORT TextFormat {
ParserImpl* parser_impl);
io::ErrorCollector* error_collector_;
- Finder* finder_;
+ const Finder* finder_;
ParseInfoTree* parse_info_tree_;
bool allow_partial_;
bool allow_case_insensitive_field_;
diff --git a/src/google/protobuf/text_format_unittest.cc b/src/google/protobuf/text_format_unittest.cc
index f823bcb2..53184130 100644
--- a/src/google/protobuf/text_format_unittest.cc
+++ b/src/google/protobuf/text_format_unittest.cc
@@ -38,9 +38,6 @@
#include <stdlib.h>
#include <limits>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -474,14 +471,14 @@ TEST_F(TextFormatTest, ErrorCasesRegisteringFieldValuePrinterShouldFail) {
// NULL printer.
EXPECT_FALSE(printer.RegisterFieldValuePrinter(
message.GetDescriptor()->FindFieldByName("optional_int32"),
- static_cast<const TextFormat::FieldValuePrinter*>(NULL)));
+ static_cast<const TextFormat::FieldValuePrinter*>(nullptr)));
EXPECT_FALSE(printer.RegisterFieldValuePrinter(
message.GetDescriptor()->FindFieldByName("optional_int32"),
- static_cast<const TextFormat::FastFieldValuePrinter*>(NULL)));
+ static_cast<const TextFormat::FastFieldValuePrinter*>(nullptr)));
// Because registration fails, the ownership of this printer is never taken.
TextFormat::FieldValuePrinter my_field_printer;
// NULL field
- EXPECT_FALSE(printer.RegisterFieldValuePrinter(NULL, &my_field_printer));
+ EXPECT_FALSE(printer.RegisterFieldValuePrinter(nullptr, &my_field_printer));
}
class CustomMessageFieldValuePrinter : public TextFormat::FieldValuePrinter {
@@ -564,6 +561,148 @@ TEST_F(TextFormatTest, CustomPrinterForMultilineComments) {
text);
}
+// Achieve effects similar to SetUseShortRepeatedPrimitives for messages, using
+// RegisterFieldValuePrinter. Use this to test the version of PrintFieldName
+// that accepts repeated field index and count.
+class CompactRepeatedFieldPrinter : public TextFormat::FastFieldValuePrinter {
+ public:
+ void PrintFieldName(const Message& message, int field_index, int field_count,
+ const Reflection* reflection,
+ const FieldDescriptor* field,
+ TextFormat::BaseTextGenerator* generator) const override {
+ if (field_index == 0 || field_index == -1) {
+ 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,
+ TextFormat::BaseTextGenerator* generator) const override {
+ if (field_index == 0 || field_index == -1) {
+ if (single_line_mode) {
+ generator->PrintLiteral(" { ");
+ } else {
+ generator->PrintLiteral(" {\n");
+ }
+ }
+ }
+ void PrintMessageEnd(
+ const Message& message, int field_index, int field_count,
+ bool single_line_mode,
+ TextFormat::BaseTextGenerator* generator) const override {
+ if (field_index == field_count - 1 || field_index == -1) {
+ if (single_line_mode) {
+ generator->PrintLiteral("} ");
+ } else {
+ generator->PrintLiteral("}\n");
+ }
+ }
+ }
+};
+
+TEST_F(TextFormatTest, CompactRepeatedFieldPrinter) {
+ TextFormat::Printer printer;
+ ASSERT_TRUE(printer.RegisterFieldValuePrinter(
+ unittest::TestAllTypes::default_instance()
+ .descriptor()
+ ->FindFieldByNumber(
+ unittest::TestAllTypes::kRepeatedNestedMessageFieldNumber),
+ new CompactRepeatedFieldPrinter));
+
+ protobuf_unittest::TestAllTypes message;
+ message.add_repeated_nested_message()->set_bb(1);
+ message.add_repeated_nested_message()->set_bb(2);
+ message.add_repeated_nested_message()->set_bb(3);
+
+ string text;
+ ASSERT_TRUE(printer.PrintToString(message, &text));
+ EXPECT_EQ(
+ "repeated_nested_message {\n"
+ " bb: 1\n"
+ " bb: 2\n"
+ " bb: 3\n"
+ "}\n",
+ text);
+}
+
+// Print strings into multiple line, with indention. Use this to test
+// BaseTextGenerator::Indent and BaseTextGenerator::Outdent.
+class MultilineStringPrinter : public TextFormat::FastFieldValuePrinter {
+ public:
+ void PrintString(const string& val,
+ TextFormat::BaseTextGenerator* generator) const override {
+ generator->Indent();
+ int last_pos = 0;
+ int newline_pos = val.find('\n');
+ while (newline_pos != string::npos) {
+ generator->PrintLiteral("\n");
+ TextFormat::FastFieldValuePrinter::PrintString(
+ val.substr(last_pos, newline_pos + 1 - last_pos), generator);
+ last_pos = newline_pos + 1;
+ newline_pos = val.find('\n', last_pos);
+ }
+ if (last_pos < val.size()) {
+ generator->PrintLiteral("\n");
+ TextFormat::FastFieldValuePrinter::PrintString(val.substr(last_pos),
+ generator);
+ }
+ generator->Outdent();
+ }
+};
+
+TEST_F(TextFormatTest, MultilineStringPrinter) {
+ TextFormat::Printer printer;
+ ASSERT_TRUE(printer.RegisterFieldValuePrinter(
+ unittest::TestAllTypes::default_instance()
+ .descriptor()
+ ->FindFieldByNumber(
+ unittest::TestAllTypes::kOptionalStringFieldNumber),
+ new MultilineStringPrinter));
+
+ protobuf_unittest::TestAllTypes message;
+ message.set_optional_string("first line\nsecond line\nthird line");
+
+ string text;
+ ASSERT_TRUE(printer.PrintToString(message, &text));
+ EXPECT_EQ(
+ "optional_string: \n"
+ " \"first line\\n\"\n"
+ " \"second line\\n\"\n"
+ " \"third line\"\n",
+ text);
+}
+
+class CustomNestedMessagePrinter : public TextFormat::MessagePrinter {
+ public:
+ CustomNestedMessagePrinter() {}
+ ~CustomNestedMessagePrinter() override {}
+ void Print(const Message& message, bool single_line_mode,
+ TextFormat::BaseTextGenerator* generator) const override {
+ generator->PrintLiteral("custom");
+ }
+};
+
+TEST_F(TextFormatTest, CustomMessagePrinter) {
+ TextFormat::Printer printer;
+ printer.RegisterMessagePrinter(
+ unittest::TestAllTypes::NestedMessage::default_instance().descriptor(),
+ new CustomNestedMessagePrinter);
+
+ unittest::TestAllTypes message;
+ string text;
+ EXPECT_TRUE(printer.PrintToString(message, &text));
+ EXPECT_EQ("", text);
+
+ message.mutable_optional_nested_message()->set_bb(1);
+ EXPECT_TRUE(printer.PrintToString(message, &text));
+ EXPECT_EQ("optional_nested_message {\n custom}\n", text);
+}
+
TEST_F(TextFormatTest, ParseBasic) {
io::ArrayInputStream input_stream(proto_debug_string_.data(),
proto_debug_string_.size());
@@ -1031,29 +1170,93 @@ TEST_F(TextFormatTest, ParseExotic) {
TEST_F(TextFormatTest, PrintFieldsInIndexOrder) {
protobuf_unittest::TestFieldOrderings message;
// Fields are listed in index order instead of field number.
- message.set_my_string("Test String"); // Field number 11
+ message.set_my_string("str"); // Field number 11
message.set_my_int(12345); // Field number 1
message.set_my_float(0.999); // Field number 101
+ // Extensions are listed based on the order of extension number.
+ // Extension number 12.
+ message
+ .MutableExtension(
+ protobuf_unittest::TestExtensionOrderings2::test_ext_orderings2)
+ ->set_my_string("ext_str2");
+ // Extension number 13.
+ message
+ .MutableExtension(
+ protobuf_unittest::TestExtensionOrderings1::test_ext_orderings1)
+ ->set_my_string("ext_str1");
+ // Extension number 14.
+ message
+ .MutableExtension(protobuf_unittest::TestExtensionOrderings2::
+ TestExtensionOrderings3::test_ext_orderings3)
+ ->set_my_string("ext_str3");
+ // Extension number 50.
+ *message.MutableExtension(protobuf_unittest::my_extension_string) = "ext_str0";
+
TextFormat::Printer printer;
string text;
// By default, print in field number order.
+ // my_int: 12345
+ // my_string: "str"
+ // [protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] {
+ // my_string: "ext_str2"
+ // }
+ // [protobuf_unittest.TestExtensionOrderings1.test_ext_orderings1] {
+ // my_string: "ext_str1"
+ // }
+ // [protobuf_unittest.TestExtensionOrderings2.TestExtensionOrderings3.test_ext_orderings3]
+ // {
+ // my_string: "ext_str3"
+ // }
+ // [protobuf_unittest.my_extension_string]: "ext_str0"
+ // my_float: 0.999
printer.PrintToString(message, &text);
- EXPECT_EQ("my_int: 12345\nmy_string: \"Test String\"\nmy_float: 0.999\n",
- text);
+ EXPECT_EQ(
+ "my_int: 12345\nmy_string: "
+ "\"str\"\n[protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] "
+ "{\n my_string: "
+ "\"ext_str2\"\n}\n[protobuf_unittest.TestExtensionOrderings1.test_ext_"
+ "orderings1] {\n my_string: "
+ "\"ext_str1\"\n}\n[protobuf_unittest.TestExtensionOrderings2."
+ "TestExtensionOrderings3.test_ext_orderings3] {\n my_string: "
+ "\"ext_str3\"\n}\n[protobuf_unittest.my_extension_string]: "
+ "\"ext_str0\"\nmy_float: 0.999\n",
+ text);
// Print in index order.
+ // my_string: "str"
+ // my_int: 12345
+ // my_float: 0.999
+ // [protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] {
+ // my_string: "ext_str2"
+ // }
+ // [protobuf_unittest.TestExtensionOrderings1.test_ext_orderings1] {
+ // my_string: "ext_str1"
+ // }
+ // [protobuf_unittest.TestExtensionOrderings2.TestExtensionOrderings3.test_ext_orderings3]
+ // {
+ // my_string: "ext_str3"
+ // }
+ // [protobuf_unittest.my_extension_string]: "ext_str0"
printer.SetPrintMessageFieldsInIndexOrder(true);
printer.PrintToString(message, &text);
- EXPECT_EQ("my_string: \"Test String\"\nmy_int: 12345\nmy_float: 0.999\n",
- text);
+ EXPECT_EQ(
+ "my_string: \"str\"\nmy_int: 12345\nmy_float: "
+ "0.999\n[protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] "
+ "{\n my_string: "
+ "\"ext_str2\"\n}\n[protobuf_unittest.TestExtensionOrderings1.test_ext_"
+ "orderings1] {\n my_string: "
+ "\"ext_str1\"\n}\n[protobuf_unittest.TestExtensionOrderings2."
+ "TestExtensionOrderings3.test_ext_orderings3] {\n my_string: "
+ "\"ext_str3\"\n}\n[protobuf_unittest.my_extension_string]: \"ext_str0\"\n",
+ text);
}
class TextFormatParserTest : public testing::Test {
protected:
void ExpectFailure(const string& input, const string& message, int line,
int col) {
- google::protobuf::scoped_ptr<unittest::TestAllTypes> proto(new unittest::TestAllTypes);
+ std::unique_ptr<unittest::TestAllTypes> proto(new unittest::TestAllTypes);
ExpectFailure(input, message, line, col, proto.get());
}
@@ -1114,7 +1317,7 @@ class TextFormatParserTest : public testing::Test {
};
TEST_F(TextFormatParserTest, ParseInfoTreeBuilding) {
- google::protobuf::scoped_ptr<unittest::TestAllTypes> message(new unittest::TestAllTypes);
+ std::unique_ptr<unittest::TestAllTypes> message(new unittest::TestAllTypes);
const Descriptor* d = message->GetDescriptor();
string stringData =
@@ -1179,7 +1382,7 @@ TEST_F(TextFormatParserTest, ParseInfoTreeBuilding) {
}
TEST_F(TextFormatParserTest, ParseFieldValueFromString) {
- google::protobuf::scoped_ptr<unittest::TestAllTypes> message(new unittest::TestAllTypes);
+ std::unique_ptr<unittest::TestAllTypes> message(new unittest::TestAllTypes);
const Descriptor* d = message->GetDescriptor();
#define EXPECT_FIELD(name, value, valuestring) \
diff --git a/src/google/protobuf/timestamp.pb.cc b/src/google/protobuf/timestamp.pb.cc
index f57d4d66..4269031f 100644
--- a/src/google/protobuf/timestamp.pb.cc
+++ b/src/google/protobuf/timestamp.pb.cc
@@ -7,7 +7,6 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
@@ -19,6 +18,7 @@
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
+
namespace google {
namespace protobuf {
class TimestampDefaultTypeInternal {
@@ -29,14 +29,9 @@ class TimestampDefaultTypeInternal {
} // namespace protobuf
} // namespace google
namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto {
-void InitDefaultsTimestampImpl() {
+static void InitDefaultsTimestamp() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_Timestamp_default_instance_;
new (ptr) ::google::protobuf::Timestamp();
@@ -45,9 +40,11 @@ void InitDefaultsTimestampImpl() {
::google::protobuf::Timestamp::InitAsDefaultInstance();
}
-void InitDefaultsTimestamp() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsTimestampImpl);
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Timestamp =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsTimestamp}, {}};
+
+void InitDefaults() {
+ ::google::protobuf::internal::InitSCC(&scc_info_Timestamp.base);
}
::google::protobuf::Metadata file_level_metadata[1];
@@ -69,17 +66,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Timestamp_default_instance_),
};
-void protobuf_AssignDescriptors() {
+static void protobuf_AssignDescriptors() {
AddDescriptors();
- ::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/timestamp.proto", schemas, file_default_instances, TableStruct::offsets, factory,
+ "google/protobuf/timestamp.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
-void protobuf_AssignDescriptorsOnce() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
+static 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;
@@ -88,7 +84,7 @@ void protobuf_RegisterTypes(const ::std::string&) {
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
-void AddDescriptorsImpl() {
+static void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\037google/protobuf/timestamp.proto\022\017googl"
@@ -105,8 +101,8 @@ void AddDescriptorsImpl() {
}
void AddDescriptors() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
+ 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 {
@@ -129,24 +125,22 @@ const int Timestamp::kNanosFieldNumber;
Timestamp::Timestamp()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestamp();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestamp();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftimestamp_2eproto::scc_info_Timestamp.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Timestamp)
}
Timestamp::Timestamp(const Timestamp& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&seconds_, &from.seconds_,
static_cast<size_t>(reinterpret_cast<char*>(&nanos_) -
@@ -158,7 +152,6 @@ void Timestamp::SharedCtor() {
::memset(&seconds_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&nanos_) -
reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_));
- _cached_size_ = 0;
}
Timestamp::~Timestamp() {
@@ -174,12 +167,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Timestamp::descriptor() {
::protobuf_google_2fprotobuf_2ftimestamp_2eproto::protobuf_AssignDescriptorsOnce();
@@ -187,7 +178,7 @@ const ::google::protobuf::Descriptor* Timestamp::descriptor() {
}
const Timestamp& Timestamp::default_instance() {
- ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestamp();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftimestamp_2eproto::scc_info_Timestamp.base);
return *internal_default_instance();
}
@@ -210,7 +201,7 @@ bool Timestamp::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Timestamp)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -334,9 +325,7 @@ size_t Timestamp::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -412,7 +401,6 @@ void Timestamp::InternalSwap(Timestamp* other) {
swap(seconds_, other->seconds_);
swap(nanos_, other->nanos_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Timestamp::GetMetadata() const {
@@ -426,7 +414,7 @@ void Timestamp::InternalSwap(Timestamp* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Timestamp* Arena::CreateMessage< ::google::protobuf::Timestamp >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Timestamp* Arena::CreateMaybeMessage< ::google::protobuf::Timestamp >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Timestamp >(arena);
}
} // namespace protobuf
diff --git a/src/google/protobuf/timestamp.pb.h b/src/google/protobuf/timestamp.pb.h
index a0f9605c..daea80f6 100644
--- a/src/google/protobuf/timestamp.pb.h
+++ b/src/google/protobuf/timestamp.pb.h
@@ -1,19 +1,19 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/timestamp.proto
-#ifndef PROTOBUF_google_2fprotobuf_2ftimestamp_2eproto_INCLUDED
-#define PROTOBUF_google_2fprotobuf_2ftimestamp_2eproto_INCLUDED
+#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto
+#define PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3005000
+#if GOOGLE_PROTOBUF_VERSION < 3006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3005001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -24,12 +24,14 @@
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
+#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftimestamp_2eproto LIBPROTOBUF_EXPORT
namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto {
// Internal implementation detail -- do not use these members.
@@ -42,11 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::uint32 offsets[];
};
void LIBPROTOBUF_EXPORT AddDescriptors();
-void LIBPROTOBUF_EXPORT InitDefaultsTimestampImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsTimestamp();
-inline void LIBPROTOBUF_EXPORT InitDefaults() {
- InitDefaultsTimestamp();
-}
} // namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto
namespace google {
namespace protobuf {
@@ -57,7 +54,7 @@ LIBPROTOBUF_EXPORT extern TimestampDefaultTypeInternal _Timestamp_default_instan
} // namespace google
namespace google {
namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Timestamp* Arena::CreateMessage< ::google::protobuf::Timestamp>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Timestamp* Arena::CreateMaybeMessage<::google::protobuf::Timestamp>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -91,10 +88,10 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -105,7 +102,7 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
return reinterpret_cast<const Timestamp*>(
&_Timestamp_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
0;
void UnsafeArenaSwap(Timestamp* other);
@@ -116,32 +113,33 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
// implements Message ----------------------------------------------
- inline Timestamp* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Timestamp>(NULL);
+ inline Timestamp* New() const final {
+ return CreateMaybeMessage<Timestamp>(NULL);
}
- Timestamp* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Timestamp>(arena);
+ Timestamp* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Timestamp>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Timestamp& from);
void MergeFrom(const Timestamp& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Timestamp* other);
protected:
explicit Timestamp(::google::protobuf::Arena* arena);
@@ -157,7 +155,7 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -184,9 +182,8 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
typedef void DestructorSkippable_;
::google::protobuf::int64 seconds_;
::google::protobuf::int32 nanos_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestampImpl();
};
// ===================================================================
@@ -238,4 +235,4 @@ inline void Timestamp::set_nanos(::google::protobuf::int32 value) {
// @@protoc_insertion_point(global_scope)
-#endif // PROTOBUF_google_2fprotobuf_2ftimestamp_2eproto_INCLUDED
+#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto
diff --git a/src/google/protobuf/type.pb.cc b/src/google/protobuf/type.pb.cc
index a2edabb6..72679df8 100644
--- a/src/google/protobuf/type.pb.cc
+++ b/src/google/protobuf/type.pb.cc
@@ -7,7 +7,6 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
@@ -19,6 +18,18 @@
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
+
+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
namespace google {
namespace protobuf {
class TypeDefaultTypeInternal {
@@ -49,17 +60,9 @@ class OptionDefaultTypeInternal {
} // namespace protobuf
} // namespace google
namespace protobuf_google_2fprotobuf_2ftype_2eproto {
-void InitDefaultsTypeImpl() {
+static void InitDefaultsType() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField();
- protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
- protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext();
{
void* ptr = &::google::protobuf::_Type_default_instance_;
new (ptr) ::google::protobuf::Type();
@@ -68,20 +71,15 @@ void InitDefaultsTypeImpl() {
::google::protobuf::Type::InitAsDefaultInstance();
}
-void InitDefaultsType() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsTypeImpl);
-}
+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,}};
-void InitDefaultsFieldImpl() {
+static void InitDefaultsField() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
{
void* ptr = &::google::protobuf::_Field_default_instance_;
new (ptr) ::google::protobuf::Field();
@@ -90,22 +88,13 @@ void InitDefaultsFieldImpl() {
::google::protobuf::Field::InitAsDefaultInstance();
}
-void InitDefaultsField() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldImpl);
-}
+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,}};
-void InitDefaultsEnumImpl() {
+static void InitDefaultsEnum() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue();
- protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
- protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext();
{
void* ptr = &::google::protobuf::_Enum_default_instance_;
new (ptr) ::google::protobuf::Enum();
@@ -114,20 +103,15 @@ void InitDefaultsEnumImpl() {
::google::protobuf::Enum::InitAsDefaultInstance();
}
-void InitDefaultsEnum() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumImpl);
-}
+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,}};
-void InitDefaultsEnumValueImpl() {
+static void InitDefaultsEnumValue() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
{
void* ptr = &::google::protobuf::_EnumValue_default_instance_;
new (ptr) ::google::protobuf::EnumValue();
@@ -136,20 +120,13 @@ void InitDefaultsEnumValueImpl() {
::google::protobuf::EnumValue::InitAsDefaultInstance();
}
-void InitDefaultsEnumValue() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumValueImpl);
-}
+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,}};
-void InitDefaultsOptionImpl() {
+static void InitDefaultsOption() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny();
{
void* ptr = &::google::protobuf::_Option_default_instance_;
new (ptr) ::google::protobuf::Option();
@@ -158,9 +135,16 @@ void InitDefaultsOptionImpl() {
::google::protobuf::Option::InitAsDefaultInstance();
}
-void InitDefaultsOption() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsOptionImpl);
+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,}};
+
+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);
}
::google::protobuf::Metadata file_level_metadata[5];
@@ -235,17 +219,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Option_default_instance_),
};
-void protobuf_AssignDescriptors() {
+static void protobuf_AssignDescriptors() {
AddDescriptors();
- ::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/type.proto", schemas, file_default_instances, TableStruct::offsets, factory,
+ "google/protobuf/type.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, file_level_enum_descriptors, NULL);
}
-void protobuf_AssignDescriptorsOnce() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
+static 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;
@@ -254,7 +237,7 @@ void protobuf_RegisterTypes(const ::std::string&) {
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 5);
}
-void AddDescriptorsImpl() {
+static void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\032google/protobuf/type.proto\022\017google.pro"
@@ -307,8 +290,8 @@ void AddDescriptorsImpl() {
}
void AddDescriptors() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
+ 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 {
@@ -450,9 +433,8 @@ const int Type::kSyntaxFieldNumber;
Type::Type()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsType();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Type.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Type)
}
@@ -462,7 +444,7 @@ Type::Type(::google::protobuf::Arena* arena)
fields_(arena),
oneofs_(arena),
options_(arena) {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsType();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Type.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Type)
@@ -472,8 +454,7 @@ Type::Type(const Type& from)
_internal_metadata_(NULL),
fields_(from.fields_),
oneofs_(from.oneofs_),
- options_(from.options_),
- _cached_size_(0) {
+ options_(from.options_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
@@ -494,7 +475,6 @@ void Type::SharedCtor() {
::memset(&source_context_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&syntax_) -
reinterpret_cast<char*>(&source_context_)) + sizeof(syntax_));
- _cached_size_ = 0;
}
Type::~Type() {
@@ -512,12 +492,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Type::descriptor() {
::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
@@ -525,7 +503,7 @@ const ::google::protobuf::Descriptor* Type::descriptor() {
}
const Type& Type::default_instance() {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsType();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Type.base);
return *internal_default_instance();
}
@@ -554,7 +532,7 @@ bool Type::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Type)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -631,7 +609,7 @@ bool Type::MergePartialFromCodedStream(
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) {
- int value;
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -709,7 +687,7 @@ void Type::SerializeWithCachedSizes(
// .google.protobuf.SourceContext source_context = 5;
if (this->has_source_context()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 5, *source_context_, output);
+ 5, this->_internal_source_context(), output);
}
// .google.protobuf.Syntax syntax = 6;
@@ -773,7 +751,7 @@ void Type::SerializeWithCachedSizes(
if (this->has_source_context()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 5, *source_context_, deterministic, target);
+ 5, this->_internal_source_context(), deterministic, target);
}
// .google.protobuf.Syntax syntax = 6;
@@ -850,9 +828,7 @@ size_t Type::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -934,11 +910,11 @@ void Type::InternalSwap(Type* other) {
CastToBase(&fields_)->InternalSwap(CastToBase(&other->fields_));
oneofs_.InternalSwap(CastToBase(&other->oneofs_));
CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
- name_.Swap(&other->name_);
+ 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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Type::GetMetadata() const {
@@ -966,9 +942,8 @@ const int Field::kDefaultValueFieldNumber;
Field::Field()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Field.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Field)
}
@@ -976,7 +951,7 @@ Field::Field(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
options_(arena) {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Field.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Field)
@@ -984,8 +959,7 @@ Field::Field(::google::protobuf::Arena* arena)
Field::Field(const Field& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- options_(from.options_),
- _cached_size_(0) {
+ options_(from.options_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
@@ -1021,7 +995,6 @@ void Field::SharedCtor() {
::memset(&kind_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&packed_) -
reinterpret_cast<char*>(&kind_)) + sizeof(packed_));
- _cached_size_ = 0;
}
Field::~Field() {
@@ -1041,12 +1014,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Field::descriptor() {
::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
@@ -1054,7 +1025,7 @@ const ::google::protobuf::Descriptor* Field::descriptor() {
}
const Field& Field::default_instance() {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Field.base);
return *internal_default_instance();
}
@@ -1082,7 +1053,7 @@ bool Field::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Field)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -1090,7 +1061,7 @@ bool Field::MergePartialFromCodedStream(
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
- int value;
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -1105,7 +1076,7 @@ bool Field::MergePartialFromCodedStream(
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
- int value;
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -1517,9 +1488,7 @@ size_t Field::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -1615,17 +1584,20 @@ void Field::UnsafeArenaSwap(Field* other) {
void Field::InternalSwap(Field* other) {
using std::swap;
CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
- name_.Swap(&other->name_);
- type_url_.Swap(&other->type_url_);
- json_name_.Swap(&other->json_name_);
- default_value_.Swap(&other->default_value_);
+ name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ type_url_.Swap(&other->type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ json_name_.Swap(&other->json_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ default_value_.Swap(&other->default_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
swap(kind_, other->kind_);
swap(cardinality_, other->cardinality_);
swap(number_, other->number_);
swap(oneof_index_, other->oneof_index_);
swap(packed_, other->packed_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Field::GetMetadata() const {
@@ -1669,9 +1641,8 @@ const int Enum::kSyntaxFieldNumber;
Enum::Enum()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnum();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Enum.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Enum)
}
@@ -1680,7 +1651,7 @@ Enum::Enum(::google::protobuf::Arena* arena)
_internal_metadata_(arena),
enumvalue_(arena),
options_(arena) {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnum();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Enum.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Enum)
@@ -1689,8 +1660,7 @@ Enum::Enum(const Enum& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
enumvalue_(from.enumvalue_),
- options_(from.options_),
- _cached_size_(0) {
+ options_(from.options_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
@@ -1711,7 +1681,6 @@ void Enum::SharedCtor() {
::memset(&source_context_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&syntax_) -
reinterpret_cast<char*>(&source_context_)) + sizeof(syntax_));
- _cached_size_ = 0;
}
Enum::~Enum() {
@@ -1729,12 +1698,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Enum::descriptor() {
::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
@@ -1742,7 +1709,7 @@ const ::google::protobuf::Descriptor* Enum::descriptor() {
}
const Enum& Enum::default_instance() {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnum();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Enum.base);
return *internal_default_instance();
}
@@ -1770,7 +1737,7 @@ bool Enum::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Enum)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -1830,7 +1797,7 @@ bool Enum::MergePartialFromCodedStream(
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
- int value;
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -1898,7 +1865,7 @@ void Enum::SerializeWithCachedSizes(
// .google.protobuf.SourceContext source_context = 4;
if (this->has_source_context()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 4, *source_context_, output);
+ 4, this->_internal_source_context(), output);
}
// .google.protobuf.Syntax syntax = 5;
@@ -1952,7 +1919,7 @@ void Enum::SerializeWithCachedSizes(
if (this->has_source_context()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 4, *source_context_, deterministic, target);
+ 4, this->_internal_source_context(), deterministic, target);
}
// .google.protobuf.Syntax syntax = 5;
@@ -2021,9 +1988,7 @@ size_t Enum::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -2103,11 +2068,11 @@ void Enum::InternalSwap(Enum* other) {
using std::swap;
CastToBase(&enumvalue_)->InternalSwap(CastToBase(&other->enumvalue_));
CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
- name_.Swap(&other->name_);
+ 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_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Enum::GetMetadata() const {
@@ -2128,9 +2093,8 @@ const int EnumValue::kOptionsFieldNumber;
EnumValue::EnumValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue();
- }
+ ::google::protobuf::internal::InitSCC(
+ &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_EnumValue.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumValue)
}
@@ -2138,7 +2102,7 @@ EnumValue::EnumValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
options_(arena) {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_EnumValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValue)
@@ -2146,8 +2110,7 @@ EnumValue::EnumValue(::google::protobuf::Arena* arena)
EnumValue::EnumValue(const EnumValue& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
- options_(from.options_),
- _cached_size_(0) {
+ options_(from.options_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
@@ -2161,7 +2124,6 @@ EnumValue::EnumValue(const EnumValue& from)
void EnumValue::SharedCtor() {
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
number_ = 0;
- _cached_size_ = 0;
}
EnumValue::~EnumValue() {
@@ -2178,12 +2140,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* EnumValue::descriptor() {
::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
@@ -2191,7 +2151,7 @@ const ::google::protobuf::Descriptor* EnumValue::descriptor() {
}
const EnumValue& EnumValue::default_instance() {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_EnumValue.base);
return *internal_default_instance();
}
@@ -2214,7 +2174,7 @@ bool EnumValue::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.EnumValue)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -2391,9 +2351,7 @@ size_t EnumValue::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -2468,10 +2426,10 @@ void EnumValue::UnsafeArenaSwap(EnumValue* other) {
void EnumValue::InternalSwap(EnumValue* other) {
using std::swap;
CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
- name_.Swap(&other->name_);
+ name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
swap(number_, other->number_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata EnumValue::GetMetadata() const {
@@ -2512,24 +2470,22 @@ const int Option::kValueFieldNumber;
Option::Option()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Option)
}
Option::Option(const Option& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
@@ -2547,7 +2503,6 @@ Option::Option(const Option& from)
void Option::SharedCtor() {
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_ = NULL;
- _cached_size_ = 0;
}
Option::~Option() {
@@ -2565,12 +2520,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Option::descriptor() {
::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
@@ -2578,7 +2531,7 @@ const ::google::protobuf::Descriptor* Option::descriptor() {
}
const Option& Option::default_instance() {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base);
return *internal_default_instance();
}
@@ -2603,7 +2556,7 @@ bool Option::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Option)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -2674,7 +2627,7 @@ void Option::SerializeWithCachedSizes(
// .google.protobuf.Any value = 2;
if (this->has_value()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, *value_, output);
+ 2, this->_internal_value(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
@@ -2706,7 +2659,7 @@ void Option::SerializeWithCachedSizes(
if (this->has_value()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 2, *value_, deterministic, target);
+ 2, this->_internal_value(), deterministic, target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
@@ -2741,9 +2694,7 @@ size_t Option::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -2816,10 +2767,10 @@ void Option::UnsafeArenaSwap(Option* other) {
}
void Option::InternalSwap(Option* other) {
using std::swap;
- name_.Swap(&other->name_);
+ name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
swap(value_, other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Option::GetMetadata() const {
@@ -2833,19 +2784,19 @@ void Option::InternalSwap(Option* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Type* Arena::CreateMessage< ::google::protobuf::Type >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::Field >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::Enum >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::EnumValue >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::Option >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Option* Arena::CreateMaybeMessage< ::google::protobuf::Option >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Option >(arena);
}
} // namespace protobuf
diff --git a/src/google/protobuf/type.pb.h b/src/google/protobuf/type.pb.h
index 49bed8ee..cbd0cdcc 100644
--- a/src/google/protobuf/type.pb.h
+++ b/src/google/protobuf/type.pb.h
@@ -1,19 +1,19 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/type.proto
-#ifndef PROTOBUF_google_2fprotobuf_2ftype_2eproto_INCLUDED
-#define PROTOBUF_google_2fprotobuf_2ftype_2eproto_INCLUDED
+#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2ftype_2eproto
+#define PROTOBUF_INCLUDED_google_2fprotobuf_2ftype_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3005000
+#if GOOGLE_PROTOBUF_VERSION < 3006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3005001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -24,6 +24,7 @@
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -33,6 +34,7 @@
#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
namespace protobuf_google_2fprotobuf_2ftype_2eproto {
// Internal implementation detail -- do not use these members.
@@ -45,23 +47,6 @@ struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::uint32 offsets[];
};
void LIBPROTOBUF_EXPORT AddDescriptors();
-void LIBPROTOBUF_EXPORT InitDefaultsTypeImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsType();
-void LIBPROTOBUF_EXPORT InitDefaultsFieldImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsField();
-void LIBPROTOBUF_EXPORT InitDefaultsEnumImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsEnum();
-void LIBPROTOBUF_EXPORT InitDefaultsEnumValueImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsEnumValue();
-void LIBPROTOBUF_EXPORT InitDefaultsOptionImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsOption();
-inline void LIBPROTOBUF_EXPORT InitDefaults() {
- InitDefaultsType();
- InitDefaultsField();
- InitDefaultsEnum();
- InitDefaultsEnumValue();
- InitDefaultsOption();
-}
} // namespace protobuf_google_2fprotobuf_2ftype_2eproto
namespace google {
namespace protobuf {
@@ -84,11 +69,11 @@ LIBPROTOBUF_EXPORT extern TypeDefaultTypeInternal _Type_default_instance_;
} // namespace google
namespace google {
namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Enum* Arena::CreateMessage< ::google::protobuf::Enum>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValue* Arena::CreateMessage< ::google::protobuf::EnumValue>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Field* Arena::CreateMessage< ::google::protobuf::Field>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Option* Arena::CreateMessage< ::google::protobuf::Option>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Type* Arena::CreateMessage< ::google::protobuf::Type>(Arena*);
+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*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -204,10 +189,10 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -218,7 +203,7 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
return reinterpret_cast<const Type*>(
&_Type_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
0;
void UnsafeArenaSwap(Type* other);
@@ -229,32 +214,33 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
// implements Message ----------------------------------------------
- inline Type* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Type>(NULL);
+ inline Type* New() const final {
+ return CreateMaybeMessage<Type>(NULL);
}
- Type* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Type>(arena);
+ Type* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Type>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Type& from);
void MergeFrom(const Type& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Type* other);
protected:
explicit Type(::google::protobuf::Arena* arena);
@@ -270,7 +256,7 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -349,6 +335,9 @@ 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();
@@ -376,9 +365,8 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::SourceContext* source_context_;
int syntax_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsTypeImpl();
};
// -------------------------------------------------------------------
@@ -408,10 +396,10 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -422,7 +410,7 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
return reinterpret_cast<const Field*>(
&_Field_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
1;
void UnsafeArenaSwap(Field* other);
@@ -433,32 +421,33 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
// implements Message ----------------------------------------------
- inline Field* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Field>(NULL);
+ inline Field* New() const final {
+ return CreateMaybeMessage<Field>(NULL);
}
- Field* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Field>(arena);
+ Field* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Field>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Field& from);
void MergeFrom(const Field& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Field* other);
protected:
explicit Field(::google::protobuf::Arena* arena);
@@ -474,7 +463,7 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -721,9 +710,8 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::int32 number_;
::google::protobuf::int32 oneof_index_;
bool packed_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsFieldImpl();
};
// -------------------------------------------------------------------
@@ -753,10 +741,10 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -767,7 +755,7 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
return reinterpret_cast<const Enum*>(
&_Enum_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
2;
void UnsafeArenaSwap(Enum* other);
@@ -778,32 +766,33 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
// implements Message ----------------------------------------------
- inline Enum* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Enum>(NULL);
+ inline Enum* New() const final {
+ return CreateMaybeMessage<Enum>(NULL);
}
- Enum* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Enum>(arena);
+ Enum* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Enum>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Enum& from);
void MergeFrom(const Enum& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Enum* other);
protected:
explicit Enum(::google::protobuf::Arena* arena);
@@ -819,7 +808,7 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -876,6 +865,9 @@ 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();
@@ -902,9 +894,8 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::SourceContext* source_context_;
int syntax_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumImpl();
};
// -------------------------------------------------------------------
@@ -934,10 +925,10 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -948,7 +939,7 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
return reinterpret_cast<const EnumValue*>(
&_EnumValue_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
3;
void UnsafeArenaSwap(EnumValue* other);
@@ -959,32 +950,33 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
// implements Message ----------------------------------------------
- inline EnumValue* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<EnumValue>(NULL);
+ inline EnumValue* New() const final {
+ return CreateMaybeMessage<EnumValue>(NULL);
}
- EnumValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<EnumValue>(arena);
+ EnumValue* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<EnumValue>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const EnumValue& from);
void MergeFrom(const EnumValue& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(EnumValue* other);
protected:
explicit EnumValue(::google::protobuf::Arena* arena);
@@ -1000,7 +992,7 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -1057,9 +1049,8 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::int32 number_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValueImpl();
};
// -------------------------------------------------------------------
@@ -1089,10 +1080,10 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -1103,7 +1094,7 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
return reinterpret_cast<const Option*>(
&_Option_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
4;
void UnsafeArenaSwap(Option* other);
@@ -1114,32 +1105,33 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
// implements Message ----------------------------------------------
- inline Option* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Option>(NULL);
+ inline Option* New() const final {
+ return CreateMaybeMessage<Option>(NULL);
}
- Option* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Option>(arena);
+ Option* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Option>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Option& from);
void MergeFrom(const Option& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Option* other);
protected:
explicit Option(::google::protobuf::Arena* arena);
@@ -1155,7 +1147,7 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -1188,6 +1180,9 @@ 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();
@@ -1205,9 +1200,8 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
typedef void DestructorSkippable_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::Any* value_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOptionImpl();
};
// ===================================================================
@@ -1428,6 +1422,9 @@ 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)
@@ -1439,7 +1436,7 @@ inline ::google::protobuf::SourceContext* Type::release_source_context() {
::google::protobuf::SourceContext* temp = source_context_;
if (GetArenaNoVirtual() != NULL) {
- temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
source_context_ = NULL;
return temp;
@@ -1454,8 +1451,8 @@ inline ::google::protobuf::SourceContext* Type::unsafe_arena_release_source_cont
inline ::google::protobuf::SourceContext* Type::mutable_source_context() {
if (source_context_ == NULL) {
- source_context_ = ::google::protobuf::Arena::Create< ::google::protobuf::SourceContext >(
- GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<::google::protobuf::SourceContext>(GetArenaNoVirtual());
+ source_context_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Type.source_context)
return source_context_;
@@ -2040,6 +2037,9 @@ 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)
@@ -2051,7 +2051,7 @@ inline ::google::protobuf::SourceContext* Enum::release_source_context() {
::google::protobuf::SourceContext* temp = source_context_;
if (GetArenaNoVirtual() != NULL) {
- temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
source_context_ = NULL;
return temp;
@@ -2066,8 +2066,8 @@ inline ::google::protobuf::SourceContext* Enum::unsafe_arena_release_source_cont
inline ::google::protobuf::SourceContext* Enum::mutable_source_context() {
if (source_context_ == NULL) {
- source_context_ = ::google::protobuf::Arena::Create< ::google::protobuf::SourceContext >(
- GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<::google::protobuf::SourceContext>(GetArenaNoVirtual());
+ source_context_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Enum.source_context)
return source_context_;
@@ -2311,6 +2311,9 @@ 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)
@@ -2322,7 +2325,7 @@ inline ::google::protobuf::Any* Option::release_value() {
::google::protobuf::Any* temp = value_;
if (GetArenaNoVirtual() != NULL) {
- temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
value_ = NULL;
return temp;
@@ -2337,8 +2340,8 @@ inline ::google::protobuf::Any* Option::unsafe_arena_release_value() {
inline ::google::protobuf::Any* Option::mutable_value() {
if (value_ == NULL) {
- value_ = ::google::protobuf::Arena::Create< ::google::protobuf::Any >(
- GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<::google::protobuf::Any>(GetArenaNoVirtual());
+ value_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Option.value)
return value_;
@@ -2382,17 +2385,17 @@ inline void Option::set_allocated_value(::google::protobuf::Any* value) {
namespace google {
namespace protobuf {
-template <> struct is_proto_enum< ::google::protobuf::Field_Kind> : ::google::protobuf::internal::true_type {};
+template <> struct is_proto_enum< ::google::protobuf::Field_Kind> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::Field_Kind>() {
return ::google::protobuf::Field_Kind_descriptor();
}
-template <> struct is_proto_enum< ::google::protobuf::Field_Cardinality> : ::google::protobuf::internal::true_type {};
+template <> struct is_proto_enum< ::google::protobuf::Field_Cardinality> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::Field_Cardinality>() {
return ::google::protobuf::Field_Cardinality_descriptor();
}
-template <> struct is_proto_enum< ::google::protobuf::Syntax> : ::google::protobuf::internal::true_type {};
+template <> struct is_proto_enum< ::google::protobuf::Syntax> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::Syntax>() {
return ::google::protobuf::Syntax_descriptor();
@@ -2403,4 +2406,4 @@ inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::Syntax>() {
// @@protoc_insertion_point(global_scope)
-#endif // PROTOBUF_google_2fprotobuf_2ftype_2eproto_INCLUDED
+#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2ftype_2eproto
diff --git a/src/google/protobuf/unittest.proto b/src/google/protobuf/unittest.proto
index 2a288daa..4af2b051 100644
--- a/src/google/protobuf/unittest.proto
+++ b/src/google/protobuf/unittest.proto
@@ -33,6 +33,8 @@
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file we will use for unit testing.
+//
+// LINT: ALLOW_GROUPS, LEGACY_NAMES
syntax = "proto2";
@@ -333,6 +335,17 @@ extend TestAllExtensions {
optional bytes oneof_bytes_extension = 114;
}
+message TestGroup {
+ optional group OptionalGroup = 16 {
+ optional int32 a = 17;
+ }
+ optional ForeignEnum optional_foreign_enum = 22;
+}
+
+message TestGroupExtension {
+ extensions 1 to max;
+}
+
message TestNestedExtension {
extend TestAllExtensions {
// Check for bug where string extensions declared in tested scope did not
@@ -342,6 +355,13 @@ message TestNestedExtension {
// underscores.
optional string nested_string_extension = 1003;
}
+
+ extend TestGroupExtension {
+ optional group OptionalGroup_extension = 16 {
+ optional int32 a = 17;
+ }
+ optional ForeignEnum optional_foreign_enum_extension = 22;
+ }
}
// We have separate messages for testing required fields because it's
@@ -554,12 +574,30 @@ message TestFieldOrderings {
optional NestedMessage optional_nested_message = 200;
}
-
extend TestFieldOrderings {
optional string my_extension_string = 50;
optional int32 my_extension_int = 5;
}
+message TestExtensionOrderings1 {
+ extend TestFieldOrderings {
+ optional TestExtensionOrderings1 test_ext_orderings1 = 13;
+ }
+ optional string my_string = 1;
+}
+
+message TestExtensionOrderings2 {
+ extend TestFieldOrderings {
+ optional TestExtensionOrderings2 test_ext_orderings2 = 12;
+ }
+ message TestExtensionOrderings3 {
+ extend TestFieldOrderings {
+ optional TestExtensionOrderings3 test_ext_orderings3 = 14;
+ }
+ optional string my_string = 1;
+ }
+ optional string my_string = 1;
+}
message TestExtremeDefaultValues {
optional bytes escaped_bytes = 1 [default = "\0\001\a\b\f\n\r\t\v\\\'\"\xfe"];
@@ -946,3 +984,21 @@ message TestHugeFieldNumbers {
extend TestHugeFieldNumbers {
optional TestAllTypes test_all_types = 536860000;
}
+
+message TestExtensionInsideTable {
+ optional int32 field1 = 1;
+ optional int32 field2 = 2;
+ optional int32 field3 = 3;
+ optional int32 field4 = 4;
+ extensions 5 to 5;
+ optional int32 field6 = 6;
+ optional int32 field7 = 7;
+ optional int32 field8 = 8;
+ optional int32 field9 = 9;
+ optional int32 field10 = 10;
+}
+
+extend TestExtensionInsideTable {
+ optional int32 test_extension_inside_table_extension = 5;
+}
+
diff --git a/src/google/protobuf/unittest_lite.proto b/src/google/protobuf/unittest_lite.proto
index 9a15bdaa..f3ff2b5d 100644
--- a/src/google/protobuf/unittest_lite.proto
+++ b/src/google/protobuf/unittest_lite.proto
@@ -454,3 +454,22 @@ message TestOneofParsingLite {
V2EnumLite oneof_enum = 9;
}
}
+
+// The following four messages are set up to test for wire compatibility between
+// packed and non-packed repeated fields. We use the field number 2048, because
+// that is large enough to require a 3-byte varint for the tag.
+message PackedInt32 {
+ repeated int32 repeated_int32 = 2048 [packed = true];
+}
+
+message NonPackedInt32 {
+ repeated int32 repeated_int32 = 2048;
+}
+
+message PackedFixed32 {
+ repeated fixed32 repeated_fixed32 = 2048 [packed = true];
+}
+
+message NonPackedFixed32 {
+ repeated fixed32 repeated_fixed32 = 2048;
+}
diff --git a/src/google/protobuf/unknown_field_set_unittest.cc b/src/google/protobuf/unknown_field_set_unittest.cc
index e55bb012..a64769e7 100644
--- a/src/google/protobuf/unknown_field_set_unittest.cc
+++ b/src/google/protobuf/unknown_field_set_unittest.cc
@@ -49,6 +49,7 @@
#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 {
diff --git a/src/google/protobuf/util/field_comparator.h b/src/google/protobuf/util/field_comparator.h
index 27ef4c77..63e89fb7 100644
--- a/src/google/protobuf/util/field_comparator.h
+++ b/src/google/protobuf/util/field_comparator.h
@@ -110,14 +110,14 @@ class LIBPROTOBUF_EXPORT DefaultFieldComparator : public FieldComparator {
// Creates new comparator with float comparison set to EXACT.
DefaultFieldComparator();
- virtual ~DefaultFieldComparator();
+ ~DefaultFieldComparator() override;
- virtual ComparisonResult Compare(
+ 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);
+ const google::protobuf::util::FieldContext* field_context) override;
void set_float_comparison(FloatComparison float_comparison) {
float_comparison_ = float_comparison;
diff --git a/src/google/protobuf/util/field_mask_util.cc b/src/google/protobuf/util/field_mask_util.cc
index 8a413498..a2e2a388 100644
--- a/src/google/protobuf/util/field_mask_util.cc
+++ b/src/google/protobuf/util/field_mask_util.cc
@@ -31,6 +31,7 @@
#include <google/protobuf/util/field_mask_util.h>
#include <google/protobuf/stubs/strutil.h>
+
#include <google/protobuf/stubs/map_util.h>
namespace google {
@@ -131,27 +132,27 @@ bool FieldMaskUtil::FromJsonString(StringPiece str, FieldMask* out) {
bool FieldMaskUtil::GetFieldDescriptors(
const Descriptor* descriptor, StringPiece path,
std::vector<const FieldDescriptor*>* field_descriptors) {
- if (field_descriptors != NULL) {
+ if (field_descriptors != nullptr) {
field_descriptors->clear();
}
std::vector<string> parts = Split(path, ".");
for (int i = 0; i < parts.size(); ++i) {
const string& field_name = parts[i];
- if (descriptor == NULL) {
+ if (descriptor == nullptr) {
return false;
}
const FieldDescriptor* field = descriptor->FindFieldByName(field_name);
- if (field == NULL) {
+ if (field == nullptr) {
return false;
}
- if (field_descriptors != NULL) {
+ if (field_descriptors != nullptr) {
field_descriptors->push_back(field);
}
if (!field->is_repeated() &&
field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
descriptor = field->message_type();
} else {
- descriptor = NULL;
+ descriptor = nullptr;
}
}
return true;
@@ -342,6 +343,12 @@ void FieldMaskTree::AddPath(const string& path) {
void FieldMaskTree::RemovePath(const string& path,
const Descriptor* descriptor) {
+ if (root_.children.empty()) {
+ // Nothing to be removed from an empty tree. We shortcut it here so an empty
+ // tree won't be interpreted as a field mask containing all fields by the
+ // code below.
+ return;
+ }
std::vector<string> parts = Split(path, ".");
if (parts.empty()) {
return;
@@ -349,16 +356,16 @@ void FieldMaskTree::RemovePath(const string& path,
std::vector<Node*> nodes(parts.size());
Node* node = &root_;
const Descriptor* current_descriptor = descriptor;
- Node* new_branch_node = NULL;
+ Node* new_branch_node = nullptr;
for (int i = 0; i < parts.size(); ++i) {
nodes[i] = node;
const FieldDescriptor* field_descriptor =
current_descriptor->FindFieldByName(parts[i]);
- if (field_descriptor == NULL ||
+ if (field_descriptor == nullptr ||
(field_descriptor->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE &&
i != parts.size() - 1)) {
// Invalid path.
- if (new_branch_node != NULL) {
+ if (new_branch_node != nullptr) {
// If add any new nodes, cleanup.
new_branch_node->ClearChildren();
}
@@ -366,7 +373,7 @@ void FieldMaskTree::RemovePath(const string& path,
}
if (node->children.empty()) {
- if (new_branch_node == NULL) {
+ if (new_branch_node == nullptr) {
new_branch_node = node;
}
for (int i = 0; i < current_descriptor->field_count(); ++i) {
@@ -542,7 +549,7 @@ void FieldMaskTree::AddRequiredFieldPath(
if (field->is_required()) {
const string& node_name = field->name();
Node*& child = node->children[node_name];
- if (child == NULL) {
+ if (child == nullptr) {
// Add required field path to the tree
child = new Node();
} else if (child->children.empty()){
diff --git a/src/google/protobuf/util/field_mask_util.h b/src/google/protobuf/util/field_mask_util.h
index 91787bd5..f0299de9 100644
--- a/src/google/protobuf/util/field_mask_util.h
+++ b/src/google/protobuf/util/field_mask_util.h
@@ -70,14 +70,14 @@ class LIBPROTOBUF_EXPORT FieldMaskUtil {
// Checks whether the given path is valid for type T.
template <typename T>
static bool IsValidPath(StringPiece path) {
- return GetFieldDescriptors(T::descriptor(), path, NULL);
+ return GetFieldDescriptors(T::descriptor(), path, nullptr);
}
// Checks whether the given FieldMask is valid for type T.
template <typename T>
static bool IsValidFieldMask(const FieldMask& mask) {
for (int i = 0; i < mask.paths_size(); ++i) {
- if (!GetFieldDescriptors(T::descriptor(), mask.paths(i), NULL))
+ if (!GetFieldDescriptors(T::descriptor(), mask.paths(i), nullptr))
return false;
}
return true;
diff --git a/src/google/protobuf/util/field_mask_util_test.cc b/src/google/protobuf/util/field_mask_util_test.cc
index 0664d9e5..3ba30aa3 100644
--- a/src/google/protobuf/util/field_mask_util_test.cc
+++ b/src/google/protobuf/util/field_mask_util_test.cc
@@ -168,7 +168,7 @@ TEST(FieldMaskUtilTest, GetFieldDescriptors) {
EXPECT_EQ(1, field_descriptors.size());
EXPECT_EQ("optional_int32", field_descriptors[0]->name());
EXPECT_FALSE(FieldMaskUtil::GetFieldDescriptors(
- TestAllTypes::descriptor(), "optional_nonexist", NULL));
+ TestAllTypes::descriptor(), "optional_nonexist", nullptr));
EXPECT_TRUE(FieldMaskUtil::GetFieldDescriptors(TestAllTypes::descriptor(),
"optional_nested_message.bb",
&field_descriptors));
@@ -176,10 +176,10 @@ TEST(FieldMaskUtilTest, GetFieldDescriptors) {
EXPECT_EQ("optional_nested_message", field_descriptors[0]->name());
EXPECT_EQ("bb", field_descriptors[1]->name());
EXPECT_FALSE(FieldMaskUtil::GetFieldDescriptors(
- TestAllTypes::descriptor(), "optional_nested_message.nonexist", NULL));
+ TestAllTypes::descriptor(), "optional_nested_message.nonexist", nullptr));
// FieldMask cannot be used to specify sub-fields of a repeated message.
EXPECT_FALSE(FieldMaskUtil::GetFieldDescriptors(
- TestAllTypes::descriptor(), "repeated_nested_message.bb", NULL));
+ TestAllTypes::descriptor(), "repeated_nested_message.bb", nullptr));
}
TEST(FieldMaskUtilTest, TestIsVaildPath) {
@@ -386,6 +386,13 @@ TEST(FieldMaskUtilTest, TestSubtract) {
FieldMaskUtil::FromString("optional_nested_message", &mask2);
FieldMaskUtil::Subtract<TestAllTypes>(mask1, mask2, &out);
EXPECT_EQ("", FieldMaskUtil::ToString(out));
+
+ // Regression test for b/72727550
+ FieldMaskUtil::FromString("optional_foreign_message.c", &mask1);
+ FieldMaskUtil::FromString("optional_foreign_message,optional_nested_message",
+ &mask2);
+ FieldMaskUtil::Subtract<TestAllTypes>(mask1, mask2, &out);
+ EXPECT_EQ("", FieldMaskUtil::ToString(out));
}
TEST(FieldMaskUtilTest, TestIspathInFieldMask) {
diff --git a/src/google/protobuf/util/internal/datapiece.cc b/src/google/protobuf/util/internal/datapiece.cc
index 213c2c40..59bc28ae 100644
--- a/src/google/protobuf/util/internal/datapiece.cc
+++ b/src/google/protobuf/util/internal/datapiece.cc
@@ -64,9 +64,9 @@ StatusOr<To> ValidateNumberConversion(To after, From before) {
MathUtil::Sign<From>(before) == MathUtil::Sign<To>(after)) {
return after;
} else {
- return InvalidArgument(::google::protobuf::internal::is_integral<From>::value
+ return InvalidArgument(std::is_integral<From>::value
? ValueAsString(before)
- : ::google::protobuf::internal::is_same<From, double>::value
+ : std::is_same<From, double>::value
? DoubleAsString(before)
: FloatAsString(before));
}
@@ -77,7 +77,7 @@ StatusOr<To> ValidateNumberConversion(To after, From before) {
// except conversion between double and float.
template <typename To, typename From>
StatusOr<To> NumberConvertAndCheck(From before) {
- if (::google::protobuf::internal::is_same<From, To>::value) return before;
+ if (std::is_same<From, To>::value) return before;
To after = static_cast<To>(before);
return ValidateNumberConversion(after, before);
@@ -87,7 +87,7 @@ StatusOr<To> NumberConvertAndCheck(From before) {
// point types (double, float) only.
template <typename To, typename From>
StatusOr<To> FloatingPointToIntConvertAndCheck(From before) {
- if (::google::protobuf::internal::is_same<From, To>::value) return before;
+ if (std::is_same<From, To>::value) return before;
To after = static_cast<To>(before);
return ValidateNumberConversion(after, before);
@@ -272,7 +272,8 @@ StatusOr<string> DataPiece::ToBytes() const {
}
StatusOr<int> DataPiece::ToEnum(const google::protobuf::Enum* enum_type,
- bool use_lower_camel_for_enums) const {
+ bool use_lower_camel_for_enums,
+ bool ignore_unknown_enum_values) const {
if (type_ == TYPE_NULL) return google::protobuf::NULL_VALUE;
if (type_ == TYPE_STRING) {
@@ -280,7 +281,7 @@ StatusOr<int> DataPiece::ToEnum(const google::protobuf::Enum* enum_type,
string enum_name = str_.ToString();
const google::protobuf::EnumValue* value =
FindEnumValueByNameOrNull(enum_type, enum_name);
- if (value != NULL) return value->number();
+ if (value != nullptr) return value->number();
// Check if int version of enum is sent as string.
StatusOr<int32> int_value = ToInt32();
@@ -296,15 +297,19 @@ StatusOr<int> DataPiece::ToEnum(const google::protobuf::Enum* enum_type,
*it = *it == '-' ? '_' : ascii_toupper(*it);
}
value = FindEnumValueByNameOrNull(enum_type, enum_name);
- if (value != NULL) return value->number();
+ if (value != nullptr) return value->number();
// If use_lower_camel_for_enums is true try with enum name without
// underscore. This will also accept camel case names as the enum_name has
// been normalized before.
if (use_lower_camel_for_enums) {
value = FindEnumValueByNameWithoutUnderscoreOrNull(enum_type, enum_name);
- if (value != NULL) return value->number();
+ 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();
} else {
// We don't need to check whether the value is actually declared in the
// enum because we preserve unknown enum values as well.
@@ -357,7 +362,8 @@ bool DataPiece::DecodeBase64(StringPiece src, string* dest) const {
WebSafeBase64Escape(*dest, &encoded);
// Remove trailing padding '=' characters before comparison.
StringPiece src_no_padding = StringPiece(src).substr(
- 0, src.ends_with("=") ? src.find_last_not_of('=') + 1 : src.length());
+ 0, StringEndsWith(src, "=") ? src.find_last_not_of('=') + 1
+ : src.length());
return encoded == src_no_padding;
}
return true;
@@ -370,7 +376,8 @@ bool DataPiece::DecodeBase64(StringPiece src, string* dest) const {
reinterpret_cast<const unsigned char*>(dest->data()), dest->length(),
&encoded, false);
StringPiece src_no_padding = StringPiece(src).substr(
- 0, src.ends_with("=") ? src.find_last_not_of('=') + 1 : src.length());
+ 0, StringEndsWith(src, "=") ? src.find_last_not_of('=') + 1
+ : src.length());
return encoded == src_no_padding;
}
return true;
diff --git a/src/google/protobuf/util/internal/datapiece.h b/src/google/protobuf/util/internal/datapiece.h
index 83516d09..95b133da 100644
--- a/src/google/protobuf/util/internal/datapiece.h
+++ b/src/google/protobuf/util/internal/datapiece.h
@@ -164,7 +164,8 @@ 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) const;
+ bool use_lower_camel_for_enums,
+ bool ignore_unknown_enum_values) const;
private:
// Disallow implicit constructor.
diff --git a/src/google/protobuf/util/internal/default_value_objectwriter.cc b/src/google/protobuf/util/internal/default_value_objectwriter.cc
index 95b3a17d..b41feb7a 100644
--- a/src/google/protobuf/util/internal/default_value_objectwriter.cc
+++ b/src/google/protobuf/util/internal/default_value_objectwriter.cc
@@ -62,11 +62,12 @@ DefaultValueObjectWriter::DefaultValueObjectWriter(
: typeinfo_(TypeInfo::NewTypeInfo(type_resolver)),
own_typeinfo_(true),
type_(type),
- current_(NULL),
- root_(NULL),
+ current_(nullptr),
+ root_(nullptr),
suppress_empty_list_(false),
preserve_proto_field_names_(false),
- field_scrub_callback_(NULL),
+ use_ints_for_enums_(false),
+ field_scrub_callback_(nullptr),
ow_(ow) {}
DefaultValueObjectWriter::~DefaultValueObjectWriter() {
@@ -80,7 +81,7 @@ DefaultValueObjectWriter::~DefaultValueObjectWriter() {
DefaultValueObjectWriter* DefaultValueObjectWriter::RenderBool(StringPiece name,
bool value) {
- if (current_ == NULL) {
+ if (current_ == nullptr) {
ow_->RenderBool(name, value);
} else {
RenderDataPiece(name, DataPiece(value));
@@ -90,7 +91,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderBool(StringPiece name,
DefaultValueObjectWriter* DefaultValueObjectWriter::RenderInt32(
StringPiece name, int32 value) {
- if (current_ == NULL) {
+ if (current_ == nullptr) {
ow_->RenderInt32(name, value);
} else {
RenderDataPiece(name, DataPiece(value));
@@ -100,7 +101,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderInt32(
DefaultValueObjectWriter* DefaultValueObjectWriter::RenderUint32(
StringPiece name, uint32 value) {
- if (current_ == NULL) {
+ if (current_ == nullptr) {
ow_->RenderUint32(name, value);
} else {
RenderDataPiece(name, DataPiece(value));
@@ -110,7 +111,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderUint32(
DefaultValueObjectWriter* DefaultValueObjectWriter::RenderInt64(
StringPiece name, int64 value) {
- if (current_ == NULL) {
+ if (current_ == nullptr) {
ow_->RenderInt64(name, value);
} else {
RenderDataPiece(name, DataPiece(value));
@@ -120,7 +121,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderInt64(
DefaultValueObjectWriter* DefaultValueObjectWriter::RenderUint64(
StringPiece name, uint64 value) {
- if (current_ == NULL) {
+ if (current_ == nullptr) {
ow_->RenderUint64(name, value);
} else {
RenderDataPiece(name, DataPiece(value));
@@ -130,7 +131,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderUint64(
DefaultValueObjectWriter* DefaultValueObjectWriter::RenderDouble(
StringPiece name, double value) {
- if (current_ == NULL) {
+ if (current_ == nullptr) {
ow_->RenderDouble(name, value);
} else {
RenderDataPiece(name, DataPiece(value));
@@ -140,7 +141,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderDouble(
DefaultValueObjectWriter* DefaultValueObjectWriter::RenderFloat(
StringPiece name, float value) {
- if (current_ == NULL) {
+ if (current_ == nullptr) {
ow_->RenderBool(name, value);
} else {
RenderDataPiece(name, DataPiece(value));
@@ -150,7 +151,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderFloat(
DefaultValueObjectWriter* DefaultValueObjectWriter::RenderString(
StringPiece name, StringPiece value) {
- if (current_ == NULL) {
+ if (current_ == nullptr) {
ow_->RenderString(name, value);
} else {
// Since StringPiece is essentially a pointer, takes a copy of "value" to
@@ -163,7 +164,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderString(
DefaultValueObjectWriter* DefaultValueObjectWriter::RenderBytes(
StringPiece name, StringPiece value) {
- if (current_ == NULL) {
+ if (current_ == nullptr) {
ow_->RenderBytes(name, value);
} else {
// Since StringPiece is essentially a pointer, takes a copy of "value" to
@@ -176,7 +177,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderBytes(
DefaultValueObjectWriter* DefaultValueObjectWriter::RenderNull(
StringPiece name) {
- if (current_ == NULL) {
+ if (current_ == nullptr) {
ow_->RenderNull(name);
} else {
RenderDataPiece(name, DataPiece::NullData());
@@ -200,10 +201,10 @@ DefaultValueObjectWriter::Node* DefaultValueObjectWriter::CreateNewNode(
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 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,
+ suppress_empty_list, preserve_proto_field_names, use_ints_for_enums,
field_scrub_callback);
}
@@ -220,12 +221,13 @@ DefaultValueObjectWriter::Node::Node(
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 suppress_empty_list, bool preserve_proto_field_names, bool use_ints_for_enums,
FieldScrubCallBack* field_scrub_callback)
: name_(name),
type_(type),
@@ -236,12 +238,13 @@ DefaultValueObjectWriter::Node::Node(
path_(path),
suppress_empty_list_(suppress_empty_list),
preserve_proto_field_names_(preserve_proto_field_names),
+ use_ints_for_enums_(use_ints_for_enums),
field_scrub_callback_(field_scrub_callback) {}
DefaultValueObjectWriter::Node* DefaultValueObjectWriter::Node::FindChild(
StringPiece name) {
if (name.empty() || kind_ != OBJECT) {
- return NULL;
+ return nullptr;
}
for (int i = 0; i < children_.size(); ++i) {
Node* child = children_[i];
@@ -249,7 +252,7 @@ DefaultValueObjectWriter::Node* DefaultValueObjectWriter::Node::FindChild(
return child;
}
}
- return NULL;
+ return nullptr;
}
void DefaultValueObjectWriter::Node::WriteTo(ObjectWriter* ow) {
@@ -317,7 +320,7 @@ const google::protobuf::Type* DefaultValueObjectWriter::Node::GetMapValueType(
}
break;
}
- return NULL;
+ return nullptr;
}
void DefaultValueObjectWriter::Node::PopulateChildren(
@@ -328,7 +331,7 @@ void DefaultValueObjectWriter::Node::PopulateChildren(
// TODO(tsun): remove "kStructValueType" from the list. It's being checked
// now because of a bug in the tool-chain that causes the "oneof_index"
// of kStructValueType to not be set correctly.
- if (type_ == NULL || type_->name() == kAnyType ||
+ if (type_ == nullptr || type_->name() == kAnyType ||
type_->name() == kStructType || type_->name() == kTimestampType ||
type_->name() == kDurationType || type_->name() == kStructValueType) {
return;
@@ -351,7 +354,7 @@ void DefaultValueObjectWriter::Node::PopulateChildren(
path.insert(path.begin(), path_.begin(), path_.end());
}
path.push_back(field.name());
- if (field_scrub_callback_ != NULL &&
+ if (field_scrub_callback_ != nullptr &&
field_scrub_callback_->Run(path, &field)) {
continue;
}
@@ -362,11 +365,11 @@ void DefaultValueObjectWriter::Node::PopulateChildren(
// of children.
if (found != orig_children_map.end()) {
new_children.push_back(children_[found->second]);
- children_[found->second] = NULL;
+ children_[found->second] = nullptr;
continue;
}
- const google::protobuf::Type* field_type = NULL;
+ const google::protobuf::Type* field_type = nullptr;
bool is_map = false;
NodeKind kind = PRIMITIVE;
@@ -405,22 +408,22 @@ void DefaultValueObjectWriter::Node::PopulateChildren(
// If the child field is of primitive type, sets its data to the default
// value of its type.
- google::protobuf::scoped_ptr<Node> child(new Node(
+ std::unique_ptr<Node> child(new Node(
preserve_proto_field_names_ ? field.name() : field.json_name(),
field_type, kind,
- kind == PRIMITIVE ? CreateDefaultDataPieceForField(field, typeinfo)
+ kind == PRIMITIVE ? CreateDefaultDataPieceForField(field, typeinfo, use_ints_for_enums_)
: DataPiece::NullData(),
- true, path, suppress_empty_list_, preserve_proto_field_names_,
+ 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.
for (int i = 0; i < children_.size(); ++i) {
- if (children_[i] == NULL) {
+ if (children_[i] == nullptr) {
continue;
}
new_children.insert(new_children.begin(), children_[i]);
- children_[i] = NULL;
+ children_[i] = nullptr;
}
children_.swap(new_children);
}
@@ -428,14 +431,14 @@ void DefaultValueObjectWriter::Node::PopulateChildren(
void DefaultValueObjectWriter::MaybePopulateChildrenOfAny(Node* node) {
// If this is an "Any" node with "@type" already given and no other children
// have been added, populates its children.
- if (node != NULL && node->is_any() && node->type() != NULL &&
+ if (node != nullptr && node->is_any() && node->type() != nullptr &&
node->type()->name() != kAnyType && node->number_of_children() == 1) {
node->PopulateChildren(typeinfo_);
}
}
DataPiece DefaultValueObjectWriter::FindEnumDefault(
- const google::protobuf::Field& field, const TypeInfo* typeinfo) {
+ const google::protobuf::Field& field, const TypeInfo* typeinfo, bool use_ints_for_enums) {
if (!field.default_value().empty())
return DataPiece(field.default_value(), true);
@@ -448,12 +451,12 @@ DataPiece DefaultValueObjectWriter::FindEnumDefault(
}
// We treat the first value as the default if none is specified.
return enum_type->enumvalue_size() > 0
- ? 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) {
+ 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>(
@@ -496,7 +499,7 @@ DataPiece DefaultValueObjectWriter::CreateDefaultDataPieceForField(
field.default_value(), &DataPiece::ToUint32, static_cast<uint32>(0)));
}
case google::protobuf::Field_Kind_TYPE_ENUM: {
- return FindEnumDefault(field, typeinfo);
+ return FindEnumDefault(field, typeinfo, use_ints_for_enums);
}
default: { return DataPiece::NullData(); }
}
@@ -504,11 +507,11 @@ DataPiece DefaultValueObjectWriter::CreateDefaultDataPieceForField(
DefaultValueObjectWriter* DefaultValueObjectWriter::StartObject(
StringPiece name) {
- if (current_ == NULL) {
+ 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_,
+ suppress_empty_list_, preserve_proto_field_names_, use_ints_for_enums_,
field_scrub_callback_.get()));
root_->PopulateChildren(typeinfo_);
current_ = root_.get();
@@ -516,17 +519,17 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::StartObject(
}
MaybePopulateChildrenOfAny(current_);
Node* child = current_->FindChild(name);
- if (current_->kind() == LIST || current_->kind() == MAP || child == NULL) {
+ if (current_->kind() == LIST || current_->kind() == MAP || child == nullptr) {
// If current_ is a list or a map node, we should create a new child and use
// the type of current_ as the type of the new child.
- google::protobuf::scoped_ptr<Node> node(
+ std::unique_ptr<Node> node(
CreateNewNode(string(name),
((current_->kind() == LIST || current_->kind() == MAP)
? current_->type()
- : NULL),
+ : nullptr),
OBJECT, DataPiece::NullData(), false,
- child == NULL ? current_->path() : child->path(),
- suppress_empty_list_, preserve_proto_field_names_,
+ child == nullptr ? current_->path() : child->path(),
+ suppress_empty_list_, preserve_proto_field_names_, use_ints_for_enums_,
field_scrub_callback_.get()));
child = node.get();
current_->AddChild(node.release());
@@ -555,22 +558,22 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::EndObject() {
DefaultValueObjectWriter* DefaultValueObjectWriter::StartList(
StringPiece name) {
- if (current_ == NULL) {
+ if (current_ == nullptr) {
std::vector<string> path;
root_.reset(CreateNewNode(string(name), &type_, LIST, DataPiece::NullData(),
false, path, suppress_empty_list_,
- preserve_proto_field_names_,
+ preserve_proto_field_names_, use_ints_for_enums_,
field_scrub_callback_.get()));
current_ = root_.get();
return this;
}
MaybePopulateChildrenOfAny(current_);
Node* child = current_->FindChild(name);
- if (child == NULL || child->kind() != LIST) {
- google::protobuf::scoped_ptr<Node> node(
- CreateNewNode(string(name), NULL, LIST, DataPiece::NullData(), false,
- child == NULL ? current_->path() : child->path(),
- suppress_empty_list_, preserve_proto_field_names_,
+ if (child == nullptr || child->kind() != LIST) {
+ 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()));
child = node.get();
current_->AddChild(node.release());
@@ -584,8 +587,8 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::StartList(
void DefaultValueObjectWriter::WriteRoot() {
root_->WriteTo(ow_);
- root_.reset(NULL);
- current_ = NULL;
+ root_.reset(nullptr);
+ current_ = nullptr;
}
DefaultValueObjectWriter* DefaultValueObjectWriter::EndList() {
@@ -601,7 +604,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::EndList() {
void DefaultValueObjectWriter::RenderDataPiece(StringPiece name,
const DataPiece& data) {
MaybePopulateChildrenOfAny(current_);
- if (current_->type() != NULL && current_->type()->name() == kAnyType &&
+ if (current_->type() != nullptr && current_->type()->name() == kAnyType &&
name == "@type") {
util::StatusOr<string> data_string = data.ToString();
if (data_string.ok()) {
@@ -621,18 +624,18 @@ void DefaultValueObjectWriter::RenderDataPiece(StringPiece name,
// other children of primitive type now. Otherwise, we should wait until
// the first value field is rendered before we populate the children,
// because the "value" field of a Any message could be omitted.
- if (current_->number_of_children() > 1 && current_->type() != NULL) {
+ if (current_->number_of_children() > 1 && current_->type() != nullptr) {
current_->PopulateChildren(typeinfo_);
}
}
}
Node* child = current_->FindChild(name);
- if (child == NULL || child->kind() != PRIMITIVE) {
+ if (child == nullptr || child->kind() != PRIMITIVE) {
// No children are found, creates a new child.
- google::protobuf::scoped_ptr<Node> node(
- CreateNewNode(string(name), NULL, PRIMITIVE, data, false,
- child == NULL ? current_->path() : child->path(),
- suppress_empty_list_, preserve_proto_field_names_,
+ 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()));
current_->AddChild(node.release());
} else {
diff --git a/src/google/protobuf/util/internal/default_value_objectwriter.h b/src/google/protobuf/util/internal/default_value_objectwriter.h
index 09c6d23f..7d245c9c 100644
--- a/src/google/protobuf/util/internal/default_value_objectwriter.h
+++ b/src/google/protobuf/util/internal/default_value_objectwriter.h
@@ -32,9 +32,6 @@
#define GOOGLE_PROTOBUF_UTIL_CONVERTER_DEFAULT_VALUE_OBJECTWRITER_H__
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <stack>
#include <vector>
@@ -77,7 +74,7 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
FieldScrubCallBack;
// A unique pointer to a DefaultValueObjectWriter::FieldScrubCallBack.
- typedef google::protobuf::scoped_ptr<FieldScrubCallBack> FieldScrubCallBackPtr;
+ typedef std::unique_ptr<FieldScrubCallBack> FieldScrubCallBackPtr;
DefaultValueObjectWriter(TypeResolver* type_resolver,
const google::protobuf::Type& type,
@@ -86,37 +83,37 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
virtual ~DefaultValueObjectWriter();
// ObjectWriter methods.
- virtual DefaultValueObjectWriter* StartObject(StringPiece name);
+ virtual DefaultValueObjectWriter* StartObject(StringPiece name) override;
- virtual DefaultValueObjectWriter* EndObject();
+ virtual DefaultValueObjectWriter* EndObject() override;
- virtual DefaultValueObjectWriter* StartList(StringPiece name);
+ virtual DefaultValueObjectWriter* StartList(StringPiece name) override;
- virtual DefaultValueObjectWriter* EndList();
+ virtual DefaultValueObjectWriter* EndList() override;
- virtual DefaultValueObjectWriter* RenderBool(StringPiece name, bool value);
+ virtual DefaultValueObjectWriter* RenderBool(StringPiece name, bool value) override;
- virtual DefaultValueObjectWriter* RenderInt32(StringPiece name, int32 value);
+ virtual DefaultValueObjectWriter* RenderInt32(StringPiece name, int32 value) override;
virtual DefaultValueObjectWriter* RenderUint32(StringPiece name,
- uint32 value);
+ uint32 value) override;
- virtual DefaultValueObjectWriter* RenderInt64(StringPiece name, int64 value);
+ virtual DefaultValueObjectWriter* RenderInt64(StringPiece name, int64 value) override;
virtual DefaultValueObjectWriter* RenderUint64(StringPiece name,
- uint64 value);
+ uint64 value) override;
virtual DefaultValueObjectWriter* RenderDouble(StringPiece name,
- double value);
+ double value) override;
- virtual DefaultValueObjectWriter* RenderFloat(StringPiece name, float value);
+ virtual DefaultValueObjectWriter* RenderFloat(StringPiece name, float value) override;
virtual DefaultValueObjectWriter* RenderString(StringPiece name,
- StringPiece value);
+ StringPiece value) override;
virtual DefaultValueObjectWriter* RenderBytes(StringPiece name,
- StringPiece value);
+ StringPiece value) override;
- virtual DefaultValueObjectWriter* RenderNull(StringPiece name);
+ virtual DefaultValueObjectWriter* RenderNull(StringPiece name) override;
// Register the callback for scrubbing of fields. Owership of
// field_scrub_callback pointer is also transferred to this class
@@ -131,6 +128,12 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
preserve_proto_field_names_ = value;
}
+ // 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;
+ }
+
protected:
enum NodeKind {
PRIMITIVE = 0,
@@ -150,7 +153,7 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
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 preserve_proto_field_names, bool use_ints_for_enums,
FieldScrubCallBack* field_scrub_callback);
virtual ~Node() {
for (int i = 0; i < children_.size(); ++i) {
@@ -233,6 +236,9 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
// Whether to preserve original proto field names
bool preserve_proto_field_names_;
+ // Whether to always print enums as ints
+ bool use_ints_for_enums_;
+
// Pointer to function for determining whether a field needs to be scrubbed
// or not. This callback is owned by the creator of this node.
FieldScrubCallBack* field_scrub_callback_;
@@ -256,11 +262,12 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
const std::vector<string>& path,
bool suppress_empty_list,
bool preserve_proto_field_names,
+ bool use_ints_for_enums,
FieldScrubCallBack* field_scrub_callback);
// Creates a DataPiece containing the default value of the type of the field.
static DataPiece CreateDefaultDataPieceForField(
- const google::protobuf::Field& field, const TypeInfo* typeinfo);
+ const google::protobuf::Field& field, const TypeInfo* typeinfo, bool use_ints_for_enums);
protected:
// Returns a pointer to current Node in tree.
@@ -272,7 +279,7 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
void MaybePopulateChildrenOfAny(Node* node);
// Writes the root_ node to ow_ and resets the root_ and current_ pointer to
- // NULL.
+ // nullptr.
void WriteRoot();
// Adds or replaces the data_ of a primitive child node.
@@ -282,7 +289,8 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
// there is no default. For proto3, where we cannot specify an explicit
// default, a zero value will always be returned.
static DataPiece FindEnumDefault(const google::protobuf::Field& field,
- const TypeInfo* typeinfo);
+ const TypeInfo* typeinfo,
+ bool use_ints_for_enums);
// Type information for all the types used in the descriptor. Used to find
// google::protobuf::Type of nested messages/enums.
@@ -297,7 +305,7 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
// The current Node. Owned by its parents.
Node* current_;
// The root Node.
- google::protobuf::scoped_ptr<Node> root_;
+ std::unique_ptr<Node> root_;
// The stack to hold the path of Nodes from current_ to root_;
std::stack<Node*> stack_;
@@ -307,6 +315,9 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
// Whether to preserve original proto field names
bool preserve_proto_field_names_;
+ // Whether to always print enums as ints
+ bool use_ints_for_enums_;
+
// Unique Pointer to function for determining whether a field needs to be
// scrubbed or not.
FieldScrubCallBackPtr field_scrub_callback_;
diff --git a/src/google/protobuf/util/internal/default_value_objectwriter_test.cc b/src/google/protobuf/util/internal/default_value_objectwriter_test.cc
index e1dd697a..0c4af61b 100644
--- a/src/google/protobuf/util/internal/default_value_objectwriter_test.cc
+++ b/src/google/protobuf/util/internal/default_value_objectwriter_test.cc
@@ -60,7 +60,7 @@ class BaseDefaultValueObjectWriterTest
TypeInfoTestHelper helper_;
MockObjectWriter mock_;
ExpectingObjectWriter expects_;
- google::protobuf::scoped_ptr<DefaultValueObjectWriter> testing_;
+ std::unique_ptr<DefaultValueObjectWriter> testing_;
};
// Tests to cover some basic DefaultValueObjectWriter use cases. More tests are
@@ -156,7 +156,7 @@ class DefaultValueObjectWriterSuppressListTest
: BaseDefaultValueObjectWriterTest(DefaultValueTest::descriptor()) {
testing_->set_suppress_empty_list(true);
}
- ~DefaultValueObjectWriterSuppressListTest() {}
+ ~DefaultValueObjectWriterSuppressListTest() override {}
};
INSTANTIATE_TEST_CASE_P(DifferentTypeInfoSourceTest,
diff --git a/src/google/protobuf/util/internal/error_listener.h b/src/google/protobuf/util/internal/error_listener.h
index 1dc814a3..e3baa224 100644
--- a/src/google/protobuf/util/internal/error_listener.h
+++ b/src/google/protobuf/util/internal/error_listener.h
@@ -33,9 +33,6 @@
#include <algorithm>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
#include <vector>
@@ -79,16 +76,16 @@ class LIBPROTOBUF_EXPORT ErrorListener {
class LIBPROTOBUF_EXPORT NoopErrorListener : public ErrorListener {
public:
NoopErrorListener() {}
- virtual ~NoopErrorListener() {}
+ virtual ~NoopErrorListener() override {}
virtual void InvalidName(const LocationTrackerInterface& loc,
- StringPiece invalid_name, StringPiece message) {}
+ StringPiece invalid_name, StringPiece message) override {}
- virtual void InvalidValue(const LocationTrackerInterface& loc,
- StringPiece type_name, StringPiece value) {}
+ virtual void InvalidValue(const LocationTrackerInterface &loc, StringPiece type_name,
+ StringPiece value) override {}
- virtual void MissingField(const LocationTrackerInterface& loc,
- StringPiece missing_name) {}
+ virtual void MissingField(const LocationTrackerInterface &loc,
+ StringPiece missing_name) override {}
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(NoopErrorListener);
diff --git a/src/google/protobuf/util/internal/field_mask_utility.cc b/src/google/protobuf/util/internal/field_mask_utility.cc
index 38835f67..778a4510 100644
--- a/src/google/protobuf/util/internal/field_mask_utility.cc
+++ b/src/google/protobuf/util/internal/field_mask_utility.cc
@@ -30,6 +30,7 @@
#include <google/protobuf/util/internal/field_mask_utility.h>
+#include <google/protobuf/util/internal/utility.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/status_macros.h>
@@ -53,7 +54,7 @@ string AppendPathSegmentToPrefix(StringPiece prefix, StringPiece segment) {
return prefix.ToString();
}
// If the segment is a map key, appends it to the prefix without the ".".
- if (segment.starts_with("[\"")) {
+ if (StringStartsWith(segment, "[\"")) {
return StrCat(prefix, segment);
}
return StrCat(prefix, ".", segment);
diff --git a/src/google/protobuf/util/internal/json_objectwriter.h b/src/google/protobuf/util/internal/json_objectwriter.h
index 81da0500..4c25b465 100644
--- a/src/google/protobuf/util/internal/json_objectwriter.h
+++ b/src/google/protobuf/util/internal/json_objectwriter.h
@@ -32,9 +32,6 @@
#define GOOGLE_PROTOBUF_UTIL_CONVERTER_JSON_OBJECTWRITER_H__
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
#include <google/protobuf/io/coded_stream.h>
@@ -89,7 +86,7 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
public:
JsonObjectWriter(StringPiece indent_string,
google::protobuf::io::CodedOutputStream* out)
- : element_(new Element(/*parent=*/NULL, /*is_json_object=*/false)),
+ : element_(new Element(/*parent=*/nullptr, /*is_json_object=*/false)),
stream_(out),
sink_(out),
indent_string_(indent_string.ToString()),
@@ -97,20 +94,20 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
virtual ~JsonObjectWriter();
// ObjectWriter methods.
- virtual JsonObjectWriter* StartObject(StringPiece name);
- virtual JsonObjectWriter* EndObject();
- virtual JsonObjectWriter* StartList(StringPiece name);
- virtual JsonObjectWriter* EndList();
- virtual JsonObjectWriter* RenderBool(StringPiece name, bool value);
- virtual JsonObjectWriter* RenderInt32(StringPiece name, int32 value);
- virtual JsonObjectWriter* RenderUint32(StringPiece name, uint32 value);
- virtual JsonObjectWriter* RenderInt64(StringPiece name, int64 value);
- 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* RenderBytes(StringPiece name, StringPiece value);
- virtual JsonObjectWriter* RenderNull(StringPiece name);
+ virtual JsonObjectWriter* StartObject(StringPiece name) override;
+ virtual JsonObjectWriter* EndObject() override;
+ virtual JsonObjectWriter* StartList(StringPiece name) override;
+ virtual JsonObjectWriter* EndList() override;
+ virtual JsonObjectWriter* RenderBool(StringPiece name, bool value) override;
+ virtual JsonObjectWriter* RenderInt32(StringPiece name, int32 value) override;
+ virtual JsonObjectWriter* RenderUint32(StringPiece name, uint32 value) override;
+ virtual JsonObjectWriter* RenderInt64(StringPiece name, int64 value) override;
+ virtual JsonObjectWriter* RenderUint64(StringPiece name, uint64 value) override;
+ virtual JsonObjectWriter* RenderDouble(StringPiece name, double value) override;
+ virtual JsonObjectWriter* RenderFloat(StringPiece name, float value) override;
+ virtual JsonObjectWriter* RenderString(StringPiece name, StringPiece value) override;
+ virtual JsonObjectWriter* RenderBytes(StringPiece name, StringPiece value) override;
+ virtual JsonObjectWriter* RenderNull(StringPiece name) override;
virtual JsonObjectWriter* RenderNullAsEmpty(StringPiece name);
void set_use_websafe_base64_for_bytes(bool value) {
@@ -146,17 +143,17 @@ 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 {
public:
explicit ByteSinkWrapper(google::protobuf::io::CodedOutputStream* stream)
: stream_(stream) {}
- virtual ~ByteSinkWrapper() {}
+ ~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);
}
@@ -211,7 +208,7 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
// Writes an individual character to the output.
void WriteChar(const char c) { stream_->WriteRaw(&c, sizeof(c)); }
- google::protobuf::scoped_ptr<Element> element_;
+ std::unique_ptr<Element> element_;
google::protobuf::io::CodedOutputStream* stream_;
ByteSinkWrapper sink_;
const string indent_string_;
diff --git a/src/google/protobuf/util/internal/json_objectwriter_test.cc b/src/google/protobuf/util/internal/json_objectwriter_test.cc
index 8cc588a6..0dc710c7 100644
--- a/src/google/protobuf/util/internal/json_objectwriter_test.cc
+++ b/src/google/protobuf/util/internal/json_objectwriter_test.cc
@@ -47,7 +47,7 @@ class JsonObjectWriterTest : public ::testing::Test {
JsonObjectWriterTest()
: str_stream_(new StringOutputStream(&output_)),
out_stream_(new CodedOutputStream(str_stream_)),
- ow_(NULL) {}
+ ow_(nullptr) {}
virtual ~JsonObjectWriterTest() {
delete ow_;
diff --git a/src/google/protobuf/util/internal/json_stream_parser.cc b/src/google/protobuf/util/internal/json_stream_parser.cc
index 2ada3583..1c63b31d 100644
--- a/src/google/protobuf/util/internal/json_stream_parser.cc
+++ b/src/google/protobuf/util/internal/json_stream_parser.cc
@@ -36,9 +36,6 @@
#include <cstdlib>
#include <cstring>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -157,7 +154,7 @@ util::Status JsonStreamParser::FinishParse() {
}
// Storage for UTF8-coerced string.
- google::protobuf::scoped_array<char> utf8;
+ std::unique_ptr<char[]> utf8;
if (coerce_to_utf8_) {
utf8.reset(new char[leftover_.size()]);
char* coerced = internal::UTF8CoerceToStructurallyValid(leftover_, utf8.get(), ' ');
diff --git a/src/google/protobuf/util/internal/object_location_tracker.h b/src/google/protobuf/util/internal/object_location_tracker.h
index 8586cecc..f9b90bc4 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 ""; }
+ string ToString() const override { return ""; }
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ObjectLocationTracker);
diff --git a/src/google/protobuf/util/internal/proto_writer.cc b/src/google/protobuf/util/internal/proto_writer.cc
index 8bebf2ab..b7a52db6 100644
--- a/src/google/protobuf/util/internal/proto_writer.cc
+++ b/src/google/protobuf/util/internal/proto_writer.cc
@@ -66,7 +66,7 @@ ProtoWriter::ProtoWriter(TypeResolver* type_resolver,
done_(false),
ignore_unknown_fields_(false),
use_lower_camel_for_enums_(false),
- element_(NULL),
+ element_(nullptr),
size_insert_(),
output_(output),
buffer_(),
@@ -85,7 +85,7 @@ ProtoWriter::ProtoWriter(const TypeInfo* typeinfo,
done_(false),
ignore_unknown_fields_(false),
use_lower_camel_for_enums_(false),
- element_(NULL),
+ element_(nullptr),
size_insert_(),
output_(output),
buffer_(),
@@ -99,14 +99,14 @@ ProtoWriter::~ProtoWriter() {
if (own_typeinfo_) {
delete typeinfo_;
}
- if (element_ == NULL) return;
+ if (element_ == nullptr) return;
// Cleanup explicitly in order to avoid destructor stack overflow when input
// is deeply nested.
// Cast to BaseElement to avoid doing additional checks (like missing fields)
// during pop().
- google::protobuf::scoped_ptr<BaseElement> element(
+ std::unique_ptr<BaseElement> element(
static_cast<BaseElement*>(element_.get())->pop<BaseElement>());
- while (element != NULL) {
+ while (element != nullptr) {
element.reset(element->pop<BaseElement>());
}
}
@@ -267,8 +267,9 @@ inline Status WriteString(int field_number, const DataPiece& data,
inline Status WriteEnum(int field_number, const DataPiece& data,
const google::protobuf::Enum* enum_type,
CodedOutputStream* stream,
- bool use_lower_camel_for_enums) {
- StatusOr<int> e = data.ToEnum(enum_type, use_lower_camel_for_enums);
+ 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);
}
@@ -294,9 +295,9 @@ std::set<const google::protobuf::Field*> GetRequiredFields(
ProtoWriter::ProtoElement::ProtoElement(const TypeInfo* typeinfo,
const google::protobuf::Type& type,
ProtoWriter* enclosing)
- : BaseElement(NULL),
+ : BaseElement(nullptr),
ow_(enclosing),
- parent_field_(NULL),
+ parent_field_(nullptr),
typeinfo_(typeinfo),
proto3_(type.syntax() == google::protobuf::SYNTAX_PROTO3),
type_(type),
@@ -374,7 +375,7 @@ ProtoWriter::ProtoElement* ProtoWriter::ProtoElement::pop() {
// all enclosing messages.
int size = ow_->size_insert_[size_index_].size;
int length = CodedOutputStream::VarintSize32(size);
- for (ProtoElement* e = parent(); e != NULL; e = e->parent()) {
+ for (ProtoElement* e = parent(); e != nullptr; e = e->parent()) {
// Only nested messages have size field, lists do not have size field.
if (e->size_index_ >= 0) {
ow_->size_insert_[e->size_index_].size += length;
@@ -394,7 +395,7 @@ void ProtoWriter::ProtoElement::RegisterField(
}
string ProtoWriter::ProtoElement::ToString() const {
- if (parent() == NULL) return "";
+ if (parent() == nullptr) return "";
string loc = parent()->ToString();
if (!ow_->IsRepeated(*parent_field_) ||
parent()->parent_field_ != parent_field_) {
@@ -439,7 +440,7 @@ void ProtoWriter::MissingField(StringPiece missing_name) {
ProtoWriter* ProtoWriter::StartObject(StringPiece name) {
// Starting the root message. Create the root ProtoElement and return.
- if (element_ == NULL) {
+ if (element_ == nullptr) {
if (!name.empty()) {
InvalidName(name, "Root element should not be named.");
}
@@ -447,9 +448,9 @@ ProtoWriter* ProtoWriter::StartObject(StringPiece name) {
return this;
}
- const google::protobuf::Field* field = NULL;
+ const google::protobuf::Field* field = nullptr;
field = BeginNamed(name, false);
- if (field == NULL) return this;
+ if (field == nullptr) return this;
// Check to see if this field is a oneof and that no oneof in that group has
// already been set.
@@ -459,7 +460,7 @@ ProtoWriter* ProtoWriter::StartObject(StringPiece name) {
}
const google::protobuf::Type* type = LookupType(field);
- if (type == NULL) {
+ if (type == nullptr) {
++invalid_depth_;
InvalidName(name,
StrCat("Missing descriptor for field: ", field->type_url()));
@@ -475,14 +476,14 @@ ProtoWriter* ProtoWriter::EndObject() {
return this;
}
- if (element_ != NULL) {
+ if (element_ != nullptr) {
element_.reset(element_->pop());
}
// If ending the root element,
// then serialize the full message with calculated sizes.
- if (element_ == NULL) {
+ if (element_ == nullptr) {
WriteRootMessage();
}
return this;
@@ -490,7 +491,7 @@ ProtoWriter* ProtoWriter::EndObject() {
ProtoWriter* ProtoWriter::StartList(StringPiece name) {
const google::protobuf::Field* field = BeginNamed(name, true);
- if (field == NULL) return this;
+ if (field == nullptr) return this;
if (!ValidOneof(*field, name)) {
++invalid_depth_;
@@ -498,7 +499,7 @@ ProtoWriter* ProtoWriter::StartList(StringPiece name) {
}
const google::protobuf::Type* type = LookupType(field);
- if (type == NULL) {
+ if (type == nullptr) {
++invalid_depth_;
InvalidName(name,
StrCat("Missing descriptor for field: ", field->type_url()));
@@ -511,7 +512,7 @@ ProtoWriter* ProtoWriter::StartList(StringPiece name) {
ProtoWriter* ProtoWriter::EndList() {
if (invalid_depth_ > 0) {
--invalid_depth_;
- } else if (element_ != NULL) {
+ } else if (element_ != nullptr) {
element_.reset(element_->pop());
}
return this;
@@ -523,12 +524,12 @@ ProtoWriter* ProtoWriter::RenderDataPiece(StringPiece name,
if (invalid_depth_ > 0) return this;
const google::protobuf::Field* field = Lookup(name);
- if (field == NULL) return this;
+ if (field == nullptr) return this;
if (!ValidOneof(*field, name)) return this;
const google::protobuf::Type* type = LookupType(field);
- if (type == NULL) {
+ if (type == nullptr) {
InvalidName(name,
StrCat("Missing descriptor for field: ", field->type_url()));
return this;
@@ -539,7 +540,7 @@ ProtoWriter* ProtoWriter::RenderDataPiece(StringPiece name,
bool ProtoWriter::ValidOneof(const google::protobuf::Field& field,
StringPiece unnormalized_name) {
- if (element_ == NULL) return true;
+ if (element_ == nullptr) return true;
if (field.oneof_index() > 0) {
if (element_->IsOneofIndexTaken(field.oneof_index())) {
@@ -665,7 +666,8 @@ ProtoWriter* ProtoWriter::RenderPrimitiveField(
case google::protobuf::Field_Kind_TYPE_ENUM: {
status = WriteEnum(field.number(), data,
typeinfo_->GetEnumByTypeUrl(field.type_url()),
- stream_.get(), use_lower_camel_for_enums_);
+ stream_.get(), use_lower_camel_for_enums_,
+ ignore_unknown_fields_);
break;
}
default: // TYPE_GROUP or TYPE_MESSAGE
@@ -692,18 +694,18 @@ const google::protobuf::Field* ProtoWriter::BeginNamed(StringPiece name,
bool is_list) {
if (invalid_depth_ > 0) {
++invalid_depth_;
- return NULL;
+ return nullptr;
}
const google::protobuf::Field* field = Lookup(name);
- if (field == NULL) {
+ if (field == nullptr) {
++invalid_depth_;
// InvalidName() already called in Lookup().
- return NULL;
+ return nullptr;
}
if (is_list && !IsRepeated(*field)) {
++invalid_depth_;
InvalidName(name, "Proto field is not repeating, cannot start list.");
- return NULL;
+ return nullptr;
}
return field;
}
@@ -711,23 +713,23 @@ const google::protobuf::Field* ProtoWriter::BeginNamed(StringPiece name,
const google::protobuf::Field* ProtoWriter::Lookup(
StringPiece unnormalized_name) {
ProtoElement* e = element();
- if (e == NULL) {
+ if (e == nullptr) {
InvalidName(unnormalized_name, "Root element must be a message.");
- return NULL;
+ return nullptr;
}
if (unnormalized_name.empty()) {
// Objects in repeated field inherit the same field descriptor.
- if (e->parent_field() == NULL) {
+ if (e->parent_field() == nullptr) {
InvalidName(unnormalized_name, "Proto fields must have a name.");
} else if (!IsRepeated(*e->parent_field())) {
InvalidName(unnormalized_name, "Proto fields must have a name.");
- return NULL;
+ return nullptr;
}
return e->parent_field();
}
const google::protobuf::Field* field =
typeinfo_->FindField(&e->type(), unnormalized_name);
- if (field == NULL && !ignore_unknown_fields_) {
+ if (field == nullptr && !ignore_unknown_fields_) {
InvalidName(unnormalized_name, "Cannot find field.");
}
return field;
@@ -746,7 +748,7 @@ void ProtoWriter::WriteRootMessage() {
int curr_pos = 0;
// Calls the destructor of CodedOutputStream to remove any uninitialized
// memory from the Cord before we read it.
- stream_.reset(NULL);
+ stream_.reset(nullptr);
const void* data;
int length;
google::protobuf::io::ArrayInputStream input_stream(buffer_.data(), buffer_.size());
diff --git a/src/google/protobuf/util/internal/proto_writer.h b/src/google/protobuf/util/internal/proto_writer.h
index 0db8485c..5bdafcc9 100644
--- a/src/google/protobuf/util/internal/proto_writer.h
+++ b/src/google/protobuf/util/internal/proto_writer.h
@@ -78,43 +78,43 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
// 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();
+ virtual ~ProtoWriter() override;
// ObjectWriter methods.
- ProtoWriter* StartObject(StringPiece name);
- ProtoWriter* EndObject();
- ProtoWriter* StartList(StringPiece name);
- ProtoWriter* EndList();
- ProtoWriter* RenderBool(StringPiece name, bool value) {
+ ProtoWriter* StartObject(StringPiece name) override;
+ ProtoWriter* EndObject() override;
+ ProtoWriter* StartList(StringPiece name) override;
+ ProtoWriter* EndList() override;
+ ProtoWriter* RenderBool(StringPiece name, bool value) override {
return RenderDataPiece(name, DataPiece(value));
}
- ProtoWriter* RenderInt32(StringPiece name, int32 value) {
+ ProtoWriter* RenderInt32(StringPiece name, int32 value) override {
return RenderDataPiece(name, DataPiece(value));
}
- ProtoWriter* RenderUint32(StringPiece name, uint32 value) {
+ ProtoWriter* RenderUint32(StringPiece name, uint32 value) override {
return RenderDataPiece(name, DataPiece(value));
}
- ProtoWriter* RenderInt64(StringPiece name, int64 value) {
+ ProtoWriter* RenderInt64(StringPiece name, int64 value) override {
return RenderDataPiece(name, DataPiece(value));
}
- ProtoWriter* RenderUint64(StringPiece name, uint64 value) {
+ ProtoWriter* RenderUint64(StringPiece name, uint64 value) override {
return RenderDataPiece(name, DataPiece(value));
}
- ProtoWriter* RenderDouble(StringPiece name, double value) {
+ ProtoWriter* RenderDouble(StringPiece name, double value) override {
return RenderDataPiece(name, DataPiece(value));
}
- ProtoWriter* RenderFloat(StringPiece name, float value) {
+ ProtoWriter* RenderFloat(StringPiece name, float value) override {
return RenderDataPiece(name, DataPiece(value));
}
- ProtoWriter* RenderString(StringPiece name, StringPiece value) {
+ 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()));
}
- ProtoWriter* RenderNull(StringPiece name) {
+ ProtoWriter* RenderNull(StringPiece name) override {
return RenderDataPiece(name, DataPiece::NullData());
}
@@ -126,11 +126,11 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
// Returns the location tracker to use for tracking locations for errors.
const LocationTrackerInterface& location() {
- return element_ != NULL ? *element_ : *tracker_;
+ return element_ != nullptr ? *element_ : *tracker_;
}
// When true, we finished writing to output a complete message.
- bool done() { return done_; }
+ bool done() override { return done_; }
// Returns the proto stream object.
google::protobuf::io::CodedOutputStream* stream() { return stream_.get(); }
@@ -163,7 +163,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() {}
+ virtual ~ProtoElement() override {}
// Called just before the destructor for clean up:
// - reports any missing required fields
@@ -173,7 +173,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
ProtoElement* pop();
// Accessors
- // parent_field() may be NULL if we are at root.
+ // parent_field() may be nullptr if we are at root.
const google::protobuf::Field* parent_field() const {
return parent_field_;
}
@@ -183,9 +183,9 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
void RegisterField(const google::protobuf::Field* field);
// To report location on error messages.
- virtual string ToString() const;
+ virtual string ToString() const override;
- virtual ProtoElement* parent() const {
+ virtual ProtoElement* parent() const override {
return static_cast<ProtoElement*>(BaseElement::parent());
}
@@ -204,7 +204,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
ProtoWriter* ow_;
// Describes the element as a field in the parent message.
- // parent_field_ is NULL if and only if this element is the root element.
+ // parent_field_ is nullptr if and only if this element is the root element.
const google::protobuf::Field* parent_field_;
// TypeInfo to lookup types.
@@ -242,7 +242,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
ProtoWriter(const TypeInfo* typeinfo, const google::protobuf::Type& type,
strings::ByteSink* output, ErrorListener* listener);
- ProtoElement* element() { return element_.get(); }
+ ProtoElement* element() override { return element_.get(); }
// Helper methods for calling ErrorListener. See error_listener.h.
void InvalidName(StringPiece unknown_name, StringPiece message);
@@ -259,7 +259,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
// extensions are found.
const google::protobuf::Field* Lookup(StringPiece name);
- // Lookup the field type in the type descriptor. Returns NULL if the type
+ // Lookup the field type in the type descriptor. Returns nullptr if the type
// is not known.
const google::protobuf::Type* LookupType(
const google::protobuf::Field* field);
@@ -309,7 +309,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
// Indicates whether we finished writing root message completely.
bool done_;
- // If true, don't report unknown field names to the listener.
+ // If true, don't report unknown field names and enum values to the listener.
bool ignore_unknown_fields_;
// If true, check if enum name in camel case or without underscore matches the
@@ -321,7 +321,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
// size_insert_: sizes of nested messages.
// pos - position to insert the size field.
// size - size value to be inserted.
- google::protobuf::scoped_ptr<ProtoElement> element_;
+ std::unique_ptr<ProtoElement> element_;
std::deque<SizeInfo> size_insert_;
// Variables for output generation:
@@ -332,7 +332,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
strings::ByteSink* output_;
string buffer_;
google::protobuf::io::StringOutputStream adapter_;
- google::protobuf::scoped_ptr<google::protobuf::io::CodedOutputStream> stream_;
+ std::unique_ptr<google::protobuf::io::CodedOutputStream> stream_;
// Variables for error tracking and reporting:
// listener_ : a place to report any errors found.
@@ -340,7 +340,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
// tracker_ : the root location tracker interface.
ErrorListener* listener_;
int invalid_depth_;
- google::protobuf::scoped_ptr<LocationTrackerInterface> tracker_;
+ std::unique_ptr<LocationTrackerInterface> tracker_;
GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(ProtoWriter);
};
diff --git a/src/google/protobuf/util/internal/protostream_objectsource.cc b/src/google/protobuf/util/internal/protostream_objectsource.cc
index 72ad5a7a..b0d86c17 100644
--- a/src/google/protobuf/util/internal/protostream_objectsource.cc
+++ b/src/google/protobuf/util/internal/protostream_objectsource.cc
@@ -73,14 +73,14 @@ namespace {
static int kDefaultMaxRecursionDepth = 64;
-// Finds a field with the given number. NULL if none found.
+// Finds a field with the given number. nullptr if none found.
const google::protobuf::Field* FindFieldByNumber(
const google::protobuf::Type& type, int number);
// Returns true if the field is packable.
bool IsPackable(const google::protobuf::Field& field);
-// Finds an enum value with the given number. NULL if none found.
+// Finds an enum value with the given number. nullptr if none found.
const google::protobuf::EnumValue* FindEnumValueByNumber(
const google::protobuf::Enum& tech_enum, int number);
@@ -127,7 +127,7 @@ ProtoStreamObjectSource::ProtoStreamObjectSource(
render_unknown_fields_(false),
render_unknown_enum_values_(true),
add_trailing_zeros_for_timestamp_and_duration_(false) {
- GOOGLE_LOG_IF(DFATAL, stream == NULL) << "Input stream is NULL.";
+ GOOGLE_LOG_IF(DFATAL, stream == nullptr) << "Input stream is nullptr.";
}
ProtoStreamObjectSource::ProtoStreamObjectSource(
@@ -145,7 +145,7 @@ ProtoStreamObjectSource::ProtoStreamObjectSource(
render_unknown_fields_(false),
render_unknown_enum_values_(true),
add_trailing_zeros_for_timestamp_and_duration_(false) {
- GOOGLE_LOG_IF(DFATAL, stream == NULL) << "Input stream is NULL.";
+ GOOGLE_LOG_IF(DFATAL, stream == nullptr) << "Input stream is nullptr.";
}
ProtoStreamObjectSource::~ProtoStreamObjectSource() {
@@ -165,7 +165,7 @@ const google::protobuf::Field* ProtoStreamObjectSource::FindAndVerifyField(
const google::protobuf::Field* field = FindFieldByNumber(type, tag >> 3);
// Verify if the field corresponds to the wire type in tag.
// If there is any discrepancy, mark the field as not found.
- if (field != NULL) {
+ if (field != nullptr) {
WireFormatLite::WireType expected_type =
WireFormatLite::WireTypeForFieldType(
static_cast<WireFormatLite::FieldType>(field->kind()));
@@ -173,7 +173,7 @@ const google::protobuf::Field* ProtoStreamObjectSource::FindAndVerifyField(
if (actual_type != expected_type &&
(!IsPackable(*field) ||
actual_type != WireFormatLite::WIRETYPE_LENGTH_DELIMITED)) {
- field = NULL;
+ field = nullptr;
}
}
return field;
@@ -186,11 +186,11 @@ Status ProtoStreamObjectSource::WriteMessage(const google::protobuf::Type& type,
ObjectWriter* ow) const {
const TypeRenderer* type_renderer = FindTypeRenderer(type.name());
- if (type_renderer != NULL) {
+ if (type_renderer != nullptr) {
return (*type_renderer)(this, type, name, ow);
}
- const google::protobuf::Field* field = NULL;
+ const google::protobuf::Field* field = nullptr;
string field_name;
// last_tag set to dummy value that is different from tag.
uint32 tag = stream_->ReadTag(), last_tag = tag + 1;
@@ -203,7 +203,7 @@ Status ProtoStreamObjectSource::WriteMessage(const google::protobuf::Type& type,
if (tag != last_tag) { // Update field only if tag is changed.
last_tag = tag;
field = FindAndVerifyField(type, tag);
- if (field != NULL) {
+ if (field != nullptr) {
if (preserve_proto_field_names_) {
field_name = field->name();
} else {
@@ -211,11 +211,11 @@ Status ProtoStreamObjectSource::WriteMessage(const google::protobuf::Type& type,
}
}
}
- if (field == NULL) {
+ if (field == nullptr) {
// If we didn't find a field, skip this unknown tag.
// TODO(wpoon): Check return boolean value.
WireFormat::SkipField(stream_, tag,
- render_unknown_fields_ ? &unknown_fields : NULL);
+ render_unknown_fields_ ? &unknown_fields : nullptr);
tag = stream_->ReadTag();
continue;
}
@@ -282,8 +282,8 @@ StatusOr<uint32> ProtoStreamObjectSource::RenderMap(
for (uint32 tag = stream_->ReadTag(); tag != 0; tag = stream_->ReadTag()) {
const google::protobuf::Field* field =
FindAndVerifyField(*field_type, tag);
- if (field == NULL) {
- WireFormat::SkipField(stream_, tag, NULL);
+ if (field == nullptr) {
+ WireFormat::SkipField(stream_, tag, nullptr);
continue;
}
// Map field numbers are key = 1 and value = 2
@@ -294,7 +294,7 @@ StatusOr<uint32> ProtoStreamObjectSource::RenderMap(
// An absent map key is treated as the default.
const google::protobuf::Field* key_field =
FindFieldByNumber(*field_type, 1);
- if (key_field == NULL) {
+ if (key_field == nullptr) {
// The Type info for this map entry is incorrect. It should always
// have a field named "key" and with field number 1.
return Status(util::error::INTERNAL, "Invalid map entry.");
@@ -525,7 +525,7 @@ Status ProtoStreamObjectSource::RenderStruct(const ProtoStreamObjectSource* os,
const google::protobuf::Type& type,
StringPiece field_name,
ObjectWriter* ow) {
- const google::protobuf::Field* field = NULL;
+ const google::protobuf::Field* field = nullptr;
uint32 tag = os->stream_->ReadTag();
ow->StartObject(field_name);
while (tag != 0) {
@@ -543,12 +543,12 @@ Status ProtoStreamObjectSource::RenderStruct(const ProtoStreamObjectSource* os,
Status ProtoStreamObjectSource::RenderStructValue(
const ProtoStreamObjectSource* os, const google::protobuf::Type& type,
StringPiece field_name, ObjectWriter* ow) {
- const google::protobuf::Field* field = NULL;
+ const google::protobuf::Field* field = nullptr;
for (uint32 tag = os->stream_->ReadTag(); tag != 0;
tag = os->stream_->ReadTag()) {
field = os->FindAndVerifyField(type, tag);
- if (field == NULL) {
- WireFormat::SkipField(os->stream_, tag, NULL);
+ if (field == nullptr) {
+ WireFormat::SkipField(os->stream_, tag, nullptr);
continue;
}
RETURN_IF_ERROR(os->RenderField(field, field_name, ow));
@@ -571,8 +571,8 @@ Status ProtoStreamObjectSource::RenderStructListValue(
while (tag != 0) {
const google::protobuf::Field* field = os->FindAndVerifyField(type, tag);
- if (field == NULL) {
- WireFormat::SkipField(os->stream_, tag, NULL);
+ if (field == nullptr) {
+ WireFormat::SkipField(os->stream_, tag, nullptr);
tag = os->stream_->ReadTag();
continue;
}
@@ -593,8 +593,8 @@ Status ProtoStreamObjectSource::RenderAny(const ProtoStreamObjectSource* os,
// First read out the type_url and value from the proto stream
for (tag = os->stream_->ReadTag(); tag != 0; tag = os->stream_->ReadTag()) {
const google::protobuf::Field* field = os->FindAndVerifyField(type, tag);
- if (field == NULL) {
- WireFormat::SkipField(os->stream_, tag, NULL);
+ if (field == nullptr) {
+ WireFormat::SkipField(os->stream_, tag, nullptr);
continue;
}
// 'type_url' has field number of 1 and 'value' has field number 2
@@ -648,6 +648,13 @@ Status ProtoStreamObjectSource::RenderAny(const ProtoStreamObjectSource* os,
// 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);
@@ -667,7 +674,7 @@ Status ProtoStreamObjectSource::RenderFieldMask(
tag = os->stream_->ReadTag()) {
if (paths_field_tag == 0) {
const google::protobuf::Field* field = os->FindAndVerifyField(type, tag);
- if (field != NULL && field->number() == 1 &&
+ if (field != nullptr && field->number() == 1 &&
field->name() == "paths") {
paths_field_tag = tag;
}
@@ -754,7 +761,7 @@ Status ProtoStreamObjectSource::RenderField(
// Get the nested message type for this field.
const google::protobuf::Type* type =
typeinfo_->GetTypeByTypeUrl(field->type_url());
- if (type == NULL) {
+ if (type == nullptr) {
return Status(util::error::INTERNAL,
StrCat("Invalid configuration. Could not find the type: ",
field->type_url()));
@@ -763,7 +770,7 @@ Status ProtoStreamObjectSource::RenderField(
// Short-circuit any special type rendering to save call-stack space.
const TypeRenderer* type_renderer = FindTypeRenderer(type->name());
- bool use_type_renderer = type_renderer != NULL;
+ bool use_type_renderer = type_renderer != nullptr;
if (use_type_renderer) {
RETURN_IF_ERROR((*type_renderer)(this, *type, field_name, ow));
@@ -873,14 +880,15 @@ Status ProtoStreamObjectSource::RenderNonMessageField(
typeinfo_->GetEnumByTypeUrl(field->type_url());
// Lookup the name of the enum, and render that. Unknown enum values
// are printed as integers.
- if (en != NULL) {
+ if (en != nullptr) {
const google::protobuf::EnumValue* enum_value =
FindEnumValueByNumber(*en, buffer32);
- if (enum_value != NULL) {
+ if (enum_value != nullptr) {
if (use_ints_for_enums_) {
ow->RenderInt32(field_name, buffer32);
} else if (use_lower_camel_for_enums_) {
- ow->RenderString(field_name, ToCamelCase(enum_value->name()));
+ ow->RenderString(field_name,
+ EnumValueNameToLowerCamelCase(enum_value->name()));
} else {
ow->RenderString(field_name, enum_value->name());
}
@@ -1002,10 +1010,10 @@ const string ProtoStreamObjectSource::ReadFieldValueAsString(
const google::protobuf::Enum* en =
typeinfo_->GetEnumByTypeUrl(field.type_url());
// Lookup the name of the enum, and render that. Skips unknown enums.
- if (en != NULL) {
+ if (en != nullptr) {
const google::protobuf::EnumValue* enum_value =
FindEnumValueByNumber(*en, buffer32);
- if (enum_value != NULL) {
+ if (enum_value != nullptr) {
result = enum_value->name();
}
}
@@ -1049,8 +1057,8 @@ std::pair<int64, int32> ProtoStreamObjectSource::ReadSecondsAndNanos(
for (tag = stream_->ReadTag(); tag != 0; tag = stream_->ReadTag()) {
const google::protobuf::Field* field = FindAndVerifyField(type, tag);
- if (field == NULL) {
- WireFormat::SkipField(stream_, tag, NULL);
+ if (field == nullptr) {
+ WireFormat::SkipField(stream_, tag, nullptr);
continue;
}
// 'seconds' has field number of 1 and 'nanos' has field number 2
@@ -1088,7 +1096,7 @@ const google::protobuf::Field* FindFieldByNumber(
return &type.fields(i);
}
}
- return NULL;
+ return nullptr;
}
// TODO(skarvaje): Replace FieldDescriptor by implementing IsTypePackable()
@@ -1109,7 +1117,7 @@ const google::protobuf::EnumValue* FindEnumValueByNumber(
return &ev;
}
}
- return NULL;
+ return nullptr;
}
// TODO(skarvaje): Look into optimizing this by not doing computation on
diff --git a/src/google/protobuf/util/internal/protostream_objectsource.h b/src/google/protobuf/util/internal/protostream_objectsource.h
index b56efdf4..acd081d9 100644
--- a/src/google/protobuf/util/internal/protostream_objectsource.h
+++ b/src/google/protobuf/util/internal/protostream_objectsource.h
@@ -78,9 +78,9 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
TypeResolver* type_resolver,
const google::protobuf::Type& type);
- virtual ~ProtoStreamObjectSource();
+ virtual ~ProtoStreamObjectSource() override;
- virtual util::Status NamedWriteTo(StringPiece name, ObjectWriter* ow) const;
+ virtual 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.
diff --git a/src/google/protobuf/util/internal/protostream_objectsource_test.cc b/src/google/protobuf/util/internal/protostream_objectsource_test.cc
index 36bb1ba9..4d86b856 100644
--- a/src/google/protobuf/util/internal/protostream_objectsource_test.cc
+++ b/src/google/protobuf/util/internal/protostream_objectsource_test.cc
@@ -31,9 +31,6 @@
#include <google/protobuf/util/internal/protostream_objectsource.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <sstream>
#include <google/protobuf/stubs/casts.h>
@@ -103,6 +100,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());
@@ -122,10 +120,11 @@ class ProtostreamObjectSourceTest
ArrayInputStream arr_stream(proto.data(), proto.size());
CodedInputStream in_stream(&arr_stream);
- google::protobuf::scoped_ptr<ProtoStreamObjectSource> os(
+ std::unique_ptr<ProtoStreamObjectSource> os(
helper_.NewProtoSource(&in_stream, GetTypeUrl(descriptor)));
if (use_lower_camel_for_enums_) os->set_use_lower_camel_for_enums(true);
if (use_ints_for_enums_) os->set_use_ints_for_enums(true);
+ if (use_preserve_proto_field_names_) os->set_preserve_proto_field_names(true);
os->set_max_recursion_depth(64);
return os->WriteTo(&mock_);
}
@@ -275,6 +274,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) {
@@ -287,6 +288,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_;
};
@@ -490,7 +492,7 @@ TEST_P(ProtostreamObjectSourceTest,
DoTest(book, Book::descriptor());
}
-TEST_P(ProtostreamObjectSourceTest, LowerCamelEnumOutputTest) {
+TEST_P(ProtostreamObjectSourceTest, LowerCamelEnumOutputMacroCase) {
Book book;
book.set_type(Book::ACTION_AND_ADVENTURE);
@@ -500,6 +502,26 @@ TEST_P(ProtostreamObjectSourceTest, LowerCamelEnumOutputTest) {
DoTest(book, Book::descriptor());
}
+TEST_P(ProtostreamObjectSourceTest, LowerCamelEnumOutputSnakeCase) {
+ Book book;
+ book.set_type(Book::arts_and_photography);
+
+ UseLowerCamelForEnums();
+
+ ow_.StartObject("")->RenderString("type", "artsAndPhotography")->EndObject();
+ DoTest(book, Book::descriptor());
+}
+
+TEST_P(ProtostreamObjectSourceTest, LowerCamelEnumOutputWithNumber) {
+ Book book;
+ book.set_type(Book::I18N_Tech);
+
+ UseLowerCamelForEnums();
+
+ ow_.StartObject("")->RenderString("type", "i18nTech")->EndObject();
+ DoTest(book, Book::descriptor());
+}
+
TEST_P(ProtostreamObjectSourceTest, EnumCaseIsUnchangedByDefault) {
Book book;
book.set_type(Book::ACTION_AND_ADVENTURE);
@@ -519,6 +541,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;
@@ -752,6 +784,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 97f96819..a1a7030a 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter.cc
+++ b/src/google/protobuf/util/internal/protostream_objectwriter.cc
@@ -62,7 +62,7 @@ ProtoStreamObjectWriter::ProtoStreamObjectWriter(
const ProtoStreamObjectWriter::Options& options)
: ProtoWriter(type_resolver, type, output, listener),
master_type_(type),
- current_(NULL),
+ current_(nullptr),
options_(options) {
set_ignore_unknown_fields(options_.ignore_unknown_fields);
set_use_lower_camel_for_enums(options_.use_lower_camel_for_enums);
@@ -73,18 +73,18 @@ ProtoStreamObjectWriter::ProtoStreamObjectWriter(
strings::ByteSink* output, ErrorListener* listener)
: ProtoWriter(typeinfo, type, output, listener),
master_type_(type),
- current_(NULL),
+ current_(nullptr),
options_(ProtoStreamObjectWriter::Options::Defaults()) {}
ProtoStreamObjectWriter::~ProtoStreamObjectWriter() {
- if (current_ == NULL) return;
+ if (current_ == nullptr) return;
// Cleanup explicitly in order to avoid destructor stack overflow when input
// is deeply nested.
// Cast to BaseElement to avoid doing additional checks (like missing fields)
// during pop().
- google::protobuf::scoped_ptr<BaseElement> element(
+ std::unique_ptr<BaseElement> element(
static_cast<BaseElement*>(current_.get())->pop<BaseElement>());
- while (element != NULL) {
+ while (element != nullptr) {
element.reset(element->pop<BaseElement>());
}
}
@@ -186,7 +186,7 @@ ProtoStreamObjectWriter::AnyWriter::AnyWriter(ProtoStreamObjectWriter* parent)
output_(&data_),
depth_(0),
is_well_known_type_(false),
- well_known_type_render_(NULL) {}
+ well_known_type_render_(nullptr) {}
ProtoStreamObjectWriter::AnyWriter::~AnyWriter() {}
@@ -195,7 +195,7 @@ void ProtoStreamObjectWriter::AnyWriter::StartObject(StringPiece name) {
// If an object writer is absent, that means we have not called StartAny()
// before reaching here, which happens when we have data before the "@type"
// field.
- if (ow_ == NULL) {
+ if (ow_ == nullptr) {
// Save data before the "@type" field for later replay.
uninterpreted_events_.push_back(Event(Event::START_OBJECT, name));
} else if (is_well_known_type_ && depth_ == 1) {
@@ -217,7 +217,7 @@ void ProtoStreamObjectWriter::AnyWriter::StartObject(StringPiece name) {
bool ProtoStreamObjectWriter::AnyWriter::EndObject() {
--depth_;
- if (ow_ == NULL) {
+ if (ow_ == nullptr) {
if (depth_ >= 0) {
// Save data before the "@type" field for later replay.
uninterpreted_events_.push_back(Event(Event::END_OBJECT));
@@ -239,7 +239,7 @@ bool ProtoStreamObjectWriter::AnyWriter::EndObject() {
void ProtoStreamObjectWriter::AnyWriter::StartList(StringPiece name) {
++depth_;
- if (ow_ == NULL) {
+ if (ow_ == nullptr) {
// Save data before the "@type" field for later replay.
uninterpreted_events_.push_back(Event(Event::START_LIST, name));
} else if (is_well_known_type_ && depth_ == 1) {
@@ -260,7 +260,7 @@ void ProtoStreamObjectWriter::AnyWriter::EndList() {
GOOGLE_LOG(DFATAL) << "Mismatched EndList found, should not be possible";
depth_ = 0;
}
- if (ow_ == NULL) {
+ if (ow_ == nullptr) {
// Save data before the "@type" field for later replay.
uninterpreted_events_.push_back(Event(Event::END_LIST));
} else {
@@ -272,9 +272,9 @@ void ProtoStreamObjectWriter::AnyWriter::RenderDataPiece(
StringPiece name, const DataPiece& value) {
// Start an Any only at depth_ 0. Other RenderDataPiece calls with "@type"
// should go to the contained ow_ as they indicate nested Anys.
- if (depth_ == 0 && ow_ == NULL && name == "@type") {
+ if (depth_ == 0 && ow_ == nullptr && name == "@type") {
StartAny(value);
- } else if (ow_ == NULL) {
+ } else if (ow_ == nullptr) {
// Save data before the "@type" field.
uninterpreted_events_.push_back(Event(name, value));
} else if (depth_ == 0 && is_well_known_type_) {
@@ -283,7 +283,7 @@ void ProtoStreamObjectWriter::AnyWriter::RenderDataPiece(
"Expect a \"value\" field for well-known types.");
invalid_ = true;
}
- if (well_known_type_render_ == NULL) {
+ if (well_known_type_render_ == nullptr) {
// Only Any and Struct don't have a special type render but both of
// them expect a JSON object (i.e., a StartObject() call).
if (value.type() != DataPiece::TYPE_NULL && !invalid_) {
@@ -327,7 +327,7 @@ void ProtoStreamObjectWriter::AnyWriter::StartAny(const DataPiece& value) {
const google::protobuf::Type* type = resolved_type.ValueOrDie();
well_known_type_render_ = FindTypeRenderer(type_url_);
- if (well_known_type_render_ != NULL ||
+ if (well_known_type_render_ != nullptr ||
// Explicitly list Any and Struct here because they don't have a
// custom renderer.
type->name() == kAnyType || type->name() == kStructType) {
@@ -360,7 +360,7 @@ void ProtoStreamObjectWriter::AnyWriter::StartAny(const DataPiece& value) {
}
void ProtoStreamObjectWriter::AnyWriter::WriteAny() {
- if (ow_ == NULL) {
+ if (ow_ == nullptr) {
if (uninterpreted_events_.empty()) {
// We never got any content, so just return immediately, which is
// equivalent to writing an empty Any.
@@ -421,7 +421,7 @@ void ProtoStreamObjectWriter::AnyWriter::Event::DeepCopy() {
ProtoStreamObjectWriter::Item::Item(ProtoStreamObjectWriter* enclosing,
ItemType item_type, bool is_placeholder,
bool is_list)
- : BaseElement(NULL),
+ : BaseElement(nullptr),
ow_(enclosing),
any_(),
item_type_(item_type),
@@ -467,7 +467,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartObject(
// Starting the root message. Create the root Item and return.
// ANY message type does not need special handling, just set the ItemType
// to ANY.
- if (current_ == NULL) {
+ if (current_ == nullptr) {
ProtoWriter::StartObject(name);
current_.reset(new Item(
this, master_type_.name() == kAnyType ? Item::ANY : Item::MESSAGE,
@@ -534,21 +534,21 @@ 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;
// If top of stack is g.p.Struct type, start the struct the map field within
// it.
- if (element() != NULL && IsStruct(*element()->parent_field())) {
+ if (element() != nullptr && IsStruct(*element()->parent_field())) {
// Render "fields": [
Push("fields", Item::MAP, true, true);
return this;
}
// If top of stack is g.p.Value type, start the Struct within it.
- if (element() != NULL && IsStructValue(*element()->parent_field())) {
+ if (element() != nullptr && IsStructValue(*element()->parent_field())) {
// Render
// "struct_value": {
// "fields": [
@@ -559,7 +559,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartObject(
}
const google::protobuf::Field* field = BeginNamed(name, false);
- if (field == NULL) return this;
+ if (field == nullptr) return this;
if (IsStruct(*field)) {
// Start a struct object.
@@ -607,7 +607,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::EndObject() {
return this;
}
- if (current_ == NULL) return this;
+ if (current_ == nullptr) return this;
if (current_->IsAny()) {
if (current_->any()->EndObject()) return this;
@@ -627,7 +627,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartList(StringPiece name) {
// Since we cannot have a top-level repeated item in protobuf, the only way
// this is valid is if we start a special type google.protobuf.ListValue or
// google.protobuf.Value.
- if (current_ == NULL) {
+ if (current_ == nullptr) {
if (!name.empty()) {
InvalidName(name, "Root element should not be named.");
IncrementInvalidDepth();
@@ -706,7 +706,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartList(StringPiece name) {
if (invalid_depth() > 0) return this;
// case i and ii above. Start "list_value" field within g.p.Value
- if (element() != NULL && element()->parent_field() != NULL) {
+ if (element() != nullptr && element()->parent_field() != nullptr) {
// Render
// "list_value": {
// "values": [ // Start this list
@@ -734,7 +734,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartList(StringPiece name) {
// When name is empty and stack is not empty, we are rendering an item within
// a list.
if (name.empty()) {
- if (element() != NULL && element()->parent_field() != NULL) {
+ if (element() != nullptr && element()->parent_field() != nullptr) {
if (IsStructValue(*element()->parent_field())) {
// Since it is g.p.Value, we bind directly to the list_value.
// Render
@@ -765,7 +765,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartList(StringPiece name) {
// name is not empty
const google::protobuf::Field* field = Lookup(name);
- if (field == NULL) {
+ if (field == nullptr) {
IncrementInvalidDepth();
return this;
}
@@ -837,7 +837,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::EndList() {
return this;
}
- if (current_ == NULL) return this;
+ if (current_ == nullptr) return this;
if (current_->IsAny()) {
current_->any()->EndList();
@@ -961,7 +961,7 @@ Status ProtoStreamObjectWriter::RenderFieldMask(ProtoStreamObjectWriter* ow,
// TODO(tsun): figure out how to do proto descriptor based snake case
// conversions as much as possible. Because ToSnakeCase sometimes returns the
// wrong value.
- google::protobuf::scoped_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());
}
@@ -977,13 +977,13 @@ Status ProtoStreamObjectWriter::RenderDuration(ProtoStreamObjectWriter* ow,
StringPiece value(data.str());
- if (!value.ends_with("s")) {
+ if (!StringEndsWith(value, "s")) {
return Status(INVALID_ARGUMENT,
"Illegal duration format; duration must end with 's'");
}
value = value.substr(0, value.size() - 1);
int sign = 1;
- if (value.starts_with("-")) {
+ if (StringStartsWith(value, "-")) {
sign = -1;
value = value.substr(1);
}
@@ -1028,10 +1028,10 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece(
Status status;
if (invalid_depth() > 0) return this;
- if (current_ == NULL) {
+ if (current_ == nullptr) {
const TypeRenderer* type_renderer =
FindTypeRenderer(GetFullTypeWithUrl(master_type_.name()));
- if (type_renderer == NULL) {
+ if (type_renderer == nullptr) {
InvalidName(name, "Root element must be a message.");
return this;
}
@@ -1054,7 +1054,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece(
return this;
}
- const google::protobuf::Field* field = NULL;
+ const google::protobuf::Field* field = nullptr;
if (current_->IsMap()) {
if (!ValidMapKey(name)) return this;
@@ -1064,14 +1064,14 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece(
ProtoWriter::RenderDataPiece("key",
DataPiece(name, use_strict_base64_decoding()));
field = Lookup("value");
- if (field == NULL) {
+ if (field == nullptr) {
Pop();
GOOGLE_LOG(DFATAL) << "Map does not have a value field.";
return this;
}
const TypeRenderer* type_renderer = FindTypeRenderer(field->type_url());
- if (type_renderer != NULL) {
+ if (type_renderer != nullptr) {
// Map's value type is a special type. Render it like a message:
// "value": {
// ... Render special type ...
@@ -1101,11 +1101,11 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece(
}
field = Lookup(name);
- if (field == NULL) return this;
+ if (field == nullptr) return this;
// Check if the field is of special type. Render it accordingly if so.
const TypeRenderer* type_renderer = FindTypeRenderer(field->type_url());
- if (type_renderer != NULL) {
+ if (type_renderer != nullptr) {
// Pass through null value only for google.protobuf.Value. For other
// types we ignore null value just like for regular field types.
if (data.type() != DataPiece::TYPE_NULL ||
@@ -1199,7 +1199,7 @@ ProtoStreamObjectWriter::FindTypeRenderer(const string& type_url) {
}
bool ProtoStreamObjectWriter::ValidMapKey(StringPiece unnormalized_name) {
- if (current_ == NULL) return true;
+ if (current_ == nullptr) return true;
if (!current_->InsertMapKeyIfNotPresent(unnormalized_name)) {
listener()->InvalidName(
@@ -1224,10 +1224,10 @@ void ProtoStreamObjectWriter::Push(StringPiece name, Item::ItemType item_type,
void ProtoStreamObjectWriter::Pop() {
// Pop all placeholder items sending StartObject or StartList events to
// ProtoWriter according to is_list value.
- while (current_ != NULL && current_->is_placeholder()) {
+ while (current_ != nullptr && current_->is_placeholder()) {
PopOneElement();
}
- if (current_ != NULL) {
+ if (current_ != nullptr) {
PopOneElement();
}
}
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter.h b/src/google/protobuf/util/internal/protostream_objectwriter.h
index ab534912..d9bb432e 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter.h
+++ b/src/google/protobuf/util/internal/protostream_objectwriter.h
@@ -112,18 +112,18 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
strings::ByteSink* output, ErrorListener* listener,
const ProtoStreamObjectWriter::Options& options =
ProtoStreamObjectWriter::Options::Defaults());
- virtual ~ProtoStreamObjectWriter();
+ virtual ~ProtoStreamObjectWriter() override;
// ObjectWriter methods.
- virtual ProtoStreamObjectWriter* StartObject(StringPiece name);
- virtual ProtoStreamObjectWriter* EndObject();
- virtual ProtoStreamObjectWriter* StartList(StringPiece name);
- virtual ProtoStreamObjectWriter* EndList();
+ virtual ProtoStreamObjectWriter* StartObject(StringPiece name) override;
+ virtual ProtoStreamObjectWriter* EndObject() override;
+ virtual ProtoStreamObjectWriter* StartList(StringPiece name) override;
+ virtual 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);
+ const DataPiece& value) override;
protected:
// Function that renders a well known type with modified behavior.
@@ -216,7 +216,7 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
ProtoStreamObjectWriter* parent_;
// The nested object writer, used to write events.
- google::protobuf::scoped_ptr<ProtoStreamObjectWriter> ow_;
+ std::unique_ptr<ProtoStreamObjectWriter> ow_;
// The type_url_ that this Any represents.
string type_url_;
@@ -263,7 +263,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() {}
+ virtual ~Item() override {}
// These functions return true if the element type is corresponding to the
// type in function name.
@@ -272,7 +272,7 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
AnyWriter* any() const { return any_.get(); }
- virtual Item* parent() const {
+ virtual Item* parent() const override {
return static_cast<Item*>(BaseElement::parent());
}
@@ -292,14 +292,14 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
ProtoStreamObjectWriter* ow_;
// A writer for Any objects, handles all Any-related nonsense.
- google::protobuf::scoped_ptr<AnyWriter> any_;
+ std::unique_ptr<AnyWriter> any_;
// The type of this element, see enum for permissible types.
ItemType item_type_;
// Set of map keys already seen for the type_. Used to validate incoming
// messages so no map key appears more than once.
- google::protobuf::scoped_ptr<hash_set<string> > map_keys_;
+ std::unique_ptr<hash_set<string> > map_keys_;
// Conveys whether this Item is a placeholder or not. Placeholder items are
// pushed to stack to account for special types.
@@ -392,7 +392,7 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
const google::protobuf::Type& master_type_;
// The current element, variable for internal state processing.
- google::protobuf::scoped_ptr<Item> current_;
+ std::unique_ptr<Item> current_;
// Reference to the options that control this class's behavior.
const ProtoStreamObjectWriter::Options options_;
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter_test.cc b/src/google/protobuf/util/internal/protostream_objectwriter_test.cc
index 87d35b08..9c50e7dd 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter_test.cc
+++ b/src/google/protobuf/util/internal/protostream_objectwriter_test.cc
@@ -146,7 +146,7 @@ class BaseProtoStreamObjectWriterTest
void CheckOutput(const Message& expected, int expected_length) {
size_t nbytes;
- google::protobuf::scoped_array<char> buffer(output_->GetBuffer(&nbytes));
+ std::unique_ptr<char[]> buffer(output_->GetBuffer(&nbytes));
if (expected_length >= 0) {
EXPECT_EQ(expected_length, nbytes);
}
@@ -154,7 +154,7 @@ class BaseProtoStreamObjectWriterTest
std::stringbuf str_buf(str, std::ios_base::in);
std::istream istream(&str_buf);
- google::protobuf::scoped_ptr<Message> message(expected.New());
+ std::unique_ptr<Message> message(expected.New());
message->ParsePartialFromIstream(&istream);
if (!MessageDifferencer::Equivalent(expected, *message)) {
@@ -170,8 +170,8 @@ class BaseProtoStreamObjectWriterTest
testing::TypeInfoTestHelper helper_;
MockErrorListener listener_;
- google::protobuf::scoped_ptr<GrowingArrayByteSink> output_;
- google::protobuf::scoped_ptr<ProtoStreamObjectWriter> ow_;
+ std::unique_ptr<GrowingArrayByteSink> output_;
+ std::unique_ptr<ProtoStreamObjectWriter> ow_;
ProtoStreamObjectWriter::Options options_;
};
@@ -1679,6 +1679,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() {
diff --git a/src/google/protobuf/util/internal/structured_objectwriter.h b/src/google/protobuf/util/internal/structured_objectwriter.h
index 3f065d6b..8e63222b 100644
--- a/src/google/protobuf/util/internal/structured_objectwriter.h
+++ b/src/google/protobuf/util/internal/structured_objectwriter.h
@@ -32,9 +32,6 @@
#define GOOGLE_PROTOBUF_UTIL_CONVERTER_STRUCTURED_OBJECTWRITER_H__
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/common.h>
@@ -80,7 +77,7 @@ class LIBPROTOBUF_EXPORT StructuredObjectWriter : public ObjectWriter {
}
// Returns true if this element is the root.
- bool is_root() const { return parent_ == NULL; }
+ bool is_root() const { return parent_ == nullptr; }
// Returns the number of hops from this element to the root element.
int level() const { return level_; }
@@ -91,10 +88,10 @@ class LIBPROTOBUF_EXPORT StructuredObjectWriter : public ObjectWriter {
private:
// Pointer to the parent Element.
- google::protobuf::scoped_ptr<BaseElement> parent_;
+ std::unique_ptr<BaseElement> parent_;
// Number of hops to the root Element.
- // The root Element has NULL parent_ and a level_ of 0.
+ // The root Element has nullptr parent_ and a level_ of 0.
const int level_;
GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(BaseElement);
diff --git a/src/google/protobuf/util/internal/testdata/books.proto b/src/google/protobuf/util/internal/testdata/books.proto
index 869271f4..5e08a291 100644
--- a/src/google/protobuf/util/internal/testdata/books.proto
+++ b/src/google/protobuf/util/internal/testdata/books.proto
@@ -65,9 +65,13 @@ message Book {
KIDS = 2;
ACTION_AND_ADVENTURE = 3;
arts_and_photography = 4;
+ I18N_Tech = 5;
}
optional Type type = 11;
+ // Useful for testing JSON snake/camel-case conversions.
+ optional string snake_field = 12;
+
extensions 200 to 499;
}
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 85d0d5c9..e32e71d0 100644
--- a/src/google/protobuf/util/internal/type_info.cc
+++ b/src/google/protobuf/util/internal/type_info.cc
@@ -59,7 +59,7 @@ class TypeInfoForTypeResolver : public TypeInfo {
}
virtual util::StatusOr<const google::protobuf::Type*> ResolveTypeUrl(
- StringPiece type_url) const {
+ StringPiece type_url) const override {
std::map<StringPiece, StatusOrType>::iterator it =
cached_types_.find(type_url);
if (it != cached_types_.end()) {
@@ -69,7 +69,7 @@ class TypeInfoForTypeResolver : public TypeInfo {
// cached_types_ map.
const string& string_type_url =
*string_storage_.insert(type_url.ToString()).first;
- google::protobuf::scoped_ptr<google::protobuf::Type> type(new google::protobuf::Type());
+ std::unique_ptr<google::protobuf::Type> type(new google::protobuf::Type());
util::Status status =
type_resolver_->ResolveMessageType(string_type_url, type.get());
StatusOrType result =
@@ -79,13 +79,13 @@ class TypeInfoForTypeResolver : public TypeInfo {
}
virtual const google::protobuf::Type* GetTypeByTypeUrl(
- StringPiece type_url) const {
+ 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 {
+ StringPiece type_url) const override {
std::map<StringPiece, StatusOrEnum>::iterator it =
cached_enums_.find(type_url);
if (it != cached_enums_.end()) {
@@ -95,7 +95,7 @@ class TypeInfoForTypeResolver : public TypeInfo {
// cached_enums_ map.
const string& string_type_url =
*string_storage_.insert(type_url.ToString()).first;
- google::protobuf::scoped_ptr<google::protobuf::Enum> enum_type(
+ std::unique_ptr<google::protobuf::Enum> enum_type(
new google::protobuf::Enum());
util::Status status =
type_resolver_->ResolveEnumType(string_type_url, enum_type.get());
@@ -105,8 +105,10 @@ 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::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 =
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 737ba9e4..281a7f58 100644
--- a/src/google/protobuf/util/internal/type_info_test_helper.cc
+++ b/src/google/protobuf/util/internal/type_info_test_helper.cc
@@ -31,9 +31,6 @@
#include <google/protobuf/util/internal/type_info_test_helper.h>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
#include <google/protobuf/stubs/logging.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 1a196715..5a077e04 100644
--- a/src/google/protobuf/util/internal/type_info_test_helper.h
+++ b/src/google/protobuf/util/internal/type_info_test_helper.h
@@ -32,9 +32,6 @@
#define GOOGLE_PROTOBUF_UTIL_CONVERTER_TYPE_INFO_TEST_HELPER_H__
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <vector>
#include <google/protobuf/io/coded_stream.h>
@@ -86,8 +83,8 @@ class TypeInfoTestHelper {
private:
TypeInfoSource type_;
- google::protobuf::scoped_ptr<TypeInfo> typeinfo_;
- google::protobuf::scoped_ptr<TypeResolver> type_resolver_;
+ std::unique_ptr<TypeInfo> typeinfo_;
+ std::unique_ptr<TypeResolver> type_resolver_;
};
} // namespace testing
} // namespace converter
diff --git a/src/google/protobuf/util/internal/utility.cc b/src/google/protobuf/util/internal/utility.cc
index b1007765..b8d917ce 100644
--- a/src/google/protobuf/util/internal/utility.cc
+++ b/src/google/protobuf/util/internal/utility.cc
@@ -52,7 +52,7 @@ bool GetBoolOptionOrDefault(
const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
const string& option_name, bool default_value) {
const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
- if (opt == NULL) {
+ if (opt == nullptr) {
return default_value;
}
return GetBoolFromAny(opt->value());
@@ -62,7 +62,7 @@ int64 GetInt64OptionOrDefault(
const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
const string& option_name, int64 default_value) {
const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
- if (opt == NULL) {
+ if (opt == nullptr) {
return default_value;
}
return GetInt64FromAny(opt->value());
@@ -72,7 +72,7 @@ double GetDoubleOptionOrDefault(
const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
const string& option_name, double default_value) {
const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
- if (opt == NULL) {
+ if (opt == nullptr) {
return default_value;
}
return GetDoubleFromAny(opt->value());
@@ -82,7 +82,7 @@ string GetStringOptionOrDefault(
const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
const string& option_name, const string& default_value) {
const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
- if (opt == NULL) {
+ if (opt == nullptr) {
return default_value;
}
return GetStringFromAny(opt->value());
@@ -144,12 +144,12 @@ const google::protobuf::Option* FindOptionOrNull(
return &opt;
}
}
- return NULL;
+ return nullptr;
}
const google::protobuf::Field* FindFieldInTypeOrNull(
const google::protobuf::Type* type, StringPiece field_name) {
- if (type != NULL) {
+ if (type != nullptr) {
for (int i = 0; i < type->fields_size(); ++i) {
const google::protobuf::Field& field = type->fields(i);
if (field.name() == field_name) {
@@ -157,12 +157,12 @@ const google::protobuf::Field* FindFieldInTypeOrNull(
}
}
}
- return NULL;
+ return nullptr;
}
const google::protobuf::Field* FindJsonFieldInTypeOrNull(
const google::protobuf::Type* type, StringPiece json_name) {
- if (type != NULL) {
+ if (type != nullptr) {
for (int i = 0; i < type->fields_size(); ++i) {
const google::protobuf::Field& field = type->fields(i);
if (field.json_name() == json_name) {
@@ -170,12 +170,12 @@ const google::protobuf::Field* FindJsonFieldInTypeOrNull(
}
}
}
- return NULL;
+ return nullptr;
}
const google::protobuf::Field* FindFieldInTypeByNumberOrNull(
const google::protobuf::Type* type, int32 number) {
- if (type != NULL) {
+ if (type != nullptr) {
for (int i = 0; i < type->fields_size(); ++i) {
const google::protobuf::Field& field = type->fields(i);
if (field.number() == number) {
@@ -183,12 +183,12 @@ const google::protobuf::Field* FindFieldInTypeByNumberOrNull(
}
}
}
- return NULL;
+ return nullptr;
}
const google::protobuf::EnumValue* FindEnumValueByNameOrNull(
const google::protobuf::Enum* enum_type, StringPiece enum_name) {
- if (enum_type != NULL) {
+ if (enum_type != nullptr) {
for (int i = 0; i < enum_type->enumvalue_size(); ++i) {
const google::protobuf::EnumValue& enum_value = enum_type->enumvalue(i);
if (enum_value.name() == enum_name) {
@@ -196,12 +196,12 @@ const google::protobuf::EnumValue* FindEnumValueByNameOrNull(
}
}
}
- return NULL;
+ return nullptr;
}
const google::protobuf::EnumValue* FindEnumValueByNumberOrNull(
const google::protobuf::Enum* enum_type, int32 value) {
- if (enum_type != NULL) {
+ if (enum_type != nullptr) {
for (int i = 0; i < enum_type->enumvalue_size(); ++i) {
const google::protobuf::EnumValue& enum_value = enum_type->enumvalue(i);
if (enum_value.number() == value) {
@@ -209,12 +209,12 @@ const google::protobuf::EnumValue* FindEnumValueByNumberOrNull(
}
}
}
- return NULL;
+ return nullptr;
}
const google::protobuf::EnumValue* FindEnumValueByNameWithoutUnderscoreOrNull(
const google::protobuf::Enum* enum_type, StringPiece enum_name) {
- if (enum_type != NULL) {
+ if (enum_type != nullptr) {
for (int i = 0; i < enum_type->enumvalue_size(); ++i) {
const google::protobuf::EnumValue& enum_value = enum_type->enumvalue(i);
string enum_name_without_underscore = enum_value.name();
@@ -235,7 +235,14 @@ const google::protobuf::EnumValue* FindEnumValueByNameWithoutUnderscoreOrNull(
}
}
}
- return NULL;
+ return nullptr;
+}
+
+string EnumValueNameToLowerCamelCase(const StringPiece input) {
+ string input_string(input);
+ std::transform(input_string.begin(), input_string.end(), input_string.begin(),
+ ::tolower);
+ return ToCamelCase(input_string);
}
string ToCamelCase(const StringPiece input) {
@@ -398,6 +405,13 @@ bool SafeStrToFloat(StringPiece str, float* value) {
return true;
}
+bool StringStartsWith(StringPiece text, StringPiece prefix) {
+ return text.starts_with(prefix);
+}
+
+bool StringEndsWith(StringPiece text, StringPiece suffix) {
+ return text.ends_with(suffix);
+}
} // namespace converter
} // namespace util
} // namespace protobuf
diff --git a/src/google/protobuf/util/internal/utility.h b/src/google/protobuf/util/internal/utility.h
index 667e660c..d8e06a97 100644
--- a/src/google/protobuf/util/internal/utility.h
+++ b/src/google/protobuf/util/internal/utility.h
@@ -32,9 +32,6 @@
#define GOOGLE_PROTOBUF_UTIL_CONVERTER_UTILITY_H__
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
#include <utility>
@@ -121,13 +118,13 @@ LIBPROTOBUF_EXPORT const StringPiece GetTypeWithoutUrl(StringPiece type_url);
LIBPROTOBUF_EXPORT const string GetFullTypeWithUrl(StringPiece simple_type);
// Finds and returns option identified by name and option_name within the
-// provided map. Returns NULL if none found.
+// provided map. Returns nullptr if none found.
const google::protobuf::Option* FindOptionOrNull(
const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
const string& option_name);
// Finds and returns the field identified by field_name in the passed tech Type
-// object. Returns NULL if none found.
+// object. Returns nullptr if none found.
const google::protobuf::Field* FindFieldInTypeOrNull(
const google::protobuf::Type* type, StringPiece field_name);
@@ -141,17 +138,17 @@ const google::protobuf::Field* FindFieldInTypeByNumberOrNull(
const google::protobuf::Type* type, int32 number);
// Finds and returns the EnumValue identified by enum_name in the passed tech
-// Enum object. Returns NULL if none found.
+// Enum object. Returns nullptr if none found.
const google::protobuf::EnumValue* FindEnumValueByNameOrNull(
const google::protobuf::Enum* enum_type, StringPiece enum_name);
// Finds and returns the EnumValue identified by value in the passed tech
-// Enum object. Returns NULL if none found.
+// Enum object. Returns nullptr if none found.
const google::protobuf::EnumValue* FindEnumValueByNumberOrNull(
const google::protobuf::Enum* enum_type, int32 value);
// Finds and returns the EnumValue identified by enum_name without underscore in
-// the passed tech Enum object. Returns NULL if none found.
+// the passed tech Enum object. Returns nullptr if none found.
// For Ex. if enum_name is ACTIONANDADVENTURE it can get accepted if
// EnumValue's name is action_and_adventure or ACTION_AND_ADVENTURE.
const google::protobuf::EnumValue* FindEnumValueByNameWithoutUnderscoreOrNull(
@@ -160,6 +157,9 @@ const google::protobuf::EnumValue* FindEnumValueByNameWithoutUnderscoreOrNull(
// Converts input to camel-case and returns it.
LIBPROTOBUF_EXPORT string ToCamelCase(const StringPiece input);
+// Converts enum name string to camel-case and returns it.
+string EnumValueNameToLowerCamelCase(const StringPiece input);
+
// Converts input to snake_case and returns it.
LIBPROTOBUF_EXPORT string ToSnakeCase(StringPiece input);
@@ -200,6 +200,12 @@ inline string ValueAsString(double 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);
+
+// Returns whether a StringPiece begins with the provided prefix.
+bool StringStartsWith(StringPiece text, StringPiece prefix);
+
+// Returns whether a StringPiece ends with the provided suffix.
+bool StringEndsWith(StringPiece text, StringPiece suffix);
} // namespace converter
} // namespace util
} // namespace protobuf
diff --git a/src/google/protobuf/util/json_format_proto3.proto b/src/google/protobuf/util/json_format_proto3.proto
index 8a0441c8..cbc3f81f 100644
--- a/src/google/protobuf/util/json_format_proto3.proto
+++ b/src/google/protobuf/util/json_format_proto3.proto
@@ -181,3 +181,9 @@ message TestCustomJsonName {
message TestExtensions {
.protobuf_unittest.TestAllExtensions extensions = 1;
}
+
+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 25e78a65..7a7f299f 100644
--- a/src/google/protobuf/util/json_util.cc
+++ b/src/google/protobuf/util/json_util.cc
@@ -97,6 +97,8 @@ util::Status BinaryToJsonStream(TypeResolver* resolver,
resolver, type, &json_writer);
default_value_writer.set_preserve_proto_field_names(
options.preserve_proto_field_names);
+ default_value_writer.set_print_enums_as_ints(
+ options.always_print_enums_as_ints);
return proto_source.WriteTo(&default_value_writer);
} else {
return proto_source.WriteTo(&json_writer);
@@ -117,30 +119,32 @@ util::Status BinaryToJsonString(TypeResolver* resolver,
namespace {
class StatusErrorListener : public converter::ErrorListener {
public:
+
StatusErrorListener() {}
- virtual ~StatusErrorListener() {}
+ virtual ~StatusErrorListener() override {}
util::Status GetStatus() { return status_; }
virtual void InvalidName(const converter::LocationTrackerInterface& loc,
- StringPiece unknown_name, StringPiece message) {
+ StringPiece unknown_name, StringPiece message) override {
status_ = util::Status(util::error::INVALID_ARGUMENT,
- loc.ToString() + ": " + message.ToString());
+ loc.ToString() + ": invalid name " +
+ string(unknown_name) + ": " + string(message));
}
virtual void InvalidValue(const converter::LocationTrackerInterface& loc,
- StringPiece type_name, StringPiece value) {
+ StringPiece type_name, StringPiece value) override {
status_ =
util::Status(util::error::INVALID_ARGUMENT,
- loc.ToString() + ": invalid value " + value.ToString() +
- " for type " + type_name.ToString());
+ loc.ToString() + ": invalid value " + string(value) +
+ " for type " + string(type_name));
}
virtual void MissingField(const converter::LocationTrackerInterface& loc,
- StringPiece missing_name) {
+ StringPiece missing_name) override {
status_ = util::Status(
util::error::INVALID_ARGUMENT,
- loc.ToString() + ": missing field " + missing_name.ToString());
+ loc.ToString() + ": missing field " + string(missing_name));
}
private:
diff --git a/src/google/protobuf/util/json_util.h b/src/google/protobuf/util/json_util.h
index b1c69813..e7868307 100644
--- a/src/google/protobuf/util/json_util.h
+++ b/src/google/protobuf/util/json_util.h
@@ -182,7 +182,7 @@ class LIBPROTOBUF_EXPORT ZeroCopyStreamByteSink : public strings::ByteSink {
: stream_(stream), buffer_(NULL), buffer_size_(0) {}
~ZeroCopyStreamByteSink();
- virtual void Append(const char* bytes, size_t len);
+ virtual void Append(const char* bytes, size_t len) override;
private:
io::ZeroCopyOutputStream* stream_;
diff --git a/src/google/protobuf/util/json_util_test.cc b/src/google/protobuf/util/json_util_test.cc
index 5b714bb1..a2a84b57 100644
--- a/src/google/protobuf/util/json_util_test.cc
+++ b/src/google/protobuf/util/json_util_test.cc
@@ -34,13 +34,13 @@
#include <string>
#include <google/protobuf/io/zero_copy_stream.h>
+#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/descriptor_database.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/util/internal/testdata/maps.pb.h>
#include <google/protobuf/util/json_format_proto3.pb.h>
#include <google/protobuf/util/type_resolver.h>
#include <google/protobuf/util/type_resolver_util.h>
-#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <gtest/gtest.h>
namespace google {
@@ -48,12 +48,13 @@ namespace protobuf {
namespace util {
namespace {
+using google::protobuf::testing::MapIn;
using proto3::FOO;
using proto3::BAR;
using proto3::TestMessage;
using proto3::TestMap;
using proto3::TestOneof;
-using google::protobuf::testing::MapIn;
+using proto3::TestEnumValue;
static const char kTypeUrlPrefix[] = "type.googleapis.com";
@@ -82,7 +83,7 @@ class JsonUtilTest : public ::testing::Test {
return FromJson(json, message, JsonParseOptions());
}
- google::protobuf::scoped_ptr<TypeResolver> resolver_;
+ std::unique_ptr<TypeResolver> resolver_;
};
TEST_F(JsonUtilTest, TestWhitespaces) {
@@ -217,6 +218,29 @@ TEST_F(JsonUtilTest, TestAlwaysPrintEnumsAsInts) {
EXPECT_EQ(proto3::BAR, parsed.repeated_enum_value(1));
}
+TEST_F(JsonUtilTest, TestPrintEnumsAsIntsWithDefaultValue) {
+ TestEnumValue orig;
+ //orig.set_enum_value1(proto3::FOO)
+ orig.set_enum_value2(proto3::FOO);
+ orig.set_enum_value3(proto3::BAR);
+
+ JsonPrintOptions print_options;
+ print_options.always_print_enums_as_ints = true;
+ print_options.always_print_primitive_fields = true;
+
+ string expected_json = "{\"enumValue1\":0,\"enumValue2\":0,\"enumValue3\":1}";
+ EXPECT_EQ(expected_json, ToJson(orig, print_options));
+
+ TestEnumValue parsed;
+ JsonParseOptions parse_options;
+ ASSERT_TRUE(FromJson(expected_json, &parsed, parse_options));
+
+ 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) {
// Some random message but good enough to verify that the parsing warpper
// functions are working properly.
@@ -260,7 +284,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));
@@ -313,7 +337,7 @@ TEST_F(JsonUtilTest, TestDynamicMessage) {
DescriptorPool pool(&database);
// A dynamic version of the test proto.
DynamicMessageFactory factory;
- google::protobuf::scoped_ptr<Message> message(factory.GetPrototype(
+ std::unique_ptr<Message> message(factory.GetPrototype(
pool.FindMessageTypeByName("proto3.TestMessage"))->New());
EXPECT_TRUE(FromJson(input, message.get()));
@@ -333,6 +357,64 @@ TEST_F(JsonUtilTest, TestDynamicMessage) {
EXPECT_EQ(ToJson(generated, options), ToJson(*message, options));
}
+TEST_F(JsonUtilTest, TestParsingUnknownEnumsAs0) {
+ TestMessage m;
+ {
+ JsonParseOptions options;
+ ASSERT_FALSE(options.ignore_unknown_fields);
+ string input =
+ "{\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
+
+ 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
+ }
+ // Integer values are read as usual
+ {
+ JsonParseOptions options;
+ string input =
+ "{\n"
+ " \"enum_value\":12345\n"
+ "}";
+ m.set_enum_value(proto3::BAR);
+ EXPECT_TRUE(FromJson(input, &m, options));
+ ASSERT_EQ(12345, m.enum_value());
+
+ options.ignore_unknown_fields = true;
+ EXPECT_TRUE(FromJson(input, &m, options));
+ EXPECT_EQ(12345, m.enum_value());
+ }
+
+ // Trying to pass an object as an enum field value is always treated as an error
+ {
+ JsonParseOptions options;
+ string input =
+ "{\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
+ {
+ JsonParseOptions options;
+ string input =
+ "{\n"
+ " \"enum_value\":[]\n"
+ "}";
+ EXPECT_FALSE(FromJson(input, &m, options));
+ options.ignore_unknown_fields = true;
+ EXPECT_FALSE(FromJson(input, &m, options));
+ }
+}
+
typedef std::pair<char*, int> Segment;
// A ZeroCopyOutputStream that writes to multiple buffers.
class SegmentedZeroCopyOutputStream : public io::ZeroCopyOutputStream {
@@ -459,26 +541,22 @@ TEST(ZeroCopyStreamByteSinkTest, TestAllInputOutputPatterns) {
}
TEST_F(JsonUtilTest, TestWrongJsonInput) {
- using namespace google::protobuf;
const char json[] = "{\"unknown_field\":\"some_value\"}";
io::ArrayInputStream input_stream(json, strlen(json));
char proto_buffer[10000];
io::ArrayOutputStream output_stream(proto_buffer, sizeof(proto_buffer));
- std::string message_type = "type.googleapis.com/proto3.TestMessage";
+ std::string message_type = "type.googleapis.com/proto3.TestMessage";
TypeResolver* resolver = NewTypeResolverForDescriptorPool(
- "type.googleapis.com",
- DescriptorPool::generated_pool());
-
- util::Status result_status = util::JsonToBinaryStream(resolver,
- message_type,
- &input_stream,
- &output_stream);
-
+ "type.googleapis.com", DescriptorPool::generated_pool());
+
+ auto result_status = util::JsonToBinaryStream(
+ resolver, message_type, &input_stream, &output_stream);
+
delete resolver;
EXPECT_FALSE(result_status.ok());
- EXPECT_EQ(result_status.error_code(),
- google::protobuf::util::error::INVALID_ARGUMENT);
+ EXPECT_EQ(result_status.error_code(),
+ util::error::INVALID_ARGUMENT);
}
} // namespace
diff --git a/src/google/protobuf/util/message_differencer.cc b/src/google/protobuf/util/message_differencer.cc
index c32e941c..7d3976f8 100644
--- a/src/google/protobuf/util/message_differencer.cc
+++ b/src/google/protobuf/util/message_differencer.cc
@@ -40,9 +40,6 @@
#include <algorithm>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <utility>
#include <google/protobuf/stubs/callback.h>
@@ -93,7 +90,7 @@ class MessageDifferencer::MultipleFieldsMapKeyComparator
virtual bool IsMatch(
const Message& message1,
const Message& message2,
- const std::vector<SpecificField>& parent_fields) const {
+ 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)) {
@@ -490,8 +487,8 @@ bool MessageDifferencer::Compare(
}
// Expand google.protobuf.Any payload if possible.
if (descriptor1->full_name() == internal::kAnyFullTypeName) {
- google::protobuf::scoped_ptr<Message> data1;
- google::protobuf::scoped_ptr<Message> data2;
+ std::unique_ptr<Message> data1;
+ std::unique_ptr<Message> data2;
if (UnpackAny(message1, &data1) && UnpackAny(message2, &data2)) {
// Avoid DFATAL for different descriptors in google.protobuf.Any payloads.
if (data1->GetDescriptor() != data2->GetDescriptor()) {
@@ -1068,7 +1065,7 @@ struct UnknownFieldOrdering {
} // namespace
bool MessageDifferencer::UnpackAny(const Message& any,
- google::protobuf::scoped_ptr<Message>* data) {
+ std::unique_ptr<Message>* data) {
const Reflection* reflection = any.GetReflection();
const FieldDescriptor* type_url_field;
const FieldDescriptor* value_field;
@@ -1341,7 +1338,7 @@ class MaximumMatcher {
int count1_;
int count2_;
- google::protobuf::scoped_ptr<NodeMatchCallback> match_callback_;
+ std::unique_ptr<NodeMatchCallback> match_callback_;
std::map<std::pair<int, int>, bool> cached_match_results_;
std::vector<int>* match_list1_;
std::vector<int>* match_list2_;
@@ -1459,11 +1456,27 @@ bool MessageDifferencer::MatchRepeatedFieldIndices(
if (match_count != count1 && reporter_ == NULL) return false;
success = success && (match_count == count1);
} else {
- for (int i = 0; i < count1; ++i) {
+ int start_offset = 0;
+ // If the two repeated fields are treated as sets, optimize for the case
+ // where both start with same items stored in the same order.
+ if (IsTreatedAsSet(repeated_field)) {
+ start_offset = std::min(count1, count2);
+ for (int i = 0; i < count1 && i < count2; i++) {
+ if (IsMatch(repeated_field, key_comparator, &message1, &message2,
+ parent_fields, i, i)) {
+ match_list1->at(i) = i;
+ match_list2->at(i) = i;
+ } else {
+ start_offset = i;
+ break;
+ }
+ }
+ }
+ for (int i = start_offset; i < count1; ++i) {
// Indicates any matched elements for this repeated field.
bool match = false;
- for (int j = 0; j < count2; j++) {
+ for (int j = start_offset; j < count2; j++) {
if (match_list2->at(j) != -1) continue;
match = IsMatch(repeated_field, key_comparator,
diff --git a/src/google/protobuf/util/message_differencer.h b/src/google/protobuf/util/message_differencer.h
index 11d6cc03..b3e65515 100644
--- a/src/google/protobuf/util/message_differencer.h
+++ b/src/google/protobuf/util/message_differencer.h
@@ -175,10 +175,8 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// If "field" is a repeated field which is being treated as a map or
// a set (see TreatAsMap() and TreatAsSet(), below), new_index indicates
- // the index the position to which the element has moved. This only
- // applies to ReportMoved() and (in the case of TreatAsMap())
- // ReportModified(). In all other cases, "new_index" will have the same
- // value as "index".
+ // the index the position to which the element has moved. If the element
+ // has not moved, "new_index" will have the same value as "index".
int new_index;
// For unknown fields, these are the pointers to the UnknownFieldSet
@@ -599,7 +597,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
public:
explicit StreamReporter(io::ZeroCopyOutputStream* output);
explicit StreamReporter(io::Printer* printer); // delimiter '$'
- virtual ~StreamReporter();
+ virtual ~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
@@ -609,32 +607,33 @@ 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);
+ const std::vector<SpecificField>& field_path) override;
virtual void ReportDeleted(const Message& message1,
const Message& message2,
- const std::vector<SpecificField>& field_path);
+ const std::vector<SpecificField>& field_path) override;
virtual void ReportModified(const Message& message1,
const Message& message2,
- const std::vector<SpecificField>& field_path);
+ const std::vector<SpecificField>& field_path) override;
virtual void ReportMoved(const Message& message1,
const Message& message2,
- const std::vector<SpecificField>& field_path);
+ const std::vector<SpecificField>& field_path) override;
virtual void ReportMatched(const Message& message1,
const Message& message2,
- const std::vector<SpecificField>& field_path);
+ const std::vector<SpecificField>& field_path) override;
virtual void ReportIgnored(const Message& message1,
const Message& message2,
- const std::vector<SpecificField>& field_path);
+ const std::vector<SpecificField>& field_path) override;
- virtual void ReportUnknownFieldIgnored(
+ 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
@@ -683,7 +682,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
public:
explicit MapEntryKeyComparator(MessageDifferencer* message_differencer);
virtual bool IsMatch(const Message& message1, const Message& message2,
- const std::vector<SpecificField>& parent_fields) const;
+ const std::vector<SpecificField>& parent_fields) const override;
private:
MessageDifferencer* message_differencer_;
@@ -823,7 +822,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// If "any" is of type google.protobuf.Any, extract its payload using
// DynamicMessageFactory and store in "data".
- bool UnpackAny(const Message& any, google::protobuf::scoped_ptr<Message>* data);
+ bool UnpackAny(const Message& any, std::unique_ptr<Message>* data);
// Checks if index is equal to new_index in all the specific fields.
static bool CheckPathChanged(const std::vector<SpecificField>& parent_fields);
@@ -864,7 +863,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
string* output_string_;
- google::protobuf::scoped_ptr<DynamicMessageFactory> dynamic_message_factory_;
+ std::unique_ptr<DynamicMessageFactory> dynamic_message_factory_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageDifferencer);
};
diff --git a/src/google/protobuf/util/message_differencer_unittest.cc b/src/google/protobuf/util/message_differencer_unittest.cc
index 75cffd9f..a263d983 100755..100644
--- a/src/google/protobuf/util/message_differencer_unittest.cc
+++ b/src/google/protobuf/util/message_differencer_unittest.cc
@@ -127,6 +127,27 @@ TEST(MessageDifferencerTest, RepeatedFieldInequalityTest) {
EXPECT_FALSE(util::MessageDifferencer::Equals(msg1, msg2));
}
+TEST(MessageDifferencerTest, RepeatedFieldSetOptimizationTest) {
+ util::MessageDifferencer differencer;
+ protobuf_unittest::TestDiffMessage msg1;
+ protobuf_unittest::TestDiffMessage msg2;
+ protobuf_unittest::TestDiffMessage::Item* item1 = msg1.add_item();
+ protobuf_unittest::TestDiffMessage::Item* item2 = msg2.add_item();
+ differencer.TreatAsSet(item1->GetDescriptor()->FindFieldByName("ra"));
+ differencer.TreatAsSet(item2->GetDescriptor()->FindFieldByName("ra"));
+ for (int i = 0; i < 1000; i++) {
+ item1->add_ra(i);
+ item2->add_ra(i);
+ }
+ EXPECT_TRUE(differencer.Compare(msg1, msg2));
+ item2->add_ra(1001);
+ EXPECT_FALSE(differencer.Compare(msg1, msg2));
+ item1->add_ra(1001);
+ EXPECT_TRUE(differencer.Compare(msg1, msg2));
+ item1->add_ra(1002);
+ EXPECT_FALSE(differencer.Compare(msg1, msg2));
+}
+
TEST(MessageDifferencerTest, MapFieldEqualityTest) {
// Create the testing protos
unittest::TestMap msg1;
diff --git a/src/google/protobuf/util/package_info.h b/src/google/protobuf/util/package_info.h
index e37e6dc0..96019203 100644
--- a/src/google/protobuf/util/package_info.h
+++ b/src/google/protobuf/util/package_info.h
@@ -38,7 +38,7 @@ namespace protobuf {
// Utility classes.
//
-// This package contains various utilities for message comprasion, JSON
+// This package contains various utilities for message comparison, JSON
// conversion, well known types, etc.
namespace util {}
diff --git a/src/google/protobuf/util/time_util.cc b/src/google/protobuf/util/time_util.cc
index 46a6f5a8..d4912837 100644
--- a/src/google/protobuf/util/time_util.cc
+++ b/src/google/protobuf/util/time_util.cc
@@ -30,13 +30,14 @@
#include <google/protobuf/util/time_util.h>
-#include <google/protobuf/stubs/time.h>
#include <google/protobuf/stubs/int128.h>
-#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/stringprintf.h>
+#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/stubs/time.h>
#include <google/protobuf/duration.pb.h>
#include <google/protobuf/timestamp.pb.h>
+
namespace google {
namespace protobuf {
namespace util {
diff --git a/src/google/protobuf/util/type_resolver_util.cc b/src/google/protobuf/util/type_resolver_util.cc
index febaa41f..aa48ef60 100644
--- a/src/google/protobuf/util/type_resolver_util.cc
+++ b/src/google/protobuf/util/type_resolver_util.cc
@@ -60,7 +60,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 +75,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()) {
@@ -95,11 +95,6 @@ class DescriptorPoolTypeResolver : public TypeResolver {
type->Clear();
type->set_name(descriptor->full_name());
for (int i = 0; i < descriptor->field_count(); ++i) {
- const FieldDescriptor* field = descriptor->field(i);
- if (field->type() == FieldDescriptor::TYPE_GROUP) {
- // Group fields cannot be represented with Type. We discard them.
- continue;
- }
ConvertFieldDescriptor(descriptor->field(i), type->add_fields());
}
for (int i = 0; i < descriptor->oneof_decl_count(); ++i) {
@@ -141,7 +136,8 @@ class DescriptorPoolTypeResolver : public TypeResolver {
if (descriptor->has_default_value()) {
field->set_default_value(DefaultValueAsString(descriptor));
}
- if (descriptor->type() == FieldDescriptor::TYPE_MESSAGE) {
+ if (descriptor->type() == FieldDescriptor::TYPE_MESSAGE ||
+ descriptor->type() == FieldDescriptor::TYPE_GROUP) {
field->set_type_url(GetTypeUrl(descriptor->message_type()));
} else if (descriptor->type() == FieldDescriptor::TYPE_ENUM) {
field->set_type_url(GetTypeUrl(descriptor->enum_type()));
diff --git a/src/google/protobuf/util/type_resolver_util_test.cc b/src/google/protobuf/util/type_resolver_util_test.cc
index 8a0bf652..9dea17ae 100644
--- a/src/google/protobuf/util/type_resolver_util_test.cc
+++ b/src/google/protobuf/util/type_resolver_util_test.cc
@@ -32,9 +32,6 @@
#include <limits>
#include <memory>
-#ifndef _SHARED_PTR_H
-#include <google/protobuf/stubs/shared_ptr.h>
-#endif
#include <string>
#include <vector>
@@ -153,7 +150,7 @@ class DescriptorPoolTypeResolverTest : public testing::Test {
}
protected:
- google::protobuf::scoped_ptr<TypeResolver> resolver_;
+ std::unique_ptr<TypeResolver> resolver_;
};
TEST_F(DescriptorPoolTypeResolverTest, TestAllTypes) {
@@ -193,6 +190,13 @@ TEST_F(DescriptorPoolTypeResolverTest, TestAllTypes) {
Field::TYPE_BYTES, "optional_bytes", 15));
EXPECT_TRUE(HasField(type, Field::CARDINALITY_OPTIONAL,
+ Field::TYPE_GROUP, "optionalgroup", 16));
+
+ EXPECT_TRUE(CheckFieldTypeUrl(
+ type, "optionalgroup",
+ GetTypeUrl<protobuf_unittest::TestAllTypes::OptionalGroup>()));
+
+ EXPECT_TRUE(HasField(type, Field::CARDINALITY_OPTIONAL,
Field::TYPE_MESSAGE, "optional_nested_message", 18));
EXPECT_TRUE(HasField(type, Field::CARDINALITY_OPTIONAL,
Field::TYPE_MESSAGE, "optional_foreign_message", 19));
@@ -249,6 +253,13 @@ TEST_F(DescriptorPoolTypeResolverTest, TestAllTypes) {
Field::TYPE_BYTES, "repeated_bytes", 45));
EXPECT_TRUE(HasField(type, Field::CARDINALITY_REPEATED,
+ Field::TYPE_GROUP, "repeatedgroup", 46));
+
+ EXPECT_TRUE(CheckFieldTypeUrl(
+ type, "repeatedgroup",
+ GetTypeUrl<protobuf_unittest::TestAllTypes::RepeatedGroup>()));
+
+ EXPECT_TRUE(HasField(type, Field::CARDINALITY_REPEATED,
Field::TYPE_MESSAGE, "repeated_nested_message", 48));
EXPECT_TRUE(HasField(type, Field::CARDINALITY_REPEATED,
Field::TYPE_MESSAGE, "repeated_foreign_message", 49));
@@ -271,13 +282,6 @@ TEST_F(DescriptorPoolTypeResolverTest, TestAllTypes) {
EXPECT_TRUE(CheckFieldTypeUrl(
type, "repeated_foreign_enum",
GetTypeUrl("protobuf_unittest.ForeignEnum")));
-
- // Groups are discarded when converting to Type.
- const Descriptor* descriptor = protobuf_unittest::TestAllTypes::descriptor();
- EXPECT_TRUE(descriptor->FindFieldByName("optionalgroup") != NULL);
- EXPECT_TRUE(descriptor->FindFieldByName("repeatedgroup") != NULL);
- ASSERT_FALSE(HasField(type, "optionalgroup"));
- ASSERT_FALSE(HasField(type, "repeatedgroup"));
}
TEST_F(DescriptorPoolTypeResolverTest, TestPackedField) {
diff --git a/src/google/protobuf/wire_format.cc b/src/google/protobuf/wire_format.cc
index 01704c94..3fdf84ed 100644
--- a/src/google/protobuf/wire_format.cc
+++ b/src/google/protobuf/wire_format.cc
@@ -41,16 +41,15 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stringprintf.h>
-#include <google/protobuf/descriptor.h>
-#include <google/protobuf/dynamic_message.h>
-#include <google/protobuf/map_field.h>
-#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/dynamic_message.h>
+#include <google/protobuf/map_field.h>
#include <google/protobuf/unknown_field_set.h>
-
+#include <google/protobuf/wire_format_lite_inl.h>
namespace google {
diff --git a/src/google/protobuf/wire_format.h b/src/google/protobuf/wire_format.h
index d602d214..36f4a0bb 100644
--- a/src/google/protobuf/wire_format.h
+++ b/src/google/protobuf/wire_format.h
@@ -260,12 +260,12 @@ class LIBPROTOBUF_EXPORT UnknownFieldSetFieldSkipper : public FieldSkipper {
public:
UnknownFieldSetFieldSkipper(UnknownFieldSet* unknown_fields)
: unknown_fields_(unknown_fields) {}
- virtual ~UnknownFieldSetFieldSkipper() {}
+ virtual ~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);
+ virtual bool SkipField(io::CodedInputStream* input, uint32 tag) override;
+ virtual bool SkipMessage(io::CodedInputStream* input) override;
+ virtual void SkipUnknownEnum(int field_number, int value) override;
protected:
UnknownFieldSet* unknown_fields_;
diff --git a/src/google/protobuf/wire_format_lite.h b/src/google/protobuf/wire_format_lite.h
index 76275518..2244b35d 100644
--- a/src/google/protobuf/wire_format_lite.h
+++ b/src/google/protobuf/wire_format_lite.h
@@ -346,32 +346,27 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
Operation op,
const char* field_name);
+ template <typename MessageType>
static inline bool ReadGroup(int field_number, io::CodedInputStream* input,
- MessageLite* value);
+ MessageType* value);
+
+ template <typename MessageType>
static inline bool ReadMessage(io::CodedInputStream* input,
- MessageLite* value);
+ MessageType* value);
- // Like above, but de-virtualize the call to MergePartialFromCodedStream().
- // The pointer must point at an instance of MessageType, *not* a subclass (or
- // the subclass must not override MergePartialFromCodedStream()).
+ // Do not use.
template <typename MessageType>
static inline bool ReadGroupNoVirtual(int field_number,
io::CodedInputStream* input,
- MessageType* value);
- template<typename MessageType>
- static inline bool ReadMessageNoVirtual(io::CodedInputStream* input,
- MessageType* value);
-
- // The same, but do not modify input's recursion depth. This is useful
- // when reading a bunch of groups or messages in a loop, because then the
- // recursion depth can be incremented before the loop and decremented after.
- template<typename MessageType>
- static inline bool ReadGroupNoVirtualNoRecursionDepth(
- int field_number, io::CodedInputStream* input, MessageType* value);
+ MessageType* value) {
+ return ReadGroup(field_number, input, value);
+ }
template<typename MessageType>
- static inline bool ReadMessageNoVirtualNoRecursionDepth(
- io::CodedInputStream* input, MessageType* value);
+ static inline bool ReadMessageNoVirtual(io::CodedInputStream* input,
+ MessageType* value) {
+ return ReadMessage(input, value);
+ }
// Write a tag. The Write*() functions typically include the tag, so
// normally there's no need to call this unless using the Write*NoTag()
@@ -612,12 +607,14 @@ 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>
INL static uint8* InternalWriteGroupToArray(int field_number,
- const MessageLite& value,
+ const MessageType& value,
bool deterministic,
uint8* target);
+ template<typename MessageType>
INL static uint8* InternalWriteMessageToArray(int field_number,
- const MessageLite& value,
+ const MessageType& value,
bool deterministic,
uint8* target);
@@ -694,8 +691,10 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
static inline size_t StringSize(const string& value);
static inline size_t BytesSize (const string& value);
- static inline size_t GroupSize (const MessageLite& value);
- static inline size_t MessageSize(const MessageLite& value);
+ 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
@@ -764,9 +763,9 @@ class LIBPROTOBUF_EXPORT CodedOutputStreamFieldSkipper : public FieldSkipper {
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);
+ virtual bool SkipField(io::CodedInputStream* input, uint32 tag) override;
+ virtual bool SkipMessage(io::CodedInputStream* input) override;
+ virtual void SkipUnknownEnum(int field_number, int value) override;
protected:
io::CodedOutputStream* unknown_fields_;
diff --git a/src/google/protobuf/wire_format_lite_inl.h b/src/google/protobuf/wire_format_lite_inl.h
index 82fb62ae..6cd2c2fb 100644
--- a/src/google/protobuf/wire_format_lite_inl.h
+++ b/src/google/protobuf/wire_format_lite_inl.h
@@ -426,48 +426,12 @@ bool WireFormatLite::ReadPackedPrimitiveNoInline(io::CodedInputStream* input,
}
-inline bool WireFormatLite::ReadGroup(int field_number,
- io::CodedInputStream* input,
- MessageLite* value) {
- if (!input->IncrementRecursionDepth()) return false;
- if (!value->MergePartialFromCodedStream(input)) return false;
- input->DecrementRecursionDepth();
- // Make sure the last thing read was an end tag for this group.
- if (!input->LastTagWas(MakeTag(field_number, WIRETYPE_END_GROUP))) {
- return false;
- }
- return true;
-}
-inline bool WireFormatLite::ReadMessage(io::CodedInputStream* input,
- MessageLite* value) {
- int length;
- if (!input->ReadVarintSizeAsInt(&length)) return false;
- std::pair<io::CodedInputStream::Limit, int> p =
- input->IncrementRecursionDepthAndPushLimit(length);
- if (p.second < 0 || !value->MergePartialFromCodedStream(input)) return false;
- // Make sure that parsing stopped when the limit was hit, not at an endgroup
- // tag.
- return input->DecrementRecursionDepthAndPopLimit(p.first);
-}
-
-// We name the template parameter something long and extremely unlikely to occur
-// elsewhere because a *qualified* member access expression designed to avoid
-// virtual dispatch, C++03 [basic.lookup.classref] 3.4.5/4 requires that the
-// name of the qualifying class to be looked up both in the context of the full
-// expression (finding the template parameter) and in the context of the object
-// whose member we are accessing. This could potentially find a nested type
-// within that object. The standard goes on to require these names to refer to
-// the same entity, which this collision would violate. The lack of a safe way
-// to avoid this collision appears to be a defect in the standard, but until it
-// is corrected, we choose the name to avoid accidental collisions.
-template<typename MessageType_WorkAroundCppLookupDefect>
-inline bool WireFormatLite::ReadGroupNoVirtual(
+template<typename MessageType>
+inline bool WireFormatLite::ReadGroup(
int field_number, io::CodedInputStream* input,
- MessageType_WorkAroundCppLookupDefect* value) {
+ MessageType* value) {
if (!input->IncrementRecursionDepth()) return false;
- if (!value->
- MessageType_WorkAroundCppLookupDefect::MergePartialFromCodedStream(input))
- return false;
+ if (!value->MergePartialFromCodedStream(input)) return false;
input->UnsafeDecrementRecursionDepth();
// Make sure the last thing read was an end tag for this group.
if (!input->LastTagWas(MakeTag(field_number, WIRETYPE_END_GROUP))) {
@@ -475,41 +439,19 @@ inline bool WireFormatLite::ReadGroupNoVirtual(
}
return true;
}
-template<typename MessageType_WorkAroundCppLookupDefect>
-inline bool WireFormatLite::ReadGroupNoVirtualNoRecursionDepth(
- int field_number, io::CodedInputStream* input,
- MessageType_WorkAroundCppLookupDefect* value) {
- return value->MessageType_WorkAroundCppLookupDefect::
- MergePartialFromCodedStream(input) &&
- input->LastTagWas(MakeTag(field_number, WIRETYPE_END_GROUP));
-}
-template<typename MessageType_WorkAroundCppLookupDefect>
-inline bool WireFormatLite::ReadMessageNoVirtual(
- io::CodedInputStream* input, MessageType_WorkAroundCppLookupDefect* value) {
+template<typename MessageType>
+inline bool WireFormatLite::ReadMessage(
+ io::CodedInputStream* input, MessageType* value) {
int length;
if (!input->ReadVarintSizeAsInt(&length)) return false;
std::pair<io::CodedInputStream::Limit, int> p =
input->IncrementRecursionDepthAndPushLimit(length);
- if (p.second < 0 || !value->
- MessageType_WorkAroundCppLookupDefect::MergePartialFromCodedStream(input))
- return false;
+ if (p.second < 0 || !value->MergePartialFromCodedStream(input)) return false;
// Make sure that parsing stopped when the limit was hit, not at an endgroup
// tag.
return input->DecrementRecursionDepthAndPopLimit(p.first);
}
-template<typename MessageType_WorkAroundCppLookupDefect>
-inline bool WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- io::CodedInputStream* input, MessageType_WorkAroundCppLookupDefect* value) {
- io::CodedInputStream::Limit old_limit = input->ReadLengthAndPushLimit();
- if (!value->
- MessageType_WorkAroundCppLookupDefect::MergePartialFromCodedStream(input))
- return false;
- // Make sure that parsing stopped when the limit was hit, not at an endgroup
- // tag.
- return input->CheckEntireMessageConsumedAndPopLimit(old_limit);
-}
-
// ===================================================================
inline void WireFormatLite::WriteTag(int field_number, WireType type,
@@ -941,15 +883,17 @@ inline uint8* WireFormatLite::WriteBytesToArray(int field_number,
}
+template<typename MessageType>
inline uint8* WireFormatLite::InternalWriteGroupToArray(
- int field_number, const MessageLite& value, bool deterministic,
+ int field_number, const MessageType& value, bool deterministic,
uint8* target) {
target = WriteTagToArray(field_number, WIRETYPE_START_GROUP, target);
target = value.InternalSerializeWithCachedSizesToArray(deterministic, target);
return WriteTagToArray(field_number, WIRETYPE_END_GROUP, target);
}
+template<typename MessageType>
inline uint8* WireFormatLite::InternalWriteMessageToArray(
- int field_number, const MessageLite& value, bool deterministic,
+ int field_number, const MessageType& value, bool deterministic,
uint8* target) {
target = WriteTagToArray(field_number, WIRETYPE_LENGTH_DELIMITED, target);
target = io::CodedOutputStream::WriteVarint32ToArray(
@@ -1013,10 +957,12 @@ inline size_t WireFormatLite::BytesSize(const string& value) {
}
-inline size_t WireFormatLite::GroupSize(const MessageLite& value) {
+template<typename MessageType>
+inline size_t WireFormatLite::GroupSize(const MessageType& value) {
return value.ByteSizeLong();
}
-inline size_t WireFormatLite::MessageSize(const MessageLite& value) {
+template<typename MessageType>
+inline size_t WireFormatLite::MessageSize(const MessageType& value) {
return LengthDelimitedSize(value.ByteSizeLong());
}
diff --git a/src/google/protobuf/wrappers.pb.cc b/src/google/protobuf/wrappers.pb.cc
index 34c6fed1..8f254b82 100644
--- a/src/google/protobuf/wrappers.pb.cc
+++ b/src/google/protobuf/wrappers.pb.cc
@@ -7,7 +7,6 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
@@ -19,6 +18,7 @@
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
+
namespace google {
namespace protobuf {
class DoubleValueDefaultTypeInternal {
@@ -69,14 +69,9 @@ class BytesValueDefaultTypeInternal {
} // namespace protobuf
} // namespace google
namespace protobuf_google_2fprotobuf_2fwrappers_2eproto {
-void InitDefaultsDoubleValueImpl() {
+static void InitDefaultsDoubleValue() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_DoubleValue_default_instance_;
new (ptr) ::google::protobuf::DoubleValue();
@@ -85,19 +80,12 @@ void InitDefaultsDoubleValueImpl() {
::google::protobuf::DoubleValue::InitAsDefaultInstance();
}
-void InitDefaultsDoubleValue() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDoubleValueImpl);
-}
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_DoubleValue =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDoubleValue}, {}};
-void InitDefaultsFloatValueImpl() {
+static void InitDefaultsFloatValue() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_FloatValue_default_instance_;
new (ptr) ::google::protobuf::FloatValue();
@@ -106,19 +94,12 @@ void InitDefaultsFloatValueImpl() {
::google::protobuf::FloatValue::InitAsDefaultInstance();
}
-void InitDefaultsFloatValue() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFloatValueImpl);
-}
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_FloatValue =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsFloatValue}, {}};
-void InitDefaultsInt64ValueImpl() {
+static void InitDefaultsInt64Value() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_Int64Value_default_instance_;
new (ptr) ::google::protobuf::Int64Value();
@@ -127,19 +108,12 @@ void InitDefaultsInt64ValueImpl() {
::google::protobuf::Int64Value::InitAsDefaultInstance();
}
-void InitDefaultsInt64Value() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsInt64ValueImpl);
-}
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Int64Value =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsInt64Value}, {}};
-void InitDefaultsUInt64ValueImpl() {
+static void InitDefaultsUInt64Value() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_UInt64Value_default_instance_;
new (ptr) ::google::protobuf::UInt64Value();
@@ -148,19 +122,12 @@ void InitDefaultsUInt64ValueImpl() {
::google::protobuf::UInt64Value::InitAsDefaultInstance();
}
-void InitDefaultsUInt64Value() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsUInt64ValueImpl);
-}
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UInt64Value =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsUInt64Value}, {}};
-void InitDefaultsInt32ValueImpl() {
+static void InitDefaultsInt32Value() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_Int32Value_default_instance_;
new (ptr) ::google::protobuf::Int32Value();
@@ -169,19 +136,12 @@ void InitDefaultsInt32ValueImpl() {
::google::protobuf::Int32Value::InitAsDefaultInstance();
}
-void InitDefaultsInt32Value() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsInt32ValueImpl);
-}
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Int32Value =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsInt32Value}, {}};
-void InitDefaultsUInt32ValueImpl() {
+static void InitDefaultsUInt32Value() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_UInt32Value_default_instance_;
new (ptr) ::google::protobuf::UInt32Value();
@@ -190,19 +150,12 @@ void InitDefaultsUInt32ValueImpl() {
::google::protobuf::UInt32Value::InitAsDefaultInstance();
}
-void InitDefaultsUInt32Value() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsUInt32ValueImpl);
-}
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UInt32Value =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsUInt32Value}, {}};
-void InitDefaultsBoolValueImpl() {
+static void InitDefaultsBoolValue() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_BoolValue_default_instance_;
new (ptr) ::google::protobuf::BoolValue();
@@ -211,19 +164,12 @@ void InitDefaultsBoolValueImpl() {
::google::protobuf::BoolValue::InitAsDefaultInstance();
}
-void InitDefaultsBoolValue() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsBoolValueImpl);
-}
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_BoolValue =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsBoolValue}, {}};
-void InitDefaultsStringValueImpl() {
+static void InitDefaultsStringValue() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_StringValue_default_instance_;
new (ptr) ::google::protobuf::StringValue();
@@ -232,19 +178,12 @@ void InitDefaultsStringValueImpl() {
::google::protobuf::StringValue::InitAsDefaultInstance();
}
-void InitDefaultsStringValue() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsStringValueImpl);
-}
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_StringValue =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsStringValue}, {}};
-void InitDefaultsBytesValueImpl() {
+static void InitDefaultsBytesValue() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
-#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
- ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
-#else
- ::google::protobuf::internal::InitProtobufDefaults();
-#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_BytesValue_default_instance_;
new (ptr) ::google::protobuf::BytesValue();
@@ -253,9 +192,19 @@ void InitDefaultsBytesValueImpl() {
::google::protobuf::BytesValue::InitAsDefaultInstance();
}
-void InitDefaultsBytesValue() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsBytesValueImpl);
+LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_BytesValue =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsBytesValue}, {}};
+
+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);
}
::google::protobuf::Metadata file_level_metadata[9];
@@ -340,17 +289,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_BytesValue_default_instance_),
};
-void protobuf_AssignDescriptors() {
+static void protobuf_AssignDescriptors() {
AddDescriptors();
- ::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/wrappers.proto", schemas, file_default_instances, TableStruct::offsets, factory,
+ "google/protobuf/wrappers.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
-void protobuf_AssignDescriptorsOnce() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
+static 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;
@@ -359,7 +307,7 @@ void protobuf_RegisterTypes(const ::std::string&) {
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 9);
}
-void AddDescriptorsImpl() {
+static void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\036google/protobuf/wrappers.proto\022\017google"
@@ -382,8 +330,8 @@ void AddDescriptorsImpl() {
}
void AddDescriptors() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
+ 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 {
@@ -405,24 +353,22 @@ const int DoubleValue::kValueFieldNumber;
DoubleValue::DoubleValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsDoubleValue();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsDoubleValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_DoubleValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.DoubleValue)
}
DoubleValue::DoubleValue(const DoubleValue& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
value_ = from.value_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.DoubleValue)
@@ -430,7 +376,6 @@ DoubleValue::DoubleValue(const DoubleValue& from)
void DoubleValue::SharedCtor() {
value_ = 0;
- _cached_size_ = 0;
}
DoubleValue::~DoubleValue() {
@@ -446,12 +391,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* DoubleValue::descriptor() {
::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
@@ -459,7 +402,7 @@ const ::google::protobuf::Descriptor* DoubleValue::descriptor() {
}
const DoubleValue& DoubleValue::default_instance() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsDoubleValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_DoubleValue.base);
return *internal_default_instance();
}
@@ -480,7 +423,7 @@ bool DoubleValue::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.DoubleValue)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -571,9 +514,7 @@ size_t DoubleValue::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -645,7 +586,6 @@ void DoubleValue::InternalSwap(DoubleValue* other) {
using std::swap;
swap(value_, other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata DoubleValue::GetMetadata() const {
@@ -664,24 +604,22 @@ const int FloatValue::kValueFieldNumber;
FloatValue::FloatValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsFloatValue();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsFloatValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_FloatValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FloatValue)
}
FloatValue::FloatValue(const FloatValue& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
value_ = from.value_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.FloatValue)
@@ -689,7 +627,6 @@ FloatValue::FloatValue(const FloatValue& from)
void FloatValue::SharedCtor() {
value_ = 0;
- _cached_size_ = 0;
}
FloatValue::~FloatValue() {
@@ -705,12 +642,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* FloatValue::descriptor() {
::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
@@ -718,7 +653,7 @@ const ::google::protobuf::Descriptor* FloatValue::descriptor() {
}
const FloatValue& FloatValue::default_instance() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsFloatValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_FloatValue.base);
return *internal_default_instance();
}
@@ -739,7 +674,7 @@ bool FloatValue::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.FloatValue)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -830,9 +765,7 @@ size_t FloatValue::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -904,7 +837,6 @@ void FloatValue::InternalSwap(FloatValue* other) {
using std::swap;
swap(value_, other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata FloatValue::GetMetadata() const {
@@ -923,24 +855,22 @@ const int Int64Value::kValueFieldNumber;
Int64Value::Int64Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt64Value();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt64Value();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int64Value.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Int64Value)
}
Int64Value::Int64Value(const Int64Value& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
value_ = from.value_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.Int64Value)
@@ -948,7 +878,6 @@ Int64Value::Int64Value(const Int64Value& from)
void Int64Value::SharedCtor() {
value_ = GOOGLE_LONGLONG(0);
- _cached_size_ = 0;
}
Int64Value::~Int64Value() {
@@ -964,12 +893,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Int64Value::descriptor() {
::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
@@ -977,7 +904,7 @@ const ::google::protobuf::Descriptor* Int64Value::descriptor() {
}
const Int64Value& Int64Value::default_instance() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt64Value();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int64Value.base);
return *internal_default_instance();
}
@@ -998,7 +925,7 @@ bool Int64Value::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Int64Value)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -1091,9 +1018,7 @@ size_t Int64Value::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -1165,7 +1090,6 @@ void Int64Value::InternalSwap(Int64Value* other) {
using std::swap;
swap(value_, other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Int64Value::GetMetadata() const {
@@ -1184,24 +1108,22 @@ const int UInt64Value::kValueFieldNumber;
UInt64Value::UInt64Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt64Value();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt64Value();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt64Value.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.UInt64Value)
}
UInt64Value::UInt64Value(const UInt64Value& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
value_ = from.value_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.UInt64Value)
@@ -1209,7 +1131,6 @@ UInt64Value::UInt64Value(const UInt64Value& from)
void UInt64Value::SharedCtor() {
value_ = GOOGLE_ULONGLONG(0);
- _cached_size_ = 0;
}
UInt64Value::~UInt64Value() {
@@ -1225,12 +1146,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* UInt64Value::descriptor() {
::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
@@ -1238,7 +1157,7 @@ const ::google::protobuf::Descriptor* UInt64Value::descriptor() {
}
const UInt64Value& UInt64Value::default_instance() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt64Value();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt64Value.base);
return *internal_default_instance();
}
@@ -1259,7 +1178,7 @@ bool UInt64Value::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.UInt64Value)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -1352,9 +1271,7 @@ size_t UInt64Value::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -1426,7 +1343,6 @@ void UInt64Value::InternalSwap(UInt64Value* other) {
using std::swap;
swap(value_, other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata UInt64Value::GetMetadata() const {
@@ -1445,24 +1361,22 @@ const int Int32Value::kValueFieldNumber;
Int32Value::Int32Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt32Value();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt32Value();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int32Value.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Int32Value)
}
Int32Value::Int32Value(const Int32Value& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
value_ = from.value_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.Int32Value)
@@ -1470,7 +1384,6 @@ Int32Value::Int32Value(const Int32Value& from)
void Int32Value::SharedCtor() {
value_ = 0;
- _cached_size_ = 0;
}
Int32Value::~Int32Value() {
@@ -1486,12 +1399,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Int32Value::descriptor() {
::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
@@ -1499,7 +1410,7 @@ const ::google::protobuf::Descriptor* Int32Value::descriptor() {
}
const Int32Value& Int32Value::default_instance() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt32Value();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int32Value.base);
return *internal_default_instance();
}
@@ -1520,7 +1431,7 @@ bool Int32Value::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Int32Value)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -1613,9 +1524,7 @@ size_t Int32Value::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -1687,7 +1596,6 @@ void Int32Value::InternalSwap(Int32Value* other) {
using std::swap;
swap(value_, other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Int32Value::GetMetadata() const {
@@ -1706,24 +1614,22 @@ const int UInt32Value::kValueFieldNumber;
UInt32Value::UInt32Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt32Value();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt32Value();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt32Value.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.UInt32Value)
}
UInt32Value::UInt32Value(const UInt32Value& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
value_ = from.value_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.UInt32Value)
@@ -1731,7 +1637,6 @@ UInt32Value::UInt32Value(const UInt32Value& from)
void UInt32Value::SharedCtor() {
value_ = 0u;
- _cached_size_ = 0;
}
UInt32Value::~UInt32Value() {
@@ -1747,12 +1652,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* UInt32Value::descriptor() {
::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
@@ -1760,7 +1663,7 @@ const ::google::protobuf::Descriptor* UInt32Value::descriptor() {
}
const UInt32Value& UInt32Value::default_instance() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt32Value();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt32Value.base);
return *internal_default_instance();
}
@@ -1781,7 +1684,7 @@ bool UInt32Value::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.UInt32Value)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -1874,9 +1777,7 @@ size_t UInt32Value::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -1948,7 +1849,6 @@ void UInt32Value::InternalSwap(UInt32Value* other) {
using std::swap;
swap(value_, other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata UInt32Value::GetMetadata() const {
@@ -1967,24 +1867,22 @@ const int BoolValue::kValueFieldNumber;
BoolValue::BoolValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBoolValue();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBoolValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BoolValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.BoolValue)
}
BoolValue::BoolValue(const BoolValue& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
value_ = from.value_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.BoolValue)
@@ -1992,7 +1890,6 @@ BoolValue::BoolValue(const BoolValue& from)
void BoolValue::SharedCtor() {
value_ = false;
- _cached_size_ = 0;
}
BoolValue::~BoolValue() {
@@ -2008,12 +1905,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* BoolValue::descriptor() {
::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
@@ -2021,7 +1916,7 @@ const ::google::protobuf::Descriptor* BoolValue::descriptor() {
}
const BoolValue& BoolValue::default_instance() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBoolValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BoolValue.base);
return *internal_default_instance();
}
@@ -2042,7 +1937,7 @@ bool BoolValue::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.BoolValue)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -2133,9 +2028,7 @@ size_t BoolValue::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -2207,7 +2100,6 @@ void BoolValue::InternalSwap(BoolValue* other) {
using std::swap;
swap(value_, other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata BoolValue::GetMetadata() const {
@@ -2226,24 +2118,22 @@ const int StringValue::kValueFieldNumber;
StringValue::StringValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsStringValue();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsStringValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_StringValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.StringValue)
}
StringValue::StringValue(const StringValue& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.value().size() > 0) {
@@ -2255,7 +2145,6 @@ StringValue::StringValue(const StringValue& from)
void StringValue::SharedCtor() {
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- _cached_size_ = 0;
}
StringValue::~StringValue() {
@@ -2272,12 +2161,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* StringValue::descriptor() {
::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
@@ -2285,7 +2172,7 @@ const ::google::protobuf::Descriptor* StringValue::descriptor() {
}
const StringValue& StringValue::default_instance() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsStringValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_StringValue.base);
return *internal_default_instance();
}
@@ -2306,7 +2193,7 @@ bool StringValue::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.StringValue)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -2412,9 +2299,7 @@ size_t StringValue::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -2484,9 +2369,9 @@ void StringValue::UnsafeArenaSwap(StringValue* other) {
}
void StringValue::InternalSwap(StringValue* other) {
using std::swap;
- value_.Swap(&other->value_);
+ value_.Swap(&other->value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata StringValue::GetMetadata() const {
@@ -2505,24 +2390,22 @@ const int BytesValue::kValueFieldNumber;
BytesValue::BytesValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBytesValue();
- }
+ ::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) {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBytesValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BytesValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.BytesValue)
}
BytesValue::BytesValue(const BytesValue& from)
: ::google::protobuf::Message(),
- _internal_metadata_(NULL),
- _cached_size_(0) {
+ _internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.value().size() > 0) {
@@ -2534,7 +2417,6 @@ BytesValue::BytesValue(const BytesValue& from)
void BytesValue::SharedCtor() {
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- _cached_size_ = 0;
}
BytesValue::~BytesValue() {
@@ -2551,12 +2433,10 @@ 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 {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* BytesValue::descriptor() {
::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
@@ -2564,7 +2444,7 @@ const ::google::protobuf::Descriptor* BytesValue::descriptor() {
}
const BytesValue& BytesValue::default_instance() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBytesValue();
+ ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BytesValue.base);
return *internal_default_instance();
}
@@ -2585,7 +2465,7 @@ bool BytesValue::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.BytesValue)
for (;;) {
- ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
@@ -2679,9 +2559,7 @@ size_t BytesValue::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ SetCachedSize(cached_size);
return total_size;
}
@@ -2751,9 +2629,9 @@ void BytesValue::UnsafeArenaSwap(BytesValue* other) {
}
void BytesValue::InternalSwap(BytesValue* other) {
using std::swap;
- value_.Swap(&other->value_);
+ value_.Swap(&other->value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata BytesValue::GetMetadata() const {
@@ -2767,31 +2645,31 @@ void BytesValue::InternalSwap(BytesValue* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DoubleValue* Arena::CreateMessage< ::google::protobuf::DoubleValue >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::FloatValue >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::Int64Value >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::UInt64Value >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::Int32Value >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::UInt32Value >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::BoolValue >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::StringValue >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_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::CreateMessage< ::google::protobuf::BytesValue >(Arena* arena) {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::BytesValue* Arena::CreateMaybeMessage< ::google::protobuf::BytesValue >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::BytesValue >(arena);
}
} // namespace protobuf
diff --git a/src/google/protobuf/wrappers.pb.h b/src/google/protobuf/wrappers.pb.h
index 876bf39b..b00d4ea9 100644
--- a/src/google/protobuf/wrappers.pb.h
+++ b/src/google/protobuf/wrappers.pb.h
@@ -1,19 +1,19 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/wrappers.proto
-#ifndef PROTOBUF_google_2fprotobuf_2fwrappers_2eproto_INCLUDED
-#define PROTOBUF_google_2fprotobuf_2fwrappers_2eproto_INCLUDED
+#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fwrappers_2eproto
+#define PROTOBUF_INCLUDED_google_2fprotobuf_2fwrappers_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3005000
+#if GOOGLE_PROTOBUF_VERSION < 3006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3005001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -24,12 +24,14 @@
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
+#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fwrappers_2eproto LIBPROTOBUF_EXPORT
namespace protobuf_google_2fprotobuf_2fwrappers_2eproto {
// Internal implementation detail -- do not use these members.
@@ -42,35 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::uint32 offsets[];
};
void LIBPROTOBUF_EXPORT AddDescriptors();
-void LIBPROTOBUF_EXPORT InitDefaultsDoubleValueImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsDoubleValue();
-void LIBPROTOBUF_EXPORT InitDefaultsFloatValueImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsFloatValue();
-void LIBPROTOBUF_EXPORT InitDefaultsInt64ValueImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsInt64Value();
-void LIBPROTOBUF_EXPORT InitDefaultsUInt64ValueImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsUInt64Value();
-void LIBPROTOBUF_EXPORT InitDefaultsInt32ValueImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsInt32Value();
-void LIBPROTOBUF_EXPORT InitDefaultsUInt32ValueImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsUInt32Value();
-void LIBPROTOBUF_EXPORT InitDefaultsBoolValueImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsBoolValue();
-void LIBPROTOBUF_EXPORT InitDefaultsStringValueImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsStringValue();
-void LIBPROTOBUF_EXPORT InitDefaultsBytesValueImpl();
-void LIBPROTOBUF_EXPORT InitDefaultsBytesValue();
-inline void LIBPROTOBUF_EXPORT InitDefaults() {
- InitDefaultsDoubleValue();
- InitDefaultsFloatValue();
- InitDefaultsInt64Value();
- InitDefaultsUInt64Value();
- InitDefaultsInt32Value();
- InitDefaultsUInt32Value();
- InitDefaultsBoolValue();
- InitDefaultsStringValue();
- InitDefaultsBytesValue();
-}
} // namespace protobuf_google_2fprotobuf_2fwrappers_2eproto
namespace google {
namespace protobuf {
@@ -105,15 +78,15 @@ LIBPROTOBUF_EXPORT extern UInt64ValueDefaultTypeInternal _UInt64Value_default_in
} // namespace google
namespace google {
namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::BoolValue* Arena::CreateMessage< ::google::protobuf::BoolValue>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::BytesValue* Arena::CreateMessage< ::google::protobuf::BytesValue>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::DoubleValue* Arena::CreateMessage< ::google::protobuf::DoubleValue>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::FloatValue* Arena::CreateMessage< ::google::protobuf::FloatValue>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Int32Value* Arena::CreateMessage< ::google::protobuf::Int32Value>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Int64Value* Arena::CreateMessage< ::google::protobuf::Int64Value>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::StringValue* Arena::CreateMessage< ::google::protobuf::StringValue>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::UInt32Value* Arena::CreateMessage< ::google::protobuf::UInt32Value>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::UInt64Value* Arena::CreateMessage< ::google::protobuf::UInt64Value>(Arena*);
+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*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -147,10 +120,10 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -161,7 +134,7 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
return reinterpret_cast<const DoubleValue*>(
&_DoubleValue_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
0;
void UnsafeArenaSwap(DoubleValue* other);
@@ -172,32 +145,33 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
// implements Message ----------------------------------------------
- inline DoubleValue* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<DoubleValue>(NULL);
+ inline DoubleValue* New() const final {
+ return CreateMaybeMessage<DoubleValue>(NULL);
}
- DoubleValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<DoubleValue>(arena);
+ DoubleValue* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<DoubleValue>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const DoubleValue& from);
void MergeFrom(const DoubleValue& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(DoubleValue* other);
protected:
explicit DoubleValue(::google::protobuf::Arena* arena);
@@ -213,7 +187,7 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -233,9 +207,8 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
double value_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsDoubleValueImpl();
};
// -------------------------------------------------------------------
@@ -265,10 +238,10 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -279,7 +252,7 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
return reinterpret_cast<const FloatValue*>(
&_FloatValue_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
1;
void UnsafeArenaSwap(FloatValue* other);
@@ -290,32 +263,33 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
// implements Message ----------------------------------------------
- inline FloatValue* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<FloatValue>(NULL);
+ inline FloatValue* New() const final {
+ return CreateMaybeMessage<FloatValue>(NULL);
}
- FloatValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<FloatValue>(arena);
+ FloatValue* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<FloatValue>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const FloatValue& from);
void MergeFrom(const FloatValue& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(FloatValue* other);
protected:
explicit FloatValue(::google::protobuf::Arena* arena);
@@ -331,7 +305,7 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -351,9 +325,8 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
float value_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsFloatValueImpl();
};
// -------------------------------------------------------------------
@@ -383,10 +356,10 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -397,7 +370,7 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
return reinterpret_cast<const Int64Value*>(
&_Int64Value_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
2;
void UnsafeArenaSwap(Int64Value* other);
@@ -408,32 +381,33 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
// implements Message ----------------------------------------------
- inline Int64Value* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Int64Value>(NULL);
+ inline Int64Value* New() const final {
+ return CreateMaybeMessage<Int64Value>(NULL);
}
- Int64Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Int64Value>(arena);
+ Int64Value* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Int64Value>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Int64Value& from);
void MergeFrom(const Int64Value& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Int64Value* other);
protected:
explicit Int64Value(::google::protobuf::Arena* arena);
@@ -449,7 +423,7 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -469,9 +443,8 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::int64 value_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt64ValueImpl();
};
// -------------------------------------------------------------------
@@ -501,10 +474,10 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -515,7 +488,7 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
return reinterpret_cast<const UInt64Value*>(
&_UInt64Value_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
3;
void UnsafeArenaSwap(UInt64Value* other);
@@ -526,32 +499,33 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
// implements Message ----------------------------------------------
- inline UInt64Value* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<UInt64Value>(NULL);
+ inline UInt64Value* New() const final {
+ return CreateMaybeMessage<UInt64Value>(NULL);
}
- UInt64Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<UInt64Value>(arena);
+ UInt64Value* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<UInt64Value>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const UInt64Value& from);
void MergeFrom(const UInt64Value& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(UInt64Value* other);
protected:
explicit UInt64Value(::google::protobuf::Arena* arena);
@@ -567,7 +541,7 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -587,9 +561,8 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::uint64 value_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt64ValueImpl();
};
// -------------------------------------------------------------------
@@ -619,10 +592,10 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -633,7 +606,7 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
return reinterpret_cast<const Int32Value*>(
&_Int32Value_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
4;
void UnsafeArenaSwap(Int32Value* other);
@@ -644,32 +617,33 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
// implements Message ----------------------------------------------
- inline Int32Value* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Int32Value>(NULL);
+ inline Int32Value* New() const final {
+ return CreateMaybeMessage<Int32Value>(NULL);
}
- Int32Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<Int32Value>(arena);
+ Int32Value* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Int32Value>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Int32Value& from);
void MergeFrom(const Int32Value& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(Int32Value* other);
protected:
explicit Int32Value(::google::protobuf::Arena* arena);
@@ -685,7 +659,7 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -705,9 +679,8 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::int32 value_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt32ValueImpl();
};
// -------------------------------------------------------------------
@@ -737,10 +710,10 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -751,7 +724,7 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
return reinterpret_cast<const UInt32Value*>(
&_UInt32Value_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
5;
void UnsafeArenaSwap(UInt32Value* other);
@@ -762,32 +735,33 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
// implements Message ----------------------------------------------
- inline UInt32Value* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<UInt32Value>(NULL);
+ inline UInt32Value* New() const final {
+ return CreateMaybeMessage<UInt32Value>(NULL);
}
- UInt32Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<UInt32Value>(arena);
+ UInt32Value* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<UInt32Value>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const UInt32Value& from);
void MergeFrom(const UInt32Value& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(UInt32Value* other);
protected:
explicit UInt32Value(::google::protobuf::Arena* arena);
@@ -803,7 +777,7 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -823,9 +797,8 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::uint32 value_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt32ValueImpl();
};
// -------------------------------------------------------------------
@@ -855,10 +828,10 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -869,7 +842,7 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
return reinterpret_cast<const BoolValue*>(
&_BoolValue_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
6;
void UnsafeArenaSwap(BoolValue* other);
@@ -880,32 +853,33 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
// implements Message ----------------------------------------------
- inline BoolValue* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<BoolValue>(NULL);
+ inline BoolValue* New() const final {
+ return CreateMaybeMessage<BoolValue>(NULL);
}
- BoolValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<BoolValue>(arena);
+ BoolValue* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<BoolValue>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const BoolValue& from);
void MergeFrom(const BoolValue& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(BoolValue* other);
protected:
explicit BoolValue(::google::protobuf::Arena* arena);
@@ -921,7 +895,7 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -941,9 +915,8 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
bool value_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBoolValueImpl();
};
// -------------------------------------------------------------------
@@ -973,10 +946,10 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -987,7 +960,7 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
return reinterpret_cast<const StringValue*>(
&_StringValue_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
7;
void UnsafeArenaSwap(StringValue* other);
@@ -998,32 +971,33 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
// implements Message ----------------------------------------------
- inline StringValue* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<StringValue>(NULL);
+ inline StringValue* New() const final {
+ return CreateMaybeMessage<StringValue>(NULL);
}
- StringValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<StringValue>(arena);
+ StringValue* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<StringValue>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const StringValue& from);
void MergeFrom(const StringValue& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(StringValue* other);
protected:
explicit StringValue(::google::protobuf::Arena* arena);
@@ -1039,7 +1013,7 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -1076,9 +1050,8 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::ArenaStringPtr value_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsStringValueImpl();
};
// -------------------------------------------------------------------
@@ -1108,10 +1081,10 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
return *this;
}
#endif
- inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
- inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
@@ -1122,7 +1095,7 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
return reinterpret_cast<const BytesValue*>(
&_BytesValue_default_instance_);
}
- static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ static constexpr int kIndexInFileMessages =
8;
void UnsafeArenaSwap(BytesValue* other);
@@ -1133,32 +1106,33 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
// implements Message ----------------------------------------------
- inline BytesValue* New() const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<BytesValue>(NULL);
+ inline BytesValue* New() const final {
+ return CreateMaybeMessage<BytesValue>(NULL);
}
- BytesValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL {
- return ::google::protobuf::Arena::CreateMessage<BytesValue>(arena);
+ BytesValue* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<BytesValue>(arena);
}
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) final;
+ void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const BytesValue& from);
void MergeFrom(const BytesValue& from);
- void Clear() PROTOBUF_FINAL;
- bool IsInitialized() const PROTOBUF_FINAL;
+ void Clear() final;
+ bool IsInitialized() const final;
- size_t ByteSizeLong() const PROTOBUF_FINAL;
+ size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
- bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ bool deterministic, ::google::protobuf::uint8* target) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
private:
void SharedCtor();
void SharedDtor();
- void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void SetCachedSize(int size) const final;
void InternalSwap(BytesValue* other);
protected:
explicit BytesValue(::google::protobuf::Arena* arena);
@@ -1174,7 +1148,7 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
}
public:
- ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -1211,9 +1185,8 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::ArenaStringPtr value_;
- mutable int _cached_size_;
+ mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
- friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBytesValueImpl();
};
// ===================================================================
@@ -1533,4 +1506,4 @@ inline void BytesValue::unsafe_arena_set_allocated_value(
// @@protoc_insertion_point(global_scope)
-#endif // PROTOBUF_google_2fprotobuf_2fwrappers_2eproto_INCLUDED
+#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fwrappers_2eproto
diff --git a/tests.sh b/tests.sh
index 76286fc9..da607281 100755
--- a/tests.sh
+++ b/tests.sh
@@ -27,6 +27,9 @@ internal_build_cpp() {
export CXX="g++-4.8" CC="gcc-4.8"
fi
+ # Initialize any submodules.
+ git submodule update --init --recursive
+
./autogen.sh
./configure CXXFLAGS="-fPIC" # -fPIC is needed for python cpp test.
# See python/setup.py for more details
@@ -35,7 +38,7 @@ internal_build_cpp() {
build_cpp() {
internal_build_cpp
- make check -j2
+ make check -j2 || (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
@@ -53,6 +56,8 @@ build_cpp() {
}
build_cpp_distcheck() {
+ # Initialize any submodules.
+ git submodule update --init --recursive
./autogen.sh
./configure
make dist
@@ -102,7 +107,7 @@ build_csharp() {
# Check that the protos haven't broken C# codegen.
# TODO(jonskeet): Fail if regenerating creates any changes.
csharp/generate_protos.sh
-
+
csharp/buildall.sh
cd conformance && make test_csharp && cd ..
@@ -223,7 +228,8 @@ internal_install_python_deps() {
fi
# Install tox (OS X doesn't have pip).
if [ $(uname -s) == "Darwin" ]; then
- sudo easy_install tox
+ brew upgrade python
+ python3 -m pip install tox
else
sudo pip install tox
fi
@@ -346,6 +352,7 @@ generate_php_test_proto() {
rm -rf generated
mkdir generated
../../src/protoc --php_out=generated \
+ proto/empty/echo.proto \
proto/test.proto \
proto/test_include.proto \
proto/test_no_namespace.proto \
@@ -419,7 +426,7 @@ build_php5.5_c() {
use_php 5.5
wget https://phar.phpunit.de/phpunit-4.8.0.phar -O /usr/bin/phpunit
pushd php/tests
- /bin/bash ./test.sh
+ /bin/bash ./test.sh 5.5
popd
# TODO(teboring): Add it back
# pushd conformance
@@ -430,7 +437,7 @@ build_php5.5_c() {
build_php5.5_zts_c() {
use_php_zts 5.5
wget https://phar.phpunit.de/phpunit-4.8.0.phar -O /usr/bin/phpunit
- cd php/tests && /bin/bash ./test.sh && cd ../..
+ cd php/tests && /bin/bash ./test.sh 5.5-zts && cd ../..
# TODO(teboring): Add it back
# pushd conformance
# make test_php_zts_c
@@ -453,7 +460,7 @@ build_php5.6() {
build_php5.6_c() {
use_php 5.6
wget https://phar.phpunit.de/phpunit-5.7.0.phar -O /usr/bin/phpunit
- cd php/tests && /bin/bash ./test.sh && cd ../..
+ cd php/tests && /bin/bash ./test.sh 5.6 && cd ../..
# TODO(teboring): Add it back
# pushd conformance
# make test_php_c
@@ -463,7 +470,7 @@ build_php5.6_c() {
build_php5.6_zts_c() {
use_php_zts 5.6
wget https://phar.phpunit.de/phpunit-5.7.0.phar -O /usr/bin/phpunit
- cd php/tests && /bin/bash ./test.sh && cd ../..
+ cd php/tests && /bin/bash ./test.sh 5.6-zts && cd ../..
# TODO(teboring): Add it back
# pushd conformance
# make test_php_zts_c
@@ -511,7 +518,7 @@ build_php7.0() {
build_php7.0_c() {
use_php 7.0
wget https://phar.phpunit.de/phpunit-5.6.0.phar -O /usr/bin/phpunit
- cd php/tests && /bin/bash ./test.sh && cd ../..
+ cd php/tests && /bin/bash ./test.sh 7.0 && cd ../..
# TODO(teboring): Add it back
# pushd conformance
# make test_php_c
@@ -521,7 +528,7 @@ build_php7.0_c() {
build_php7.0_zts_c() {
use_php_zts 7.0
wget https://phar.phpunit.de/phpunit-5.6.0.phar -O /usr/bin/phpunit
- cd php/tests && /bin/bash ./test.sh && cd ../..
+ cd php/tests && /bin/bash ./test.sh 7.0-zts && cd ../..
# TODO(teboring): Add it back.
# pushd conformance
# make test_php_zts_c
@@ -575,7 +582,7 @@ build_php7.1() {
build_php7.1_c() {
use_php 7.1
wget https://phar.phpunit.de/phpunit-5.6.0.phar -O /usr/bin/phpunit
- cd php/tests && /bin/bash ./test.sh && cd ../..
+ cd php/tests && /bin/bash ./test.sh 7.1 && cd ../..
pushd conformance
# make test_php_c
popd
@@ -584,7 +591,7 @@ build_php7.1_c() {
build_php7.1_zts_c() {
use_php_zts 7.1
wget https://phar.phpunit.de/phpunit-5.6.0.phar -O /usr/bin/phpunit
- cd php/tests && /bin/bash ./test.sh && cd ../..
+ cd php/tests && /bin/bash ./test.sh 7.1-zts && cd ../..
pushd conformance
# make test_php_c
popd
diff --git a/third_party/googletest b/third_party/googletest
new file mode 160000
+Subproject c3bb0ee2a63279a803aaad956b9b26d74bf9e6e
diff --git a/update_file_lists.sh b/update_file_lists.sh
index 9c0fbdc5..646c8ce3 100755
--- a/update_file_lists.sh
+++ b/update_file_lists.sh
@@ -1,4 +1,4 @@
-#!/bin/sh
+#!/bin/bash
# This script copies source file lists from src/Makefile.am to cmake files.
@@ -24,7 +24,7 @@ get_header_files() {
}
get_source_files() {
- get_variable_value $@ | grep "cc$"
+ get_variable_value $@ | grep "cc$\|inc$"
}
get_proto_files_blacklisted() {
@@ -55,6 +55,7 @@ PUBLIC_HEADERS=$(sort_files $GZHEADERS $HEADERS)
LIBPROTOBUF_LITE_SOURCES=$(get_source_files $MAKEFILE libprotobuf_lite_la_SOURCES)
LIBPROTOBUF_SOURCES=$(get_source_files $MAKEFILE libprotobuf_la_SOURCES)
LIBPROTOC_SOURCES=$(get_source_files $MAKEFILE libprotoc_la_SOURCES)
+LIBPROTOC_HEADERS=$(get_header_files $MAKEFILE libprotoc_la_SOURCES)
LITE_PROTOS=$(get_proto_files $MAKEFILE protoc_lite_outputs)
PROTOS=$(get_proto_files $MAKEFILE protoc_outputs)
PROTOS_BLACKLISTED=$(get_proto_files_blacklisted $MAKEFILE protoc_outputs)
@@ -116,6 +117,7 @@ CMAKE_PREFIX="\${protobuf_source_dir}/src/"
set_cmake_value $CMAKE_DIR/libprotobuf-lite.cmake libprotobuf_lite_files $CMAKE_PREFIX $LIBPROTOBUF_LITE_SOURCES
set_cmake_value $CMAKE_DIR/libprotobuf.cmake libprotobuf_files $CMAKE_PREFIX $LIBPROTOBUF_SOURCES
set_cmake_value $CMAKE_DIR/libprotoc.cmake libprotoc_files $CMAKE_PREFIX $LIBPROTOC_SOURCES
+set_cmake_value $CMAKE_DIR/libprotoc.cmake libprotoc_headers $CMAKE_PREFIX $LIBPROTOC_HEADERS
set_cmake_value $CMAKE_DIR/tests.cmake lite_test_protos "" $LITE_PROTOS
set_cmake_value $CMAKE_DIR/tests.cmake tests_protos "" $PROTOS_BLACKLISTED
set_cmake_value $CMAKE_DIR/tests.cmake common_test_files $CMAKE_PREFIX $COMMON_TEST_SOURCES
@@ -126,15 +128,15 @@ set_cmake_value $CMAKE_DIR/tests.cmake lite_arena_test_files $CMAKE_PREFIX $LITE
# Generate extract_includes.bat
echo "mkdir include" > $EXTRACT_INCLUDES_BAT
-for HEADER in $PUBLIC_HEADERS; do
- HEADER_DIR=$(dirname $HEADER)
- while [ ! "$HEADER_DIR" = "." ]; do
- echo $HEADER_DIR | sed "s/\\//\\\\/g"
- HEADER_DIR=$(dirname $HEADER_DIR)
+for INCLUDE in $PUBLIC_HEADERS $WKT_PROTOS; do
+ INCLUDE_DIR=$(dirname "$INCLUDE")
+ while [ ! "$INCLUDE_DIR" = "." ]; do
+ echo "mkdir include\\${INCLUDE_DIR//\//\\}"
+ INCLUDE_DIR=$(dirname "$INCLUDE_DIR")
done
-done | sort | uniq | sed "s/^/mkdir include\\\\/" >> $EXTRACT_INCLUDES_BAT
-for HEADER in $PUBLIC_HEADERS; do
- WINPATH=$(echo $HEADER | sed 's;/;\\;g')
+done | sort | uniq >> $EXTRACT_INCLUDES_BAT
+for INCLUDE in $PUBLIC_HEADERS $WKT_PROTOS; do
+ WINPATH=${INCLUDE//\//\\}
echo "copy \"\${PROTOBUF_SOURCE_WIN32_PATH}\\..\\src\\$WINPATH\" include\\$WINPATH" >> $EXTRACT_INCLUDES_BAT
done