aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore12
-rw-r--r--.gitmodules4
-rw-r--r--.travis.yml123
-rw-r--r--BUILD63
-rw-r--r--LICENSE12
-rw-r--r--Makefile.am111
-rw-r--r--README.md27
-rw-r--r--WORKSPACE13
-rw-r--r--appveyor.bat18
-rw-r--r--appveyor.yml35
-rwxr-xr-xautogen.sh18
-rw-r--r--benchmarks/Makefile.am550
-rw-r--r--benchmarks/ProtoBench.java203
-rw-r--r--benchmarks/README.md181
-rw-r--r--benchmarks/__init__.py0
-rw-r--r--benchmarks/benchmark_messages_proto2.proto143
-rw-r--r--benchmarks/cpp/cpp_benchmark.cc (renamed from benchmarks/cpp_benchmark.cc)40
-rw-r--r--benchmarks/datasets/google_message1/proto2/benchmark_message1_proto2.proto78
-rw-r--r--benchmarks/datasets/google_message1/proto2/dataset.google_message1_proto2.pb (renamed from benchmarks/google_message1.dat)bin228 -> 289 bytes
-rw-r--r--benchmarks/datasets/google_message1/proto3/benchmark_message1_proto3.proto (renamed from benchmarks/benchmark_messages_proto3.proto)0
-rw-r--r--benchmarks/datasets/google_message1/proto3/dataset.google_message1_proto3.pbbin0 -> 289 bytes
-rw-r--r--benchmarks/datasets/google_message2/benchmark_message2.proto76
-rw-r--r--benchmarks/datasets/google_message2/dataset.google_message2.pb (renamed from benchmarks/google_message2.dat)bin84570 -> 84625 bytes
-rw-r--r--benchmarks/datasets/google_message3/benchmark_message3.proto534
-rw-r--r--benchmarks/datasets/google_message3/benchmark_message3_1.proto1280
-rw-r--r--benchmarks/datasets/google_message3/benchmark_message3_2.proto499
-rw-r--r--benchmarks/datasets/google_message3/benchmark_message3_3.proto466
-rw-r--r--benchmarks/datasets/google_message3/benchmark_message3_4.proto491
-rw-r--r--benchmarks/datasets/google_message3/benchmark_message3_5.proto473
-rw-r--r--benchmarks/datasets/google_message3/benchmark_message3_6.proto454
-rw-r--r--benchmarks/datasets/google_message3/benchmark_message3_7.proto56
-rw-r--r--benchmarks/datasets/google_message3/benchmark_message3_8.proto1900
-rw-r--r--benchmarks/datasets/google_message4/benchmark_message4.proto454
-rw-r--r--benchmarks/datasets/google_message4/benchmark_message4_1.proto474
-rw-r--r--benchmarks/datasets/google_message4/benchmark_message4_2.proto292
-rw-r--r--benchmarks/datasets/google_message4/benchmark_message4_3.proto751
-rwxr-xr-xbenchmarks/download_data.sh5
-rw-r--r--benchmarks/generate_datasets.cc117
-rw-r--r--benchmarks/go/go_benchmark_test.go124
-rwxr-xr-xbenchmarks/java/pom.xml95
-rwxr-xr-xbenchmarks/java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java232
-rw-r--r--benchmarks/python/__init__.py0
-rwxr-xr-xbenchmarks/python/py_benchmark.py152
-rw-r--r--benchmarks/python/python_benchmark_messages.cc29
-rw-r--r--benchmarks/readme.txt46
-rw-r--r--benchmarks/util/__init__.py0
-rwxr-xr-xbenchmarks/util/big_query_utils.py188
-rw-r--r--benchmarks/util/gogo_data_scrubber.cc105
-rw-r--r--benchmarks/util/protoc-gen-gogoproto.cc103
-rwxr-xr-xbenchmarks/util/run_and_upload.py290
-rw-r--r--benchmarks/util/schema_proto2_to_proto3_util.h137
-rw-r--r--cmake/CMakeLists.txt41
-rw-r--r--cmake/README.md42
-rw-r--r--cmake/extract_includes.bat.in33
-rw-r--r--cmake/install.cmake32
-rw-r--r--cmake/libprotobuf-lite.cmake16
-rw-r--r--cmake/libprotobuf.cmake10
-rw-r--r--cmake/libprotoc.cmake60
-rw-r--r--cmake/protobuf-config.cmake.in22
-rw-r--r--cmake/protoc.cmake12
-rw-r--r--cmake/tests.cmake34
-rw-r--r--cmake/version.rc.in45
-rw-r--r--configure.ac19
-rw-r--r--conformance/conformance_cpp.cc1
-rw-r--r--conformance/conformance_test.cc24
-rw-r--r--conformance/conformance_test.h3
-rw-r--r--conformance/conformance_test_runner.cc7
-rw-r--r--conformance/failure_list_cpp.txt1
-rw-r--r--conformance/failure_list_java.txt2
-rw-r--r--conformance/failure_list_ruby.txt2
-rw-r--r--csharp/README.md12
-rw-r--r--csharp/build_packages.bat2
-rwxr-xr-xcsharp/buildall.sh2
-rw-r--r--csharp/global.json2
-rw-r--r--csharp/src/AddressBook/Addressbook.cs2
-rwxr-xr-x[-rw-r--r--]csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs83
-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--csharp/src/Google.Protobuf.Test/UnknownFieldSetTest.cs48
-rw-r--r--csharp/src/Google.Protobuf/CodedInputStream.cs11
-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--csharp/src/Google.Protobuf/Google.Protobuf.csproj6
-rw-r--r--csharp/src/Google.Protobuf/JsonParser.cs5
-rw-r--r--csharp/src/Google.Protobuf/MessageExtensions.cs102
-rw-r--r--csharp/src/Google.Protobuf/MessageParser.cs66
-rw-r--r--csharp/src/Google.Protobuf/Reflection/Descriptor.cs201
-rw-r--r--csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs24
-rw-r--r--csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs2
-rw-r--r--csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs180
-rw-r--r--csharp/src/Google.Protobuf/UnknownFieldSet.cs8
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Any.cs21
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Api.cs2
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs4
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs8
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Type.cs6
-rw-r--r--docs/performance.md304
-rw-r--r--docs/third_party.md8
-rw-r--r--examples/WORKSPACE2
-rw-r--r--examples/add_person_test.go4
-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/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/Android.java (renamed from javanano/src/test/java/com/google/protobuf/nano/unittest_simple_nano.proto)35
-rw-r--r--java/core/src/main/java/com/google/protobuf/BooleanArrayList.java16
-rw-r--r--java/core/src/main/java/com/google/protobuf/ByteString.java10
-rw-r--r--java/core/src/main/java/com/google/protobuf/CodedInputStream.java102
-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/FieldSet.java5
-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.java164
-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.java86
-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.java30
-rw-r--r--java/core/src/main/java/com/google/protobuf/Utf8.java478
-rw-r--r--java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java12
-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/DecodeUtf8Test.java325
-rw-r--r--java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java20
-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/IsValidUtf8TestUtil.java9
-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/TestUtil.java6
-rw-r--r--java/core/src/test/java/com/google/protobuf/TextFormatTest.java105
-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.xml7
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java2
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/JsonFormat.java57
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/Timestamps.java11
-rw-r--r--java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java15
-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_class_nano.proto48
-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_multiple_nano.proto63
-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--jenkins/README.md6
-rw-r--r--jenkins/buildcmds/README.md6
-rwxr-xr-xjenkins/buildcmds/pull_request_32.sh16
-rw-r--r--js/binary/arith.js2
-rw-r--r--js/binary/constants.js19
-rw-r--r--js/binary/decoder.js12
-rw-r--r--js/binary/encoder.js4
-rw-r--r--js/binary/reader.js50
-rw-r--r--js/binary/utils.js12
-rw-r--r--js/binary/utils_test.js2
-rw-r--r--js/binary/writer.js112
-rw-r--r--js/binary/writer_test.js12
-rw-r--r--js/commonjs/export_testdeps.js1
-rw-r--r--js/debug.js11
-rw-r--r--js/debug_test.js11
-rw-r--r--js/map.js16
-rw-r--r--js/message.js145
-rw-r--r--js/message_test.js23
-rw-r--r--kokoro/linux/32-bit/Dockerfile (renamed from jenkins/docker32/Dockerfile)0
-rwxr-xr-xkokoro/linux/32-bit/build.sh17
-rw-r--r--kokoro/linux/32-bit/continuous.cfg11
-rw-r--r--kokoro/linux/32-bit/presubmit.cfg11
-rw-r--r--kokoro/linux/64-bit/Dockerfile (renamed from jenkins/docker/Dockerfile)0
-rwxr-xr-xkokoro/linux/64-bit/build.sh (renamed from jenkins/buildcmds/pull_request.sh)13
-rw-r--r--kokoro/linux/64-bit/continuous.cfg11
-rw-r--r--kokoro/linux/64-bit/presubmit.cfg11
-rwxr-xr-xkokoro/linux/benchmark/build.sh88
-rwxr-xr-xkokoro/linux/benchmark/continuous.cfg11
-rwxr-xr-xkokoro/linux/build_and_run_docker.sh (renamed from jenkins/build_and_run_docker.sh)21
-rwxr-xr-xkokoro/linux/golang/build.sh17
-rw-r--r--kokoro/linux/golang/continuous.cfg11
-rw-r--r--kokoro/linux/golang/presubmit.cfg11
-rwxr-xr-xkokoro/linux/java_jdk7/build.sh17
-rw-r--r--kokoro/linux/java_jdk7/continuous.cfg11
-rw-r--r--kokoro/linux/java_jdk7/presubmit.cfg11
-rwxr-xr-xkokoro/linux/java_oracle7/build.sh17
-rw-r--r--kokoro/linux/java_oracle7/continuous.cfg11
-rw-r--r--kokoro/linux/java_oracle7/presubmit.cfg11
-rwxr-xr-xkokoro/linux/javascript/build.sh17
-rw-r--r--kokoro/linux/javascript/continuous.cfg11
-rw-r--r--kokoro/linux/javascript/presubmit.cfg11
-rw-r--r--kokoro/linux/make_test_output.py (renamed from jenkins/make_test_output.py)0
-rwxr-xr-xkokoro/linux/php_all/build.sh17
-rw-r--r--kokoro/linux/php_all/continuous.cfg11
-rw-r--r--kokoro/linux/php_all/presubmit.cfg11
-rw-r--r--kokoro/linux/prepare_build_linux_rc10
-rwxr-xr-xkokoro/linux/pull_request_in_docker.sh (renamed from jenkins/pull_request_in_docker.sh)11
-rwxr-xr-xkokoro/linux/python/build.sh17
-rw-r--r--kokoro/linux/python/continuous.cfg11
-rw-r--r--kokoro/linux/python/presubmit.cfg11
-rwxr-xr-xkokoro/linux/python_cpp/build.sh17
-rw-r--r--kokoro/linux/python_cpp/continuous.cfg11
-rw-r--r--kokoro/linux/python_cpp/presubmit.cfg11
-rwxr-xr-xkokoro/linux/ruby_all/build.sh17
-rw-r--r--kokoro/linux/ruby_all/continuous.cfg11
-rw-r--r--kokoro/linux/ruby_all/presubmit.cfg11
-rwxr-xr-xkokoro/macos/prepare_build_macos_rc2
-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.sh34
-rwxr-xr-xobjectivec/DevTools/pddm_tests.py6
-rw-r--r--objectivec/GPBCodedInputStream.m8
-rw-r--r--objectivec/GPBCodedInputStream_PackagePrivate.h2
-rw-r--r--objectivec/GPBCodedOutputStream.m7
-rw-r--r--objectivec/GPBDescriptor.m6
-rw-r--r--objectivec/GPBDictionary.h2800
-rw-r--r--objectivec/GPBDictionary.m1953
-rw-r--r--objectivec/GPBMessage.m83
-rw-r--r--objectivec/GPBMessage_PackagePrivate.h18
-rw-r--r--objectivec/GPBProtocolBuffers_RuntimeSupport.h2
-rw-r--r--objectivec/GPBRootObject.m8
-rw-r--r--objectivec/GPBUtilities.m337
-rw-r--r--objectivec/GPBUtilities_PackagePrivate.h7
-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.pbxproj258
-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.md10
-rw-r--r--objectivec/Tests/GPBCodedInputStreamTests.m4
-rw-r--r--objectivec/Tests/GPBCodedOuputStreamTests.m12
-rw-r--r--objectivec/Tests/GPBCompileTest01.m (renamed from src/google/protobuf/unittest_import_public_proto3.proto)14
-rw-r--r--objectivec/Tests/GPBCompileTest02.m40
-rw-r--r--objectivec/Tests/GPBCompileTest03.m40
-rw-r--r--objectivec/Tests/GPBCompileTest04.m (renamed from javanano/src/test/java/com/google/protobuf/nano/unittest_single_nano.proto)12
-rw-r--r--objectivec/Tests/GPBCompileTest05.m (renamed from javanano/src/test/java/com/google/protobuf/nano/unittest_stringutf8_nano.proto)17
-rw-r--r--objectivec/Tests/GPBCompileTest06.m40
-rw-r--r--objectivec/Tests/GPBCompileTest07.m (renamed from javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nameclash_nano.proto)15
-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_enum_class_multiple_nano.proto)22
-rw-r--r--objectivec/Tests/GPBCompileTest25.m (renamed from javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_merge_nano.proto)21
-rw-r--r--objectivec/Tests/GPBDictionaryTests+Bool.m80
-rw-r--r--objectivec/Tests/GPBDictionaryTests+Int32.m105
-rw-r--r--objectivec/Tests/GPBDictionaryTests+Int64.m105
-rw-r--r--objectivec/Tests/GPBDictionaryTests+String.m95
-rw-r--r--objectivec/Tests/GPBDictionaryTests+UInt32.m105
-rw-r--r--objectivec/Tests/GPBDictionaryTests+UInt64.m105
-rw-r--r--objectivec/Tests/GPBDictionaryTests.pddm35
-rw-r--r--objectivec/Tests/GPBMessageTests+Serialization.m8
-rw-r--r--objectivec/Tests/GPBMessageTests.m57
-rw-r--r--objectivec/Tests/GPBUtilitiesTests.m8
-rw-r--r--objectivec/Tests/iOSTestHarness/AppDelegate.m35
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/Contents.json116
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6.pngbin8583 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6_2x.pngbin17744 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7.pngbin8969 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7_2x.pngbin18788 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6.pngbin7021 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6_2x.pngbin13348 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_2x.pngbin11128 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_3x.pngbin21792 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/LaunchImage.launchimage/Contents.json49
-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/Tests/unittest_objc.proto21
-rw-r--r--objectivec/google/protobuf/Any.pbobjc.h29
-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/Struct.pbobjc.m7
-rw-r--r--objectivec/google/protobuf/Timestamp.pbobjc.h16
-rw-r--r--objectivec/google/protobuf/Type.pbobjc.h8
-rw-r--r--objectivec/google/protobuf/Type.pbobjc.m17
-rw-r--r--objectivec/google/protobuf/Wrappers.pbobjc.h8
-rw-r--r--php/README.md2
-rw-r--r--php/ext/google/protobuf/message.c10
-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.php2
-rw-r--r--php/src/Google/Protobuf/Internal/FileOptions.php90
-rw-r--r--php/src/Google/Protobuf/Internal/GPBUtil.php2
-rw-r--r--php/src/Google/Protobuf/Internal/Message.php4
-rw-r--r--php/src/Google/Protobuf/Timestamp.php10
-rw-r--r--php/tests/proto/test_empty_php_namespace.proto1
-rw-r--r--php/tests/proto/test_no_namespace.proto2
-rw-r--r--php/tests/proto/test_php_namespace.proto1
-rwxr-xr-xphp/tests/test.sh2
-rw-r--r--protobuf.bzl29
-rw-r--r--protoc-artifacts/Dockerfile22
-rw-r--r--protoc-artifacts/README.md13
-rwxr-xr-xprotoc-artifacts/build-protoc.sh6
-rwxr-xr-xprotoc-artifacts/build-zip.sh4
-rw-r--r--protoc-artifacts/pom.xml2
-rwxr-xr-xprotoc-artifacts/scl-enable-devtoolset.sh13
-rw-r--r--python/MANIFEST.in3
-rw-r--r--python/google/protobuf/compiler/__init__.py0
-rwxr-xr-xpython/google/protobuf/descriptor.py113
-rw-r--r--python/google/protobuf/descriptor_database.py26
-rw-r--r--python/google/protobuf/descriptor_pool.py32
-rwxr-xr-xpython/google/protobuf/internal/_parameterized.py50
-rwxr-xr-xpython/google/protobuf/internal/api_implementation.py11
-rwxr-xr-xpython/google/protobuf/internal/containers.py4
-rw-r--r--python/google/protobuf/internal/descriptor_database_test.py21
-rw-r--r--python/google/protobuf/internal/descriptor_pool_test.py56
-rwxr-xr-xpython/google/protobuf/internal/descriptor_test.py13
-rwxr-xr-xpython/google/protobuf/internal/encoder.py19
-rw-r--r--python/google/protobuf/internal/json_format_test.py12
-rwxr-xr-xpython/google/protobuf/internal/message_test.py45
-rw-r--r--python/google/protobuf/internal/no_package.proto10
-rwxr-xr-xpython/google/protobuf/internal/text_format_test.py100
-rw-r--r--python/google/protobuf/internal/well_known_types.py10
-rw-r--r--python/google/protobuf/internal/well_known_types_test.py18
-rw-r--r--python/google/protobuf/json_format.py33
-rw-r--r--python/google/protobuf/pyext/descriptor.cc93
-rw-r--r--python/google/protobuf/pyext/descriptor_containers.cc530
-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.cc115
-rw-r--r--python/google/protobuf/pyext/message.h43
-rw-r--r--python/google/protobuf/pyext/message_factory.cc8
-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.py90
-rw-r--r--python/google/protobuf/util/__init__.py0
-rwxr-xr-xpython/setup.py17
-rw-r--r--ruby/README.md4
-rw-r--r--ruby/Rakefile6
-rw-r--r--ruby/ext/google/protobuf_c/message.c4
-rw-r--r--ruby/ext/google/protobuf_c/storage.c16
-rw-r--r--ruby/lib/google/protobuf/repeated_field.rb4
-rw-r--r--ruby/tests/repeated_field_test.rb15
-rw-r--r--src/Makefile.am120
-rw-r--r--src/README.md146
-rw-r--r--src/google/protobuf/any.cc11
-rw-r--r--src/google/protobuf/any.h11
-rw-r--r--src/google/protobuf/any.pb.cc73
-rw-r--r--src/google/protobuf/any.pb.h56
-rw-r--r--src/google/protobuf/any.proto21
-rw-r--r--src/google/protobuf/api.pb.cc239
-rw-r--r--src/google/protobuf/api.pb.h223
-rwxr-xr-xsrc/google/protobuf/arena.cc392
-rw-r--r--src/google/protobuf/arena.h639
-rw-r--r--src/google/protobuf/arena_impl.h177
-rw-r--r--src/google/protobuf/arena_test_util.h2
-rw-r--r--src/google/protobuf/arena_unittest.cc84
-rwxr-xr-xsrc/google/protobuf/arenastring.h79
-rw-r--r--src/google/protobuf/arenastring_unittest.cc3
-rw-r--r--src/google/protobuf/compiler/annotation_test_util.cc29
-rw-r--r--src/google/protobuf/compiler/annotation_test_util.h17
-rw-r--r--src/google/protobuf/compiler/code_generator.cc2
-rw-r--r--src/google/protobuf/compiler/code_generator.h2
-rw-r--r--src/google/protobuf/compiler/command_line_interface.cc51
-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.cc45
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_field.h49
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_file.cc354
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_file.h11
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_generator.cc66
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_helpers.cc83
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_helpers.h56
-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.cc1174
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message.h19
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message_field.cc701
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message_field.h26
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_move_unittest.cc2
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_options.h4
-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_primitive_field.cc8
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_string_field.cc281
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_string_field.h7
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_unittest.cc2242
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_unittest.inc2281
-rw-r--r--src/google/protobuf/compiler/cpp/metadata_test.cc7
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_doc_comment.cc2
-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.cc6
-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.cc12
-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.cc13
-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_map_field_lite.cc26
-rw-r--r--src/google/protobuf/compiler/java/java_message.cc56
-rw-r--r--src/google/protobuf/compiler/java/java_message_builder.cc26
-rw-r--r--src/google/protobuf/compiler/java/java_message_builder_lite.cc8
-rw-r--r--src/google/protobuf/compiler/java/java_message_field_lite.cc23
-rw-r--r--src/google/protobuf/compiler/java/java_message_lite.cc145
-rw-r--r--src/google/protobuf/compiler/java/java_plugin_unittest.cc5
-rw-r--r--src/google/protobuf/compiler/java/java_primitive_field.cc3
-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_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.cc2
-rwxr-xr-xsrc/google/protobuf/compiler/js/js_generator.cc78
-rw-r--r--src/google/protobuf/compiler/main.cc6
-rw-r--r--src/google/protobuf/compiler/mock_code_generator.cc16
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_enum.cc5
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_enum.h4
-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.cc127
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_file.h9
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_generator.cc8
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_generator.h2
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_helpers.cc41
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_helpers.h18
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_map_field.h2
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_message.cc48
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_message.h8
-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.cc66
-rw-r--r--src/google/protobuf/compiler/php/php_generator.h9
-rw-r--r--src/google/protobuf/compiler/plugin.cc2
-rw-r--r--src/google/protobuf/compiler/plugin.pb.cc273
-rw-r--r--src/google/protobuf/compiler/plugin.pb.h253
-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.cc4
-rw-r--r--src/google/protobuf/descriptor.cc412
-rw-r--r--src/google/protobuf/descriptor.h9
-rw-r--r--src/google/protobuf/descriptor.pb.cc2187
-rw-r--r--src/google/protobuf/descriptor.pb.h2313
-rw-r--r--src/google/protobuf/descriptor.proto11
-rw-r--r--src/google/protobuf/descriptor_database.h2
-rw-r--r--src/google/protobuf/descriptor_database_unittest.cc9
-rw-r--r--src/google/protobuf/descriptor_unittest.cc561
-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.h58
-rw-r--r--src/google/protobuf/dynamic_message.cc91
-rw-r--r--src/google/protobuf/dynamic_message.h5
-rw-r--r--src/google/protobuf/dynamic_message_unittest.cc77
-rw-r--r--src/google/protobuf/empty.pb.cc62
-rw-r--r--src/google/protobuf/empty.pb.h58
-rw-r--r--src/google/protobuf/extension_set.cc531
-rw-r--r--src/google/protobuf/extension_set.h139
-rw-r--r--src/google/protobuf/extension_set_heavy.cc148
-rw-r--r--src/google/protobuf/extension_set_unittest.cc50
-rw-r--r--src/google/protobuf/field_mask.pb.cc66
-rw-r--r--src/google/protobuf/field_mask.pb.h54
-rw-r--r--src/google/protobuf/field_mask.proto4
-rw-r--r--src/google/protobuf/generated_enum_reflection.h1
-rw-r--r--src/google/protobuf/generated_enum_util.h4
-rw-r--r--src/google/protobuf/generated_message_reflection.cc79
-rw-r--r--src/google/protobuf/generated_message_reflection.h53
-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.h248
-rw-r--r--src/google/protobuf/generated_message_util.cc91
-rw-r--r--src/google/protobuf/generated_message_util.h88
-rw-r--r--src/google/protobuf/implicit_weak_message.cc18
-rw-r--r--src/google/protobuf/implicit_weak_message.h52
-rw-r--r--src/google/protobuf/inlined_string_field.h271
-rw-r--r--src/google/protobuf/io/coded_stream.cc37
-rw-r--r--src/google/protobuf/io/coded_stream.h84
-rw-r--r--src/google/protobuf/io/coded_stream_unittest.cc5
-rw-r--r--src/google/protobuf/io/printer.cc10
-rw-r--r--src/google/protobuf/io/zero_copy_stream_impl_lite.h7
-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.h8
-rw-r--r--src/google/protobuf/map_entry_lite.h19
-rw-r--r--src/google/protobuf/map_field.cc52
-rw-r--r--src/google/protobuf/map_field.h17
-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.cc50
-rw-r--r--src/google/protobuf/map_unittest_proto3.proto120
-rw-r--r--src/google/protobuf/message.cc4
-rw-r--r--src/google/protobuf/message.h16
-rw-r--r--src/google/protobuf/message_lite.h40
-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
-rwxr-xr-xsrc/google/protobuf/reflection.h25
-rw-r--r--src/google/protobuf/reflection_ops.cc29
-rw-r--r--src/google/protobuf/repeated_field.cc16
-rw-r--r--src/google/protobuf/repeated_field.h337
-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.cc67
-rw-r--r--src/google/protobuf/source_context.pb.h54
-rw-r--r--src/google/protobuf/struct.pb.cc159
-rw-r--r--src/google/protobuf/struct.pb.h191
-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.h155
-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/callback.h15
-rw-r--r--src/google/protobuf/stubs/casts.h5
-rwxr-xr-xsrc/google/protobuf/stubs/common.cc86
-rw-r--r--src/google/protobuf/stubs/common.h7
-rw-r--r--src/google/protobuf/stubs/common_unittest.cc2
-rw-r--r--src/google/protobuf/stubs/hash.h13
-rw-r--r--src/google/protobuf/stubs/int128.cc52
-rw-r--r--src/google/protobuf/stubs/io_win32.cc17
-rw-r--r--src/google/protobuf/stubs/io_win32_unittest.cc7
-rw-r--r--src/google/protobuf/stubs/map_util.h7
-rw-r--r--src/google/protobuf/stubs/mathlimits.h2
-rw-r--r--src/google/protobuf/stubs/mutex.h38
-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/port.h69
-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/status.cc2
-rw-r--r--src/google/protobuf/stubs/status.h2
-rw-r--r--src/google/protobuf/stubs/stringprintf.cc2
-rw-r--r--src/google/protobuf/stubs/stringprintf.h2
-rw-r--r--src/google/protobuf/stubs/structurally_valid.cc31
-rw-r--r--src/google/protobuf/stubs/structurally_valid_unittest.cc30
-rw-r--r--src/google/protobuf/stubs/strutil.cc22
-rw-r--r--src/google/protobuf/stubs/strutil.h20
-rw-r--r--src/google/protobuf/stubs/strutil_unittest.cc2
-rw-r--r--src/google/protobuf/stubs/time.cc4
-rw-r--r--src/google/protobuf/stubs/time_test.cc53
-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/testing/googletest.cc2
-rw-r--r--src/google/protobuf/testing/googletest.h4
-rw-r--r--src/google/protobuf/text_format.cc184
-rw-r--r--src/google/protobuf/text_format.h92
-rw-r--r--src/google/protobuf/text_format_unittest.cc226
-rw-r--r--src/google/protobuf/timestamp.pb.cc62
-rw-r--r--src/google/protobuf/timestamp.pb.h58
-rw-r--r--src/google/protobuf/timestamp.proto8
-rw-r--r--src/google/protobuf/type.pb.cc377
-rw-r--r--src/google/protobuf/type.pb.h390
-rw-r--r--src/google/protobuf/unittest.proto61
-rw-r--r--src/google/protobuf/unittest_import_proto3.proto68
-rw-r--r--src/google/protobuf/unittest_lite.proto19
-rw-r--r--src/google/protobuf/unittest_lite_imports_nonlite.proto3
-rw-r--r--src/google/protobuf/unknown_field_set_unittest.cc1
-rw-r--r--src/google/protobuf/util/delimited_message_util.cc2
-rw-r--r--src/google/protobuf/util/delimited_message_util.h2
-rw-r--r--src/google/protobuf/util/field_comparator.cc10
-rw-r--r--src/google/protobuf/util/field_comparator.h11
-rw-r--r--src/google/protobuf/util/field_mask_util.cc27
-rw-r--r--src/google/protobuf/util/field_mask_util.h13
-rw-r--r--src/google/protobuf/util/field_mask_util_test.cc19
-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.h29
-rw-r--r--src/google/protobuf/util/internal/default_value_objectwriter_test.cc4
-rw-r--r--src/google/protobuf/util/internal/error_listener.h3
-rw-r--r--src/google/protobuf/util/internal/field_mask_utility.cc3
-rw-r--r--src/google/protobuf/util/internal/json_escaping.h8
-rw-r--r--src/google/protobuf/util/internal/json_objectwriter.cc13
-rw-r--r--src/google/protobuf/util/internal/json_objectwriter.h47
-rw-r--r--src/google/protobuf/util/internal/json_objectwriter_test.cc8
-rw-r--r--src/google/protobuf/util/internal/json_stream_parser.cc5
-rw-r--r--src/google/protobuf/util/internal/object_writer.h7
-rw-r--r--src/google/protobuf/util/internal/proto_writer.cc70
-rw-r--r--src/google/protobuf/util/internal/proto_writer.h46
-rw-r--r--src/google/protobuf/util/internal/protostream_objectsource.cc71
-rw-r--r--src/google/protobuf/util/internal/protostream_objectsource_test.cc27
-rw-r--r--src/google/protobuf/util/internal/protostream_objectwriter.cc78
-rw-r--r--src/google/protobuf/util/internal/protostream_objectwriter.h8
-rw-r--r--src/google/protobuf/util/internal/protostream_objectwriter_test.cc8
-rw-r--r--src/google/protobuf/util/internal/structured_objectwriter.h9
-rw-r--r--src/google/protobuf/util/internal/testdata/books.proto1
-rw-r--r--src/google/protobuf/util/internal/type_info.cc4
-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.cc53
-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.cc14
-rw-r--r--src/google/protobuf/util/json_util.h8
-rw-r--r--src/google/protobuf/util/json_util_test.cc108
-rw-r--r--src/google/protobuf/util/message_differencer.cc41
-rw-r--r--src/google/protobuf/util/message_differencer.h24
-rwxr-xr-xsrc/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.cc8
-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_lite.cc189
-rw-r--r--src/google/protobuf/wire_format_lite.h57
-rw-r--r--src/google/protobuf/wire_format_lite_inl.h113
-rw-r--r--src/google/protobuf/wire_format_unittest.cc1
-rw-r--r--src/google/protobuf/wrappers.pb.cc420
-rw-r--r--src/google/protobuf/wrappers.pb.h410
-rwxr-xr-xtests.sh21
m---------third_party/benchmark0
m---------third_party/googletest0
-rwxr-xr-xupdate_file_lists.sh22
728 files changed, 40253 insertions, 47548 deletions
diff --git a/.gitignore b/.gitignore
index af88e226..abd72fc9 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
@@ -58,8 +58,6 @@ python/*.egg
python/.eggs/
python/.tox
python/build/
-python/google/protobuf/compiler/
-python/google/protobuf/util/
src/js_embed
src/protoc
@@ -180,3 +178,11 @@ 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 e7853ebe..74d4ea7b 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,55 +1,57 @@
-sudo: required
-dist: trusty
-# Note: travis currently does not support listing more than one language so
-# this cheats and claims to only be cpp. If they add multiple language
-# support, this should probably get updated to install steps and/or
-# rvm/gemfile/jdk/etc. entries rather than manually doing the work.
+# Everything is driven by the test.sh, so the language doesn't really
+# matter, it just controls the default install/script/etc. steps on
+# travis.
language: cpp
-os:
- - osx
-# The Objective C build needs Xcode 7.0 or later.
-osx_image: xcode8.3
-script:
- - ./tests.sh $CONFIG
-env:
- - CONFIG=cpp
- - CONFIG=cpp_distcheck
- - CONFIG=golang
- - CONFIG=java_jdk7
- - CONFIG=java_oracle7
- - CONFIG=javanano_jdk7
- - CONFIG=javanano_oracle7
- - CONFIG=javascript
- # iOS build log was starting to choke travis UI, so split to cover the
- # Xcode Debug and Release Configurations independently.
- - CONFIG=objectivec_ios_debug
- - CONFIG=objectivec_ios_release
- - CONFIG=objectivec_osx
- - CONFIG=objectivec_cocoapods_integration
- - CONFIG=python
- - CONFIG=python_cpp
- - CONFIG=ruby21
- - CONFIG=ruby22
- - CONFIG=jruby
- - CONFIG=php5.6_mac
- - CONFIG=php7.0_mac
+script: ./tests.sh $CONFIG
+
+# The test matrix is manually built to cover a mix of linux and macOS
+# hosted setups; this lets some extra settings be done specific to each
+# host/language instead of forcing common values on all the tests.
matrix:
- exclude:
- # It's nontrivial to programmatically install a new JDK from the command
- # line on OS X, so we rely on testing on Linux for Java code.
+ include:
+ # -----------------------------------------------------------------
+ # macOS hosted tests for Objective-C
+
+ - os: osx
+ env: CONFIG=objectivec_osx
+ osx_image: xcode9.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=java_jdk7
+ env: CONFIG=objectivec_ios_debug
+ osx_image: xcode9.3
+ language: objective-c
- os: osx
- env: CONFIG=java_oracle7
+ env: CONFIG=objectivec_ios_release
+ osx_image: xcode9.3
+ language: objective-c
- os: osx
- env: CONFIG=javanano_jdk7
+ env: CONFIG=objectivec_cocoapods_integration
+ osx_image: xcode9.3
+ language: objective-c
+
+ # -----------------------------------------------------------------
+ # macOS hosted tests for other languages.
+
- os: osx
- env: CONFIG=javanano_oracle7
- # Requires installing golang, currently travis.sh is doing that with apt-get
- # which doesn't work on OS X.
+ env: CONFIG=cpp
- os: osx
- env: CONFIG=golang
- include:
+ env: CONFIG=cpp_distcheck
+ - os: osx
+ env: CONFIG=javascript
+ - os: osx
+ env: CONFIG=python
+ - os: osx
+ env: CONFIG=python_cpp
+ - os: osx
+ env: CONFIG=php5.6_mac
+ - os: osx
+ env: CONFIG=php7.0_mac
+
+ # -----------------------------------------------------------------
+ # Linux hosted tests
+
# The dotnet environment requires Ubuntu 14.04 or 16.04. This
# configuration is effectively an "extra" one, outside the
# autogenerated matrix.
@@ -57,8 +59,16 @@ matrix:
env: CONFIG=csharp
language: csharp
dist: trusty
- dotnet: 1.0.1
+ dotnet: 2.0.3
mono: none
+ # Install the .NET Core 1.0 runtime as that's what we test against
+ addons:
+ apt:
+ sources:
+ - sourceline: 'deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-trusty-prod trusty main'
+ key_url: 'https://packages.microsoft.com/keys/microsoft.asc'
+ packages:
+ - dotnet-sharedframework-microsoft.netcore.app-1.0.5
# This test is kept on travis because it doesn't play nicely with other
# tests on jenkins running in parallel.
- os: linux
@@ -67,25 +77,14 @@ matrix:
# fetch pre-built Linux protoc binaries in the test.
- os: linux
env: CONFIG=java_compatibility
+ sudo: required
+ dist: trusty
# The Python compatibility test currently only runs on Linux because it will
# fetch pre-built Linux protoc binaries in the test.
- os: linux
env: CONFIG=python_compatibility
- allow_failures:
- # These currently do not work on OS X but are being worked on by @haberman.
- - os: osx
- env: CONFIG=ruby22
- - os: osx
- env: CONFIG=jruby
- # https://github.com/google/protobuf/issues/1253 - Started failing when
- # we moved to an OS X image that is 10.11.
- - os: osx
- env: CONFIG=python_cpp
- # Mark the iOS test as flakey as xcodebuild some times fails to start the
- # iOS Simulator.
- - os: osx
- env: CONFIG=objectivec_ios_debug
- - os: osx
- env: CONFIG=objectivec_ios_release
+ sudo: required
+ dist: trusty
+
notifications:
email: false
diff --git a/BUILD b/BUILD
index bcaf9cd5..d6fb85d8 100644
--- a/BUILD
+++ b/BUILD
@@ -5,18 +5,28 @@ licenses(["notice"])
exports_files(["LICENSE"])
################################################################################
+# Java 9 configuration
+################################################################################
+
+config_setting(
+ name = "jdk9",
+ values = {
+ "java_toolchain": "@bazel_tools//tools/jdk:toolchain_jdk9",
+ },
+)
+
+################################################################################
# Protobuf Runtime Library
################################################################################
-WIN_COPTS = [
+MSVC_COPTS = [
"/DHAVE_PTHREAD",
"/wd4018", # -Wno-sign-compare
"/wd4514", # -Wno-unused-function
]
COPTS = select({
- ":windows" : WIN_COPTS,
- ":windows_msvc" : WIN_COPTS,
+ ":msvc" : MSVC_COPTS,
"//conditions:default": [
"-DHAVE_PTHREAD",
"-Wall",
@@ -24,17 +34,14 @@ COPTS = select({
"-Woverloaded-virtual",
"-Wno-sign-compare",
"-Wno-unused-function",
+ # Prevents ISO C++ const string assignment warnings for pyext sources.
+ "-Wno-writable-strings",
],
})
config_setting(
- name = "windows",
- values = { "cpu": "x64_windows" },
-)
-
-config_setting(
- name = "windows_msvc",
- values = { "cpu": "x64_windows_msvc" },
+ name = "msvc",
+ values = { "compiler": "msvc-cl" },
)
config_setting(
@@ -44,11 +51,10 @@ 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": [],
"//conditions:default": ["-lpthread", "-lm"],
})
@@ -70,18 +76,16 @@ cc_library(
"src/google/protobuf/extension_set.cc",
"src/google/protobuf/generated_message_table_driven_lite.cc",
"src/google/protobuf/generated_message_util.cc",
+ "src/google/protobuf/implicit_weak_message.cc",
"src/google/protobuf/io/coded_stream.cc",
"src/google/protobuf/io/zero_copy_stream.cc",
"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",
@@ -239,7 +243,7 @@ internal_copied_filegroup(
srcs = WELL_KNOWN_PROTOS,
dest = "",
strip_prefix = "src",
- visibility = ["//visibility:hidden"],
+ visibility = ["//visibility:private"],
)
[proto_library(
@@ -337,17 +341,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",
@@ -464,6 +457,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",
]
@@ -506,6 +500,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",
@@ -530,6 +525,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",
@@ -542,7 +538,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",
@@ -551,7 +546,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",
@@ -605,7 +599,10 @@ java_library(
]) + [
":gen_well_known_protos_java",
],
- javacopts = ["-source 6", "-target 6"],
+ javacopts = select({
+ "//:jdk9": ["--add-modules=jdk.unsupported"],
+ "//conditions:default": ["-source 7", "-target 7"],
+ }),
visibility = ["//visibility:public"],
)
@@ -614,7 +611,7 @@ java_library(
srcs = glob([
"java/util/src/main/java/com/google/protobuf/util/*.java",
]),
- javacopts = ["-source 6", "-target 6"],
+ javacopts = ["-source 7", "-target 7"],
visibility = ["//visibility:public"],
deps = [
"protobuf_java",
@@ -732,6 +729,7 @@ py_proto_library(
":python_srcs",
"//external:six",
],
+ py_extra_srcs = glob(["python/**/__init__.py"]),
srcs_version = "PY2AND3",
visibility = ["//visibility:public"],
)
@@ -825,6 +823,7 @@ proto_lang_toolchain(
command_line = "--cpp_out=$(OUT)",
runtime = ":protobuf",
visibility = ["//visibility:public"],
+ blacklisted_protos = [":_internal_wkt_protos_genrule"],
)
proto_lang_toolchain(
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 19a16071..2ad619a7 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"; \
@@ -98,7 +98,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 +132,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 \
@@ -211,6 +211,7 @@ java_EXTRA_DIST=
java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java \
java/core/src/main/java/com/google/protobuf/AbstractParser.java \
java/core/src/main/java/com/google/protobuf/AbstractProtobufList.java \
+ java/core/src/main/java/com/google/protobuf/Android.java \
java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java \
java/core/src/main/java/com/google/protobuf/BlockingService.java \
java/core/src/main/java/com/google/protobuf/BooleanArrayList.java \
@@ -293,6 +294,7 @@ java_EXTRA_DIST=
java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java \
java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java \
java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java \
+ java/core/src/test/java/com/google/protobuf/DecodeUtf8Test.java \
java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java \
java/core/src/test/java/com/google/protobuf/DescriptorsTest.java \
java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java \
@@ -352,6 +354,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 \
@@ -367,9 +370,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 \
@@ -384,45 +385,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 \
@@ -495,11 +457,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 \
@@ -537,6 +501,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 \
@@ -563,20 +552,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/Contents.json \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6_2x.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7_2x.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6_2x.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_2x.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_3x.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/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 \
@@ -767,6 +742,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 \
@@ -801,6 +777,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 \
@@ -854,12 +831,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 \
@@ -1026,7 +1005,7 @@ js_EXTRA_DIST= \
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 \
@@ -1037,7 +1016,6 @@ EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \
CHANGES.txt \
update_file_lists.sh \
BUILD \
- gmock.BUILD \
WORKSPACE \
cmake/CMakeLists.txt \
cmake/README.md \
@@ -1055,6 +1033,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/README.md b/README.md
index 3a4e6ed2..1a45ee60 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)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-jruby.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fjruby%2Fcontinuous) | |
+| 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..06a8a841 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -1,10 +1,9 @@
workspace(name = "com_google_protobuf")
-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(
@@ -21,12 +20,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..1dd076a4 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -1,19 +1,23 @@
-# 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: csharp
image: Visual Studio 2017
# Our build scripts run tests automatically; we don't want AppVeyor
@@ -21,19 +25,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 d98eae5e..564fdab3 100644
--- a/benchmarks/Makefile.am
+++ b/benchmarks/Makefile.am
@@ -1,78 +1,518 @@
+benchmarks_protoc_inputs_benchmark_wrapper = \
+ benchmarks.proto
-benchmarks_protoc_inputs = \
- benchmarks.proto \
- benchmark_messages_proto3.proto
+benchmarks_protoc_inputs = \
+ datasets/google_message1/proto3/benchmark_message1_proto3.proto
-benchmarks_protoc_inputs_proto2 = \
- benchmark_messages_proto2.proto
+benchmarks_protoc_inputs_proto2 = \
+ 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 \
+ 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 \
+ 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
-benchmarks_protoc_outputs = \
- benchmarks.pb.cc \
- benchmarks.pb.h \
- benchmark_messages_proto3.pb.cc \
- benchmark_messages_proto3.pb.h
+make_tmp_dir:
+ mkdir -p 'tmp/java/src/main/java'
+ touch make_tmp_dir
-benchmarks_protoc_outputs_proto2 = \
- benchmark_messages_proto2.pb.cc \
- benchmark_messages_proto2.pb.h
+# 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) $(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/cpp --java_out=$$oldpwd/tmp/java/src/main/java --python_out=$$oldpwd/tmp $(benchmarks_protoc_inputs_proto2) )
+ touch protoc_middleman2
+
+all_data = $$(find $(srcdir) -type f -name "dataset.*.pb" -not -path "./tmp/*")
+
+############# CPP RULES ##############
+
+benchmarks_protoc_outputs = \
+ cpp/benchmarks.pb.cc \
+ cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.cc
+
+benchmarks_protoc_outputs_header = \
+ cpp/benchmarks.pb.h \
+ cpp/datasets/google_message1/proto3/benchmark_message1_proto3.pb.h
+
+benchmarks_protoc_outputs_proto2_header = \
+ 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 = \
+ 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
+$(benchmarks_protoc_outputs_header): protoc_middleman
+$(benchmarks_protoc_outputs_proto2): protoc_middleman2
+$(benchmarks_protoc_outputs_proto2_header): protoc_middleman2
+
+initialize_submodule:
+ oldpwd=`pwd`
+ cd $(top_srcdir)/third_party
+ git submodule update --init -r
+ cd $(top_srcdir)/third_party/benchmark && cmake -DCMAKE_BUILD_TYPE=Release && make
+ cd $$oldpwd
+ touch 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
-bin_PROGRAMS = generate-datasets cpp-benchmark
+bin_PROGRAMS = cpp-benchmark
+
+cpp_benchmark_LDADD = $(top_srcdir)/src/libprotobuf.la $(top_srcdir)/third_party/benchmark/src/libbenchmark.a
+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/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) \
+ $(benchmarks_protoc_outputs_proto2_header) \
+ $(benchmarks_protoc_outputs_header)
+
+cpp: protoc_middleman protoc_middleman2 cpp-benchmark initialize_submodule
+ ./cpp-benchmark $(all_data)
+
+############ CPP RULES END ############
+
+############# JAVA RULES ##############
+
+java_benchmark_testing_files = \
+ java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java
+
+javac_middleman: $(java_benchmark_testing_files) protoc_middleman protoc_middleman2
+ cp -r $(srcdir)/java tmp && cd tmp/java && mvn clean compile assembly:single
+ cd ../..
+ @touch javac_middleman
+
+java-benchmark: javac_middleman
+ @echo "Writing shortcut script 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/*.jar"' com.google.caliper.runner.CaliperMain com.google.protobuf.ProtoCaliperBenchmark -i runtime '"\\" >> java-benchmark
+ @echo '-b serializeToByteString,serializeToByteArray,serializeToMemoryStream,'"\\" >> java-benchmark
+ @echo 'deserializeFromByteString,deserializeFromByteArray,deserializeFromMemoryStream '"\\" >> java-benchmark
+ @echo '-DdataFile=$${data_files:0:-1} $${conf[*]}' >> java-benchmark
+ @chmod +x java-benchmark
+
+java: protoc_middleman protoc_middleman2 java-benchmark
+ ./java-benchmark $(all_data)
+
+############# JAVA RULES END ##############
+
+
+############# PYTHON RULES ##############
+
+python_add_init: protoc_middleman protoc_middleman2
+ all_file=`find tmp -type f -regex '.*\.py'` && \
+ for file in $${all_file[@]}; do \
+ path="$${file%/*}"; \
+ while true; do \
+ touch "$$path/__init__.py" && chmod +x "$$path/__init__.py"; \
+ if [[ $$path != *"/"* ]]; then break; fi; \
+ path=$${path%/*}; \
+ done \
+ done
+
+python_cpp_pkg_flags = `pkg-config --cflags --libs python`
+
+lib_LTLIBRARIES = libbenchmark_messages.la
+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)/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) \
+ $(benchmarks_protoc_outputs_proto2_header) \
+ $(benchmarks_protoc_outputs_header)
+
+python-pure-python-benchmark: python_add_init
+ @echo "Writing shortcut script python-pure-python-benchmark..."
+ @echo '#! /bin/bash' > python-pure-python-benchmark
+ @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-pure-python-benchmark
+ @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-pure-python-benchmark
+ @echo export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=\'python\' >> python-pure-python-benchmark
+ @echo cp $(srcdir)/python/py_benchmark.py tmp >> python-pure-python-benchmark
+ @echo python tmp/py_benchmark.py '$$@' >> python-pure-python-benchmark
+ @chmod +x python-pure-python-benchmark
+
+python-cpp-reflection-benchmark: python_add_init
+ @echo "Writing shortcut script python-cpp-reflection-benchmark..."
+ @echo '#! /bin/bash' > python-cpp-reflection-benchmark
+ @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-reflection-benchmark
+ @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-reflection-benchmark
+ @echo export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=\'cpp\' >> python-cpp-reflection-benchmark
+ @echo cp $(srcdir)/python/py_benchmark.py tmp >> python-cpp-reflection-benchmark
+ @echo python tmp/py_benchmark.py '$$@' >> python-cpp-reflection-benchmark
+ @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/bash' > python-cpp-generated-code-benchmark
+ @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-generated-code-benchmark
+ @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-generated-code-benchmark
+ @echo export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=\'cpp\' >> python-cpp-generated-code-benchmark
+ @echo cp $(srcdir)/python/py_benchmark.py tmp >> python-cpp-generated-code-benchmark
+ @echo python tmp/py_benchmark.py --cpp_generated '$$@' >> python-cpp-generated-code-benchmark
+ @chmod +x python-cpp-generated-code-benchmark
+
+python-pure-python: python-pure-python-benchmark
+ ./python-pure-python-benchmark $(all_data)
-generate_datasets_LDADD = $(top_srcdir)/src/libprotobuf.la
-generate_datasets_SOURCES = generate_datasets.cc
-generate_datasets_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir)
-nodist_generate_datasets_SOURCES = \
- $(benchmarks_protoc_outputs) \
- $(benchmarks_protoc_outputs_proto2)
+python-cpp-reflection: python-cpp-reflection-benchmark
+ ./python-cpp-reflection-benchmark $(all_data)
+python-cpp-generated-code: python-cpp-generated-code-benchmark
+ ./python-cpp-generated-code-benchmark $(all_data)
+
+############# 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
-generate_datasets-generate_datasets.$(OBJEXT): benchmarks.pb.h
+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_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
-nodist_cpp_benchmark_SOURCES = \
- $(benchmarks_protoc_outputs) \
- $(benchmarks_protoc_outputs_proto2)
+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
-$(benchmarks_protoc_outputs): protoc_middleman
-$(benchmarks_protoc_outputs_proto2): protoc_middleman2
+new_data = $$(for data in $(all_data); do echo "tmp$${data\#$(srcdir)}"; done | xargs)
-CLEANFILES = \
- $(benchmarks_protoc_outputs) \
- $(benchmarks_protoc_outputs_proto2) \
- protoc_middleman \
- protoc_middleman2 \
- dataset.*
+generate_gogo_data: protoc_middleman protoc_middleman2 gogo-data-scrubber
+ mkdir -p `dirname $(new_data)`
+ ./gogo-data-scrubber $(all_data) $(new_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
-MAINTAINERCLEANFILES = \
- Makefile.in
+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
-if USE_EXTERNAL_PROTOC
+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
-protoc_middleman: $(benchmarks_protoc_inputs)
- $(PROTOC) -I$(srcdir) -I$(top_srcdir) --cpp_out=. $(benchmarks_protoc_inputs)
- touch 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
-protoc_middleman2: $(benchmarks_protoc_inputs_proto2)
- $(PROTOC) -I$(srcdir) -I$(top_srcdir) --cpp_out=. $(benchmarks_protoc_inputs_proto2)
- touch protoc_middleman2
+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
-else
+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
-# We have to cd to $(srcdir) before executing protoc because $(protoc_inputs) is
-# relative to srcdir, which may not be the same as the current directory when
-# building out-of-tree.
-protoc_middleman: $(top_srcdir)/src/protoc$(EXEEXT) $(benchmarks_protoc_inputs) $(well_known_type_protoc_inputs)
- oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd $(benchmarks_protoc_inputs) )
- touch protoc_middleman
+gogo_data = $$(find . -type f -name "dataset.*.pb" -path "./tmp/*")
-protoc_middleman2: $(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 $(benchmarks_protoc_inputs_proto2) )
- touch 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_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)
+
+############ UTIL RULES END ############
+
+MAINTAINERCLEANFILES = \
+ Makefile.in
+
+CLEANFILES = \
+ $(benchmarks_protoc_outputs) \
+ $(benchmarks_protoc_outputs_header) \
+ $(benchmarks_protoc_outputs_proto2) \
+ $(benchmarks_protoc_outputs_proto2_header) \
+ initialize_submodule \
+ make_tmp_dir \
+ protoc_middleman \
+ protoc_middleman2 \
+ javac_middleman \
+ java-benchmark \
+ python_cpp_proto_library \
+ python-pure-python-benchmark \
+ python-cpp-reflection-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.*
+
-endif
+clean-local:
+ -rm -rf tmp/*
diff --git a/benchmarks/ProtoBench.java b/benchmarks/ProtoBench.java
deleted file mode 100644
index 86d62feb..00000000
--- a/benchmarks/ProtoBench.java
+++ /dev/null
@@ -1,203 +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.protocolbuffers;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-import java.lang.reflect.Method;
-
-import com.google.protobuf.ByteString;
-import com.google.protobuf.CodedInputStream;
-import com.google.protobuf.CodedOutputStream;
-import com.google.protobuf.Message;
-
-public class ProtoBench {
-
- private static final long MIN_SAMPLE_TIME_MS = 2 * 1000;
- private static final long TARGET_TIME_MS = 30 * 1000;
-
- private ProtoBench() {
- // Prevent instantiation
- }
-
- public static void main(String[] args) {
- if (args.length < 2 || (args.length % 2) != 0) {
- System.err.println("Usage: ProtoBench <descriptor type name> <input data>");
- System.err.println("The descriptor type name is the fully-qualified message name,");
- System.err.println("e.g. com.google.protocolbuffers.benchmark.Message1");
- System.err.println("(You can specify multiple pairs of descriptor type name and input data.)");
- System.exit(1);
- }
- boolean success = true;
- for (int i = 0; i < args.length; i += 2) {
- success &= runTest(args[i], args[i + 1]);
- }
- System.exit(success ? 0 : 1);
- }
-
- /**
- * Runs a single test. Error messages are displayed to stderr, and the return value
- * indicates general success/failure.
- */
- public static boolean runTest(String type, String file) {
- System.out.println("Benchmarking " + type + " with file " + file);
- final Message defaultMessage;
- try {
- Class<?> clazz = Class.forName(type);
- Method method = clazz.getDeclaredMethod("getDefaultInstance");
- defaultMessage = (Message) method.invoke(null);
- } catch (Exception e) {
- // We want to do the same thing with all exceptions. Not generally nice,
- // but this is slightly different.
- System.err.println("Unable to get default message for " + type);
- return false;
- }
-
- try {
- final byte[] inputData = readAllBytes(file);
- final ByteArrayInputStream inputStream = new ByteArrayInputStream(inputData);
- final ByteString inputString = ByteString.copyFrom(inputData);
- final Message sampleMessage = defaultMessage.newBuilderForType().mergeFrom(inputString).build();
- FileOutputStream devNullTemp = null;
- CodedOutputStream reuseDevNullTemp = null;
- try {
- devNullTemp = new FileOutputStream("/dev/null");
- reuseDevNullTemp = CodedOutputStream.newInstance(devNullTemp);
- } catch (FileNotFoundException e) {
- // ignore: this is probably Windows, where /dev/null does not exist
- }
- final FileOutputStream devNull = devNullTemp;
- final CodedOutputStream reuseDevNull = reuseDevNullTemp;
- benchmark("Serialize to byte string", inputData.length, new Action() {
- public void execute() { sampleMessage.toByteString(); }
- });
- benchmark("Serialize to byte array", inputData.length, new Action() {
- public void execute() { sampleMessage.toByteArray(); }
- });
- benchmark("Serialize to memory stream", inputData.length, new Action() {
- public void execute() throws IOException {
- sampleMessage.writeTo(new ByteArrayOutputStream());
- }
- });
- if (devNull != null) {
- benchmark("Serialize to /dev/null with FileOutputStream", inputData.length, new Action() {
- public void execute() throws IOException {
- sampleMessage.writeTo(devNull);
- }
- });
- benchmark("Serialize to /dev/null reusing FileOutputStream", inputData.length, new Action() {
- public void execute() throws IOException {
- sampleMessage.writeTo(reuseDevNull);
- reuseDevNull.flush(); // force the write to the OutputStream
- }
- });
- }
- benchmark("Deserialize from byte string", inputData.length, new Action() {
- public void execute() throws IOException {
- defaultMessage.newBuilderForType().mergeFrom(inputString).build();
- }
- });
- benchmark("Deserialize from byte array", inputData.length, new Action() {
- public void execute() throws IOException {
- defaultMessage.newBuilderForType()
- .mergeFrom(CodedInputStream.newInstance(inputData)).build();
- }
- });
- benchmark("Deserialize from memory stream", inputData.length, new Action() {
- public void execute() throws IOException {
- defaultMessage.newBuilderForType()
- .mergeFrom(CodedInputStream.newInstance(inputStream)).build();
- inputStream.reset();
- }
- });
- System.out.println();
- return true;
- } catch (Exception e) {
- System.err.println("Error: " + e.getMessage());
- System.err.println("Detailed exception information:");
- e.printStackTrace(System.err);
- return false;
- }
- }
-
- private static void benchmark(String name, long dataSize, Action action) throws IOException {
- // Make sure it's JITted "reasonably" hard before running the first progress test
- for (int i=0; i < 100; i++) {
- action.execute();
- }
-
- // Run it progressively more times until we've got a reasonable sample
- int iterations = 1;
- long elapsed = timeAction(action, iterations);
- while (elapsed < MIN_SAMPLE_TIME_MS) {
- iterations *= 2;
- elapsed = timeAction(action, iterations);
- }
-
- // Upscale the sample to the target time. Do this in floating point arithmetic
- // to avoid overflow issues.
- iterations = (int) ((TARGET_TIME_MS / (double) elapsed) * iterations);
- elapsed = timeAction(action, iterations);
- System.out.println(name + ": " + iterations + " iterations in "
- + (elapsed/1000f) + "s; "
- + (iterations * dataSize) / (elapsed * 1024 * 1024 / 1000f)
- + "MB/s");
- }
-
- private static long timeAction(Action action, int iterations) throws IOException {
- System.gc();
- long start = System.currentTimeMillis();
- for (int i = 0; i < iterations; i++) {
- action.execute();
- }
- long end = System.currentTimeMillis();
- return end - start;
- }
-
- private static byte[] readAllBytes(String filename) throws IOException {
- RandomAccessFile file = new RandomAccessFile(new File(filename), "r");
- byte[] content = new byte[(int) file.length()];
- file.readFully(content);
- return content;
- }
-
- /**
- * Interface used to capture a single action to benchmark.
- */
- interface Action {
- void execute() throws IOException;
- }
-}
diff --git a/benchmarks/README.md b/benchmarks/README.md
index c9027805..21cd7352 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -3,23 +3,182 @@
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)
-The schema for the datasets is described in `benchmarks.proto`.
+## Prerequisite
+
+First, you need to follow the instruction in the root directory's README to
+build your language's protobuf, then:
+
+### CPP
+You need to install [cmake](https://cmake.org/) before building the benchmark.
+
+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
+[google/caliper](https://github.com/google/caliper) as benchmark tool, which
+can be automaticly included by maven.
+
+### Python
+We're using python C++ API for testing the generated
+CPP proto version of python protobuf, which is also a prerequisite for Python
+protobuf cpp implementation. You need to install the correct version of Python
+C++ extension package before run generated CPP proto version of Python
+protobuf's benchmark. e.g. under Ubuntu, you need to
+
+```
+$ sudo apt-get install python-dev
+$ 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.
-Generate the data sets like so:
+To install protoc-gen-go, run:
```
-$ make
-$ ./generate-datasets
-Wrote dataset: dataset.google_message1_proto3.pb
-Wrote dataset: dataset.google_message1_proto2.pb
-Wrote dataset: dataset.google_message2.pb
-$
+$ 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
+initially, you need to run the following command to download the testing data:
+
+```
+$ ./download_data.sh
+```
+
+After doing this the big data file will automaticly generated in the
+benchmark directory.
+
+## Run instructions
+
+To run all the benchmark dataset:
+
+### Java:
+
+```
+$ make java
+```
+
+### CPP:
+
+```
+$ 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
+reflection and cpp generated code. To run these version benchmark, you need to:
+
+#### Pure Python:
+
+```
+$ make python-pure-python
+```
+
+#### CPP reflection:
+
```
+$ make python-cpp-reflection
+```
+
+#### CPP generated code:
+
+```
+$ make python-cpp-generated-code
+```
+
+### 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 options)]
+```
+
+### CPP:
+
+```
+$ make cpp-benchmark
+$ ./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 [--json] $(specific generated dataset file name)
+```
+
+#### CPP reflection:
+
+```
+$ make python-cpp-reflection-benchmark
+$ ./python-cpp-reflection-benchmark [--json] $(specific generated dataset file name)
+```
+
+#### CPP generated code:
+
+```
+$ make python-cpp-generated-code-benchmark
+$ ./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:
+
+1. name is the benchmark dataset's name.
+2. message_name is the benchmark's message type full name (including package and message name)
+3. payload is the list of raw data.
+
+The schema for the datasets is described in `benchmarks.proto`.
-Each data set will be written to its own file. Benchmarks will
-likely want to run several benchmarks against each data set (parse,
+Benchmark likely want to run several benchmarks against each data set (parse,
serialize, possibly JSON, possibly using different APIs, etc).
We would like to add more data sets. In general we will favor data sets
diff --git a/benchmarks/__init__.py b/benchmarks/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/benchmarks/__init__.py
diff --git a/benchmarks/benchmark_messages_proto2.proto b/benchmarks/benchmark_messages_proto2.proto
deleted file mode 100644
index 59085503..00000000
--- a/benchmarks/benchmark_messages_proto2.proto
+++ /dev/null
@@ -1,143 +0,0 @@
-// Benchmark messages for proto2.
-
-syntax = "proto2";
-
-package benchmarks.proto2;
-option java_package = "com.google.protobuf.benchmarks";
-
-// This is the default, but we specify it here explicitly.
-option optimize_for = SPEED;
-
-option cc_enable_arenas = true;
-
-message GoogleMessage1 {
- required string field1 = 1;
- optional string field9 = 9;
- optional string field18 = 18;
- optional bool field80 = 80 [default=false];
- optional bool field81 = 81 [default=true];
- required int32 field2 = 2;
- required int32 field3 = 3;
- optional int32 field280 = 280;
- optional int32 field6 = 6 [default=0];
- optional int64 field22 = 22;
- optional string field4 = 4;
- repeated fixed64 field5 = 5;
- optional bool field59 = 59 [default=false];
- optional string field7 = 7;
- optional int32 field16 = 16;
- optional int32 field130 = 130 [default=0];
- optional bool field12 = 12 [default=true];
- optional bool field17 = 17 [default=true];
- optional bool field13 = 13 [default=true];
- optional bool field14 = 14 [default=true];
- optional int32 field104 = 104 [default=0];
- optional int32 field100 = 100 [default=0];
- optional int32 field101 = 101 [default=0];
- optional string field102 = 102;
- optional string field103 = 103;
- optional int32 field29 = 29 [default=0];
- optional bool field30 = 30 [default=false];
- optional int32 field60 = 60 [default=-1];
- optional int32 field271 = 271 [default=-1];
- optional int32 field272 = 272 [default=-1];
- optional int32 field150 = 150;
- optional int32 field23 = 23 [default=0];
- optional bool field24 = 24 [default=false];
- optional int32 field25 = 25 [default=0];
- optional GoogleMessage1SubMessage field15 = 15;
- optional bool field78 = 78;
- optional int32 field67 = 67 [default=0];
- optional int32 field68 = 68;
- optional int32 field128 = 128 [default=0];
- optional string field129 = 129 [default="xxxxxxxxxxxxxxxxxxxxx"];
- optional int32 field131 = 131 [default=0];
-}
-
-message GoogleMessage1SubMessage {
- optional int32 field1 = 1 [default=0];
- optional int32 field2 = 2 [default=0];
- optional int32 field3 = 3 [default=0];
- optional string field15 = 15;
- optional bool field12 = 12 [default=true];
- optional int64 field13 = 13;
- optional int64 field14 = 14;
- optional int32 field16 = 16;
- optional int32 field19 = 19 [default=2];
- optional bool field20 = 20 [default=true];
- optional bool field28 = 28 [default=true];
- optional fixed64 field21 = 21;
- optional int32 field22 = 22;
- optional bool field23 = 23 [ default=false ];
- optional bool field206 = 206 [default=false];
- optional fixed32 field203 = 203;
- optional int32 field204 = 204;
- optional string field205 = 205;
- optional uint64 field207 = 207;
- optional uint64 field300 = 300;
-}
-
-message GoogleMessage2 {
- optional string field1 = 1;
- optional int64 field3 = 3;
- optional int64 field4 = 4;
- optional int64 field30 = 30;
- optional bool field75 = 75 [default=false];
- optional string field6 = 6;
- optional bytes field2 = 2;
- optional int32 field21 = 21 [default=0];
- optional int32 field71 = 71;
- optional float field25 = 25;
- optional int32 field109 = 109 [default=0];
- optional int32 field210 = 210 [default=0];
- optional int32 field211 = 211 [default=0];
- optional int32 field212 = 212 [default=0];
- optional int32 field213 = 213 [default=0];
- optional int32 field216 = 216 [default=0];
- optional int32 field217 = 217 [default=0];
- optional int32 field218 = 218 [default=0];
- optional int32 field220 = 220 [default=0];
- optional int32 field221 = 221 [default=0];
- optional float field222 = 222 [default=0.0];
- optional int32 field63 = 63;
-
- repeated group Group1 = 10 {
- required float field11 = 11;
- optional float field26 = 26;
- optional string field12 = 12;
- optional string field13 = 13;
- repeated string field14 = 14;
- required uint64 field15 = 15;
- optional int32 field5 = 5;
- optional string field27 = 27;
- optional int32 field28 = 28;
- optional string field29 = 29;
- optional string field16 = 16;
- repeated string field22 = 22;
- repeated int32 field73 = 73;
- optional int32 field20 = 20 [default=0];
- optional string field24 = 24;
- optional GoogleMessage2GroupedMessage field31 = 31;
- }
- repeated string field128 = 128;
- optional int64 field131 = 131;
- repeated string field127 = 127;
- optional int32 field129 = 129;
- repeated int64 field130 = 130;
- optional bool field205 = 205 [default=false];
- optional bool field206 = 206 [default=false];
-}
-
-message GoogleMessage2GroupedMessage {
- optional float field1 = 1;
- optional float field2 = 2;
- optional float field3 = 3 [default=0.0];
- optional bool field4 = 4;
- optional bool field5 = 5;
- optional bool field6 = 6 [default=true];
- optional bool field7 = 7 [default=false];
- optional float field8 = 8;
- optional bool field9 = 9;
- optional float field10 = 10;
- optional int64 field11 = 11;
-}
diff --git a/benchmarks/cpp_benchmark.cc b/benchmarks/cpp/cpp_benchmark.cc
index 0e6febc2..f8b55291 100644
--- a/benchmarks/cpp_benchmark.cc
+++ b/benchmarks/cpp/cpp_benchmark.cc
@@ -28,13 +28,16 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#include <glob.h>
-#include <iostream>
#include <fstream>
+#include <iostream>
#include "benchmark/benchmark_api.h"
#include "benchmarks.pb.h"
-#include "benchmark_messages_proto2.pb.h"
-#include "benchmark_messages_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"
+
#define PREFIX "dataset."
#define SUFFIX ".pb"
@@ -118,9 +121,10 @@ class ParseNewArenaFixture : public Fixture {
virtual void BenchmarkCase(benchmark::State& state) {
WrappingCounter i(payloads_.size());
size_t total = 0;
+ Arena arena;
while (state.KeepRunning()) {
- Arena arena;
+ arena.Reset();
Message* m = Arena::CreateMessage<T>(&arena);
const std::string& payload = payloads_[i.Next()];
total += payload.size();
@@ -219,6 +223,14 @@ void RegisterBenchmarks(const std::string& dataset_bytes) {
RegisterBenchmarksForType<benchmarks::proto2::GoogleMessage1>(dataset);
} else if (dataset.message_name() == "benchmarks.proto2.GoogleMessage2") {
RegisterBenchmarksForType<benchmarks::proto2::GoogleMessage2>(dataset);
+ } else if (dataset.message_name() ==
+ "benchmarks.google_message3.GoogleMessage3") {
+ RegisterBenchmarksForType
+ <benchmarks::google_message3::GoogleMessage3>(dataset);
+ } else if (dataset.message_name() ==
+ "benchmarks.google_message4.GoogleMessage4") {
+ RegisterBenchmarksForType
+ <benchmarks::google_message4::GoogleMessage4>(dataset);
} else {
std::cerr << "Unknown message type: " << dataset.message_name();
exit(1);
@@ -226,17 +238,17 @@ void RegisterBenchmarks(const std::string& dataset_bytes) {
}
int main(int argc, char *argv[]) {
- glob_t glob_result;
- if (glob("dataset.*.pb", 0, NULL, &glob_result) != 0) {
- fprintf(stderr, "No dataset files found.\n");
+ ::benchmark::Initialize(&argc, argv);
+ if (argc == 1) {
+ std::cerr << "Usage: ./cpp-benchmark <input data>" << std::endl;
+ std::cerr << "input data is in the format of \"benchmarks.proto\""
+ << std::endl;
return 1;
+ } else {
+ for (int i = 1; i < argc; i++) {
+ RegisterBenchmarks(ReadFile(argv[i]));
+ }
}
- for (size_t i = 0; i < glob_result.gl_pathc; i++) {
- fprintf(stderr, "Found input dataset: %s\n", glob_result.gl_pathv[i]);
- RegisterBenchmarks(ReadFile(glob_result.gl_pathv[i]));
- }
-
- ::benchmark::Initialize(&argc, argv);
::benchmark::RunSpecifiedBenchmarks();
}
diff --git a/benchmarks/datasets/google_message1/proto2/benchmark_message1_proto2.proto b/benchmarks/datasets/google_message1/proto2/benchmark_message1_proto2.proto
new file mode 100644
index 00000000..21261905
--- /dev/null
+++ b/benchmarks/datasets/google_message1/proto2/benchmark_message1_proto2.proto
@@ -0,0 +1,78 @@
+// Benchmark messages for proto2.
+
+syntax = "proto2";
+
+package benchmarks.proto2;
+option java_package = "com.google.protobuf.benchmarks";
+
+// This is the default, but we specify it here explicitly.
+option optimize_for = SPEED;
+
+option cc_enable_arenas = true;
+
+message GoogleMessage1 {
+ required string field1 = 1;
+ optional string field9 = 9;
+ optional string field18 = 18;
+ optional bool field80 = 80 [default = false];
+ optional bool field81 = 81 [default = true];
+ required int32 field2 = 2;
+ required int32 field3 = 3;
+ optional int32 field280 = 280;
+ optional int32 field6 = 6 [default = 0];
+ optional int64 field22 = 22;
+ optional string field4 = 4;
+ repeated fixed64 field5 = 5;
+ optional bool field59 = 59 [default = false];
+ optional string field7 = 7;
+ optional int32 field16 = 16;
+ optional int32 field130 = 130 [default = 0];
+ optional bool field12 = 12 [default = true];
+ optional bool field17 = 17 [default = true];
+ optional bool field13 = 13 [default = true];
+ optional bool field14 = 14 [default = true];
+ optional int32 field104 = 104 [default = 0];
+ optional int32 field100 = 100 [default = 0];
+ optional int32 field101 = 101 [default = 0];
+ optional string field102 = 102;
+ optional string field103 = 103;
+ optional int32 field29 = 29 [default = 0];
+ optional bool field30 = 30 [default = false];
+ optional int32 field60 = 60 [default = -1];
+ optional int32 field271 = 271 [default = -1];
+ optional int32 field272 = 272 [default = -1];
+ optional int32 field150 = 150;
+ optional int32 field23 = 23 [default = 0];
+ optional bool field24 = 24 [default = false];
+ optional int32 field25 = 25 [default = 0];
+ optional GoogleMessage1SubMessage field15 = 15;
+ optional bool field78 = 78;
+ optional int32 field67 = 67 [default = 0];
+ optional int32 field68 = 68;
+ optional int32 field128 = 128 [default = 0];
+ optional string field129 = 129 [default = "xxxxxxxxxxxxxxxxxxxxx"];
+ optional int32 field131 = 131 [default = 0];
+}
+
+message GoogleMessage1SubMessage {
+ optional int32 field1 = 1 [default = 0];
+ optional int32 field2 = 2 [default = 0];
+ optional int32 field3 = 3 [default = 0];
+ optional string field15 = 15;
+ optional bool field12 = 12 [default = true];
+ optional int64 field13 = 13;
+ optional int64 field14 = 14;
+ optional int32 field16 = 16;
+ optional int32 field19 = 19 [default = 2];
+ optional bool field20 = 20 [default = true];
+ optional bool field28 = 28 [default = true];
+ optional fixed64 field21 = 21;
+ optional int32 field22 = 22;
+ optional bool field23 = 23 [default = false];
+ optional bool field206 = 206 [default = false];
+ optional fixed32 field203 = 203;
+ optional int32 field204 = 204;
+ optional string field205 = 205;
+ optional uint64 field207 = 207;
+ optional uint64 field300 = 300;
+}
diff --git a/benchmarks/google_message1.dat b/benchmarks/datasets/google_message1/proto2/dataset.google_message1_proto2.pb
index bc0f064c..f6fe7848 100644
--- a/benchmarks/google_message1.dat
+++ b/benchmarks/datasets/google_message1/proto2/dataset.google_message1_proto2.pb
Binary files differ
diff --git a/benchmarks/benchmark_messages_proto3.proto b/benchmarks/datasets/google_message1/proto3/benchmark_message1_proto3.proto
index 090b554b..090b554b 100644
--- a/benchmarks/benchmark_messages_proto3.proto
+++ b/benchmarks/datasets/google_message1/proto3/benchmark_message1_proto3.proto
diff --git a/benchmarks/datasets/google_message1/proto3/dataset.google_message1_proto3.pb b/benchmarks/datasets/google_message1/proto3/dataset.google_message1_proto3.pb
new file mode 100644
index 00000000..4955bed3
--- /dev/null
+++ b/benchmarks/datasets/google_message1/proto3/dataset.google_message1_proto3.pb
Binary files differ
diff --git a/benchmarks/datasets/google_message2/benchmark_message2.proto b/benchmarks/datasets/google_message2/benchmark_message2.proto
new file mode 100644
index 00000000..820630e4
--- /dev/null
+++ b/benchmarks/datasets/google_message2/benchmark_message2.proto
@@ -0,0 +1,76 @@
+// Benchmark messages for proto2.
+
+syntax = "proto2";
+
+package benchmarks.proto2;
+option java_package = "com.google.protobuf.benchmarks";
+
+// This is the default, but we specify it here explicitly.
+option optimize_for = SPEED;
+
+option cc_enable_arenas = true;
+
+message GoogleMessage2 {
+ optional string field1 = 1;
+ optional int64 field3 = 3;
+ optional int64 field4 = 4;
+ optional int64 field30 = 30;
+ optional bool field75 = 75 [default = false];
+ optional string field6 = 6;
+ optional bytes field2 = 2;
+ optional int32 field21 = 21 [default = 0];
+ optional int32 field71 = 71;
+ optional float field25 = 25;
+ optional int32 field109 = 109 [default = 0];
+ optional int32 field210 = 210 [default = 0];
+ optional int32 field211 = 211 [default = 0];
+ optional int32 field212 = 212 [default = 0];
+ optional int32 field213 = 213 [default = 0];
+ optional int32 field216 = 216 [default = 0];
+ optional int32 field217 = 217 [default = 0];
+ optional int32 field218 = 218 [default = 0];
+ optional int32 field220 = 220 [default = 0];
+ optional int32 field221 = 221 [default = 0];
+ optional float field222 = 222 [default = 0.0];
+ optional int32 field63 = 63;
+
+ repeated group Group1 = 10 {
+ required float field11 = 11;
+ optional float field26 = 26;
+ optional string field12 = 12;
+ optional string field13 = 13;
+ repeated string field14 = 14;
+ required uint64 field15 = 15;
+ optional int32 field5 = 5;
+ optional string field27 = 27;
+ optional int32 field28 = 28;
+ optional string field29 = 29;
+ optional string field16 = 16;
+ repeated string field22 = 22;
+ repeated int32 field73 = 73;
+ optional int32 field20 = 20 [default = 0];
+ optional string field24 = 24;
+ optional GoogleMessage2GroupedMessage field31 = 31;
+ }
+ repeated string field128 = 128;
+ optional int64 field131 = 131;
+ repeated string field127 = 127;
+ optional int32 field129 = 129;
+ repeated int64 field130 = 130;
+ optional bool field205 = 205 [default = false];
+ optional bool field206 = 206 [default = false];
+}
+
+message GoogleMessage2GroupedMessage {
+ optional float field1 = 1;
+ optional float field2 = 2;
+ optional float field3 = 3 [default = 0.0];
+ optional bool field4 = 4;
+ optional bool field5 = 5;
+ optional bool field6 = 6 [default = true];
+ optional bool field7 = 7 [default = false];
+ optional float field8 = 8;
+ optional bool field9 = 9;
+ optional float field10 = 10;
+ optional int64 field11 = 11;
+}
diff --git a/benchmarks/google_message2.dat b/benchmarks/datasets/google_message2/dataset.google_message2.pb
index 06c09441..3fa0e49e 100644
--- a/benchmarks/google_message2.dat
+++ b/benchmarks/datasets/google_message2/dataset.google_message2.pb
Binary files differ
diff --git a/benchmarks/datasets/google_message3/benchmark_message3.proto b/benchmarks/datasets/google_message3/benchmark_message3.proto
new file mode 100644
index 00000000..d6f0d14e
--- /dev/null
+++ b/benchmarks/datasets/google_message3/benchmark_message3.proto
@@ -0,0 +1,534 @@
+syntax = "proto2";
+
+import "datasets/google_message3/benchmark_message3_1.proto";
+import "datasets/google_message3/benchmark_message3_2.proto";
+import "datasets/google_message3/benchmark_message3_3.proto";
+import "datasets/google_message3/benchmark_message3_4.proto";
+import "datasets/google_message3/benchmark_message3_5.proto";
+import "datasets/google_message3/benchmark_message3_7.proto";
+import "datasets/google_message3/benchmark_message3_8.proto";
+package benchmarks.google_message3;
+
+option cc_enable_arenas = true;
+option java_package = "com.google.protobuf.benchmarks";
+
+message GoogleMessage3 {
+ optional .benchmarks.google_message3.Message37487 field37519 = 2;
+ optional .benchmarks.google_message3.Message36876 field37520 = 3;
+ optional .benchmarks.google_message3.Message13062 field37521 = 4;
+ optional .benchmarks.google_message3.Message952 field37522 = 5;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37523 = 6;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37524 = 7;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37525 = 8;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37526 = 9;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37527 = 10;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37528 = 11;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37529 = 12;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37530 = 13;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37531 = 14;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37532 = 15;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37533 = 16;
+}
+
+message Message1327 {
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field1369 = 1;
+ repeated .benchmarks.google_message3.Message1328 field1370 = 3;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field1371 = 5;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field1372 = 6;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message1327 field1373 = 23104162;
+ }
+}
+
+message Message3672 {
+ optional .benchmarks.google_message3.Enum3476 field3727 = 1;
+ optional int32 field3728 = 11;
+ optional int32 field3729 = 2;
+ repeated group Message3673 = 3 {
+ required .benchmarks.google_message3.Enum3476 field3738 = 4;
+ required int32 field3739 = 5;
+ }
+ repeated group Message3674 = 6 {
+ required .benchmarks.google_message3.Enum3476 field3740 = 7;
+ required int32 field3741 = 8;
+ }
+ optional bool field3732 = 9;
+ optional int32 field3733 = 10;
+ optional .benchmarks.google_message3.Enum3476 field3734 = 20;
+ optional int32 field3735 = 21;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field3736 = 50;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message3672 field3737 = 3144435;
+ }
+}
+
+message Message3804 {
+ required int64 field3818 = 1;
+ required bool field3819 = 2;
+ repeated .benchmarks.google_message3.Enum3805 field3820 = 4;
+ optional int32 field3821 = 5;
+ optional bool field3822 = 6;
+ optional int64 field3823 = 7;
+ optional .benchmarks.google_message3.Enum3783 field3824 = 8;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message3804 field3825 = 59241828;
+ }
+}
+
+message Message6849 {
+ repeated .benchmarks.google_message3.Message6850 field6910 = 1;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message6849 field6911 = 107558455;
+ }
+}
+
+message Message6866 {
+ repeated .benchmarks.google_message3.Message6863 field6973 = 1;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message6866 field6974 = 22259060;
+ }
+}
+
+message Message6870 {
+ repeated .benchmarks.google_message3.Message6871 field6991 = 1;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message6870 field6992 = 90034652;
+ }
+}
+
+message Message7651 {
+ optional string field7685 = 1;
+ optional int64 field7686 = 2;
+ optional int64 field7687 = 3;
+ optional int64 field7688 = 4;
+ optional int32 field7689 = 5;
+ optional int32 field7690 = 6;
+ optional int32 field7691 = 7;
+ optional int32 field7692 = 8;
+ optional int32 field7693 = 9;
+ optional int32 field7694 = 10;
+ optional int32 field7695 = 11;
+ optional int32 field7696 = 12;
+ optional int32 field7697 = 13;
+ optional int32 field7698 = 14;
+ optional int32 field7699 = 15;
+ optional int32 field7700 = 16;
+ optional int32 field7701 = 17;
+ optional int32 field7702 = 18;
+ optional bool field7703 = 19;
+ repeated int32 field7704 = 20;
+ repeated int32 field7705 = 21;
+ repeated string field7706 = 22;
+ repeated string field7707 = 23;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field7708 = 24;
+ optional int32 field7709 = 25;
+ optional int32 field7710 = 26;
+ optional int32 field7711 = 27;
+ optional int32 field7712 = 43;
+ optional int32 field7713 = 28;
+ optional int32 field7714 = 29;
+ repeated .benchmarks.google_message3.Message7547 field7715 = 30;
+ repeated .benchmarks.google_message3.Message7547 field7716 = 31;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field7717 = 32;
+ repeated string field7718 = 33;
+ repeated string field7719 = 34;
+ repeated .benchmarks.google_message3.Message7648 field7720 = 35;
+ optional bool field7721 = 36;
+ optional bool field7722 = 37;
+ optional bool field7723 = 38;
+ optional bool field7724 = 39;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field7725 = 40;
+ optional .benchmarks.google_message3.UnusedEnum field7726 = 41;
+ optional .benchmarks.google_message3.Enum7654 field7727 = 42;
+ optional string field7728 = 44;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field7729 = 45;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message7651 field7730 = 55876009;
+ }
+}
+
+message Message7864 {
+ optional string field7866 = 1;
+ optional string field7867 = 2;
+ repeated .benchmarks.google_message3.Message7865 field7868 = 5;
+ repeated .benchmarks.google_message3.Message7865 field7869 = 6;
+ repeated .benchmarks.google_message3.Message7865 field7870 = 7;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field7871 = 8;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message7864 field7872 = 44542730;
+ }
+}
+
+message Message7929 {
+ optional int64 field7942 = 1;
+ optional int64 field7943 = 4;
+ optional int64 field7944 = 5;
+ optional int64 field7945 = 12;
+ optional int64 field7946 = 13;
+ optional int64 field7947 = 18;
+ optional int64 field7948 = 6;
+ optional int64 field7949 = 7;
+ repeated .benchmarks.google_message3.Message7919 field7950 = 8;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field7951 = 20;
+ repeated .benchmarks.google_message3.Message7920 field7952 = 14;
+ repeated .benchmarks.google_message3.Message7921 field7953 = 15;
+ repeated .benchmarks.google_message3.Message7928 field7954 = 17;
+ optional int64 field7955 = 19;
+ optional bool field7956 = 2;
+ optional int64 field7957 = 3;
+ optional int64 field7958 = 9;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field7959 = 10;
+ repeated bytes field7960 = 11;
+ optional int64 field7961 = 16;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message7929 field7962 = 53392238;
+ }
+}
+
+message Message8508 {
+ repeated .benchmarks.google_message3.Message8511 field8517 = 8;
+ repeated .benchmarks.google_message3.Message8512 field8518 = 9;
+ repeated .benchmarks.google_message3.Message8513 field8519 = 11;
+ optional bool field8520 = 13;
+ optional .benchmarks.google_message3.Message8514 field8521 = 14;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field8522 = 15;
+ repeated .benchmarks.google_message3.Message8515 field8523 = 16;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field8524 = 17;
+ optional int64 field8525 = 1;
+ optional float field8526 = 2;
+ optional int64 field8527 = 3;
+ optional int64 field8528 = 4;
+ optional int32 field8529 = 5;
+ optional bytes field8530 = 6;
+ repeated bytes field8531 = 7;
+ optional bool field8532 = 10;
+ optional bytes field8533 = 12;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message8508 field8534 = 3811804;
+ }
+}
+
+message Message9122 {
+ optional float field9132 = 1;
+ optional float field9133 = 2;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message9122 field9134 = 120398939;
+ }
+}
+
+message Message10177 {
+ repeated .benchmarks.google_message3.Message10155 field10270 = 1;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message10177 field10271 = 26801105;
+ }
+}
+
+message Message10278 {
+ repeated int32 field10286 = 1 [packed = true];
+ repeated int32 field10287 = 2 [packed = true];
+ optional int32 field10288 = 3;
+ extend .benchmarks.google_message3.Message10155 {
+ optional .benchmarks.google_message3.Message10278 field10289 = 29374161;
+ }
+}
+
+message Message10323 {
+ repeated .benchmarks.google_message3.Message10320 field10360 = 1;
+ extend .benchmarks.google_message3.Message10155 {
+ optional .benchmarks.google_message3.Message10323 field10361 = 27922524;
+ }
+}
+
+message Message10324 {
+ repeated .benchmarks.google_message3.Message10322 field10362 = 1;
+ optional .benchmarks.google_message3.Message10321 field10363 = 2;
+ extend .benchmarks.google_message3.Message10155 {
+ optional .benchmarks.google_message3.Message10324 field10364 = 27832297;
+ }
+}
+
+message Message11990 {
+ repeated .benchmarks.google_message3.Message11988 field12030 = 1;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message11990 field12031 = 21265426;
+ }
+}
+
+message Message12691 {
+ optional string field12713 = 1;
+ optional int32 field12714 = 2;
+ optional .benchmarks.google_message3.Message12668 field12715 = 3;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message12691 field12716 = 28426536;
+ }
+}
+
+message Message12870 {
+ required int32 field12879 = 1;
+ optional int32 field12880 = 7;
+ required int32 field12881 = 2;
+ optional uint64 field12882 = 3;
+ optional string field12883 = 2001;
+ optional fixed64 field12884 = 4;
+ repeated fixed64 field12885 = 14;
+ optional int32 field12886 = 9;
+ optional int64 field12887 = 18;
+ repeated .benchmarks.google_message3.Message12870 field12888 = 8;
+ optional int32 field12889 = 5;
+ optional uint64 field12890 = 6;
+ optional int32 field12891 = 10;
+ optional int32 field12892 = 11;
+ optional double field12893 = 12;
+ optional .benchmarks.google_message3.Message12825 field12894 = 13;
+ optional double field12895 = 15;
+ optional string field12896 = 16;
+ optional .benchmarks.google_message3.Enum12871 field12897 = 17;
+ optional int32 field12898 = 19;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message12870 field12899 = 5447656;
+ }
+}
+
+message Message13154 {
+ required float field13164 = 1;
+ required float field13165 = 2;
+ extend .benchmarks.google_message3.Message13145 {
+ optional .benchmarks.google_message3.Message13154 field13166 = 47301086;
+ }
+}
+
+message Message16507 {
+ optional bool field16510 = 3;
+ optional bool field16511 = 4;
+ optional bool field16512 = 14;
+ repeated string field16513 = 5;
+ repeated string field16514 = 6;
+ optional string field16515 = 8;
+ repeated int32 field16516 = 9;
+ repeated int32 field16517 = 10;
+ optional int32 field16518 = 7;
+ optional string field16519 = 15;
+ repeated string field16520 = 11;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16521 = 27;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16522 = 22;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16523 = 28;
+ optional string field16524 = 18;
+ optional int32 field16525 = 19;
+ optional int32 field16526 = 20;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field16527 = 23;
+ optional bool field16528 = 24;
+ repeated string field16529 = 25;
+ optional double field16530 = 26;
+ optional .benchmarks.google_message3.Message16478 field16531 = 30;
+ optional bool field16532 = 31;
+ optional string field16533 = 32;
+ optional bool field16534 = 33;
+ optional bool field16535 = 35;
+ optional bool field16536 = 36;
+ optional bool field16537 = 37;
+ optional bool field16538 = 38;
+ optional bool field16539 = 39;
+ optional bool field16540 = 40;
+ repeated string field16541 = 41;
+ extensions 21 to 21;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message16507 field16542 = 5569941;
+ }
+}
+
+message Message16564 {
+ repeated .benchmarks.google_message3.Message16552 field16568 = 1;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message16564 field16569 = 25830030;
+ }
+}
+
+message Message16661 {
+ repeated .benchmarks.google_message3.Message16660 field16671 = 1;
+ repeated uint64 field16672 = 2;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message16661 field16673 = 31274398;
+ }
+}
+
+message Message16746 {
+ repeated .benchmarks.google_message3.Message16727 field16806 = 1;
+ optional bool field16807 = 2;
+ optional bool field16808 = 3;
+ repeated .benchmarks.google_message3.Message16725 field16809 = 4;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message16746 field16810 = 28406765;
+ }
+}
+
+message Message17786 {
+ repeated group Message17787 = 1 {
+ required int32 field18177 = 2;
+ required int32 field18178 = 3;
+ optional .benchmarks.google_message3.Message17783 field18179 = 4;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18180 = 5;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18181 = 6;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field18182 = 8;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18183 = 9;
+ optional .benchmarks.google_message3.Message17726 field18184 = 10;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18185 = 11;
+ optional .benchmarks.google_message3.Message16945 field18186 = 102;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18187 = 12;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18188 = 13;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18189 = 7;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18190 = 100;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18191 = 101;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18192 = 14;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18193 = 19;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18194 = 22;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18195 = 24;
+ optional .benchmarks.google_message3.Enum16925 field18196 = 21;
+ optional bool field18197 = 18;
+ repeated .benchmarks.google_message3.UnusedEnum field18198 = 23;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18199 = 15;
+ optional string field18200 = 16;
+ optional string field18201 = 17;
+ optional bool field18202 = 99;
+ }
+ repeated .benchmarks.google_message3.Message17782 field18175 = 20;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message17786 field18176 = 11823055;
+ }
+}
+
+message Message22857 {
+ repeated .benchmarks.google_message3.Message22853 field22874 = 1;
+ extend .benchmarks.google_message3.Message10155 {
+ optional .benchmarks.google_message3.Message22857 field22875 = 67799715;
+ }
+}
+
+message Message24404 {
+ repeated group Message24405 = 1 {
+ required int32 field24686 = 2;
+ required int32 field24687 = 3;
+ optional .benchmarks.google_message3.Message24317 field24688 = 4;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24689 = 5;
+ optional .benchmarks.google_message3.Message24376 field24690 = 6;
+ optional .benchmarks.google_message3.Message24345 field24691 = 7;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24692 = 8;
+ optional .benchmarks.google_message3.Message24379 field24693 = 9;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24694 = 10;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24695 = 11;
+ optional .benchmarks.google_message3.Message24391 field24696 = 12;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24697 = 13;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24698 = 14;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24699 = 22;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24700 = 23;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24701 = 25;
+ optional .benchmarks.google_message3.Enum16925 field24702 = 18;
+ optional float field24703 = 20;
+ optional bool field24704 = 19;
+ repeated .benchmarks.google_message3.Enum16891 field24705 = 24;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24706 = 15;
+ optional string field24707 = 16;
+ optional string field24708 = 17;
+ optional float field24709 = 21;
+ optional bool field24710 = 26;
+ optional .benchmarks.google_message3.UnusedEnum field24711 = 27;
+ optional bool field24712 = 28;
+ optional .benchmarks.google_message3.UnusedEnum field24713 = 29;
+ optional bool field24714 = 31;
+ optional bool field24715 = 99;
+ optional int64 field24716 = 32;
+ }
+ optional .benchmarks.google_message3.Message24403 field24684 = 30;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message24404 field24685 = 9129287;
+ }
+}
+
+message Message27300 {
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field27302 = 1;
+ optional string field27303 = 2;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message27300 field27304 = 24956467;
+ }
+}
+
+message Message27453 {
+ optional string field27459 = 15;
+ repeated string field27460 = 1;
+ repeated float field27461 = 6;
+ repeated int32 field27462 = 27;
+ repeated int32 field27463 = 28;
+ repeated .benchmarks.google_message3.Message27454 field27464 = 24;
+ repeated string field27465 = 2;
+ repeated float field27466 = 7;
+ repeated string field27467 = 22;
+ repeated string field27468 = 23;
+ optional string field27469 = 26;
+ repeated .benchmarks.google_message3.Message27357 field27470 = 8;
+ optional .benchmarks.google_message3.Message27360 field27471 = 16;
+ optional string field27472 = 25;
+ optional string field27473 = 11;
+ optional bool field27474 = 13;
+ optional bool field27475 = 14;
+ optional bool field27476 = 17;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field27477 = 12;
+ optional bool field27478 = 34268945;
+ optional bool field27479 = 20;
+ optional string field27480 = 21;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field27481 = 10;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message27453 field27482 = 8086204;
+ }
+}
+
+extend .benchmarks.google_message3.Message16945 {
+ optional string field17026 = 472;
+ repeated string field17027 = 818;
+ optional .benchmarks.google_message3.Message0 field17031 = 215;
+ repeated .benchmarks.google_message3.Message0 field17032 = 292;
+ repeated .benchmarks.google_message3.Message0 field17038 = 234;
+ repeated .benchmarks.google_message3.Message0 field17039 = 235;
+ optional .benchmarks.google_message3.Message0 field17042 = 246;
+ optional string field17043 = 224;
+ optional string field17044 = 225;
+ repeated string field17048 = 63;
+ repeated string field17049 = 64;
+ repeated .benchmarks.google_message3.Message0 field17052 = 233;
+ repeated .benchmarks.google_message3.Message0 field17053 = 66;
+ repeated string field17056 = 275;
+ optional string field17057 = 226;
+ repeated .benchmarks.google_message3.Message0 field17060 = 27;
+ repeated string field17073 = 75;
+ repeated .benchmarks.google_message3.Message0 field17076 = 77;
+ repeated string field17078 = 296;
+ repeated .benchmarks.google_message3.Message0 field17082 = 160;
+ repeated .benchmarks.google_message3.Message0 field17091 = 585;
+ repeated .benchmarks.google_message3.Message0 field17098 = 987;
+ repeated .benchmarks.google_message3.Message0 field17101 = 157;
+ repeated string field17102 = 158;
+ repeated string field17107 = 166;
+ repeated string field17133 = 567;
+ repeated string field17134 = 572;
+ repeated string field17160 = 49;
+ repeated string field17168 = 32;
+ repeated string field17170 = 34;
+ repeated .benchmarks.google_message3.Message0 field17172 = 509;
+ repeated string field17174 = 39;
+ repeated .benchmarks.google_message3.Message0 field17175 = 40;
+ repeated .benchmarks.google_message3.Message0 field17178 = 511;
+ repeated .benchmarks.google_message3.Message0 field17185 = 50;
+ repeated int32 field17207 = 1081;
+ repeated .benchmarks.google_message3.Message0 field17238 = 184;
+ repeated .benchmarks.google_message3.Message0 field17289 = 177;
+ repeated .benchmarks.google_message3.Message0 field17290 = 178;
+ repeated .benchmarks.google_message3.Message0 field17296 = 474;
+ repeated string field17298 = 44;
+ repeated .benchmarks.google_message3.Message0 field17301 = 47;
+ optional .benchmarks.google_message3.Message0 field17412 = 21;
+ repeated .benchmarks.google_message3.Message0 field17438 = 132;
+ repeated .benchmarks.google_message3.Message0 field17458 = 512;
+ repeated string field17460 = 560;
+ repeated string field17466 = 552;
+ repeated .benchmarks.google_message3.Message0 field17617 = 1080;
+ repeated int32 field17618 = 1084;
+}
+
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_1.proto b/benchmarks/datasets/google_message3/benchmark_message3_1.proto
new file mode 100644
index 00000000..3219553c
--- /dev/null
+++ b/benchmarks/datasets/google_message3/benchmark_message3_1.proto
@@ -0,0 +1,1280 @@
+syntax = "proto2";
+
+import "datasets/google_message3/benchmark_message3_2.proto";
+import "datasets/google_message3/benchmark_message3_3.proto";
+import "datasets/google_message3/benchmark_message3_5.proto";
+import "datasets/google_message3/benchmark_message3_7.proto";
+import "datasets/google_message3/benchmark_message3_8.proto";
+package benchmarks.google_message3;
+
+option cc_enable_arenas = true;
+option java_package = "com.google.protobuf.benchmarks";
+
+message Message34390 {
+ repeated .benchmarks.google_message3.Message34387 field34452 = 1;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message34390 field34453 = 92144610;
+ }
+}
+
+message Message34624 {
+ optional .benchmarks.google_message3.Message34621 field34683 = 1;
+ optional .benchmarks.google_message3.Message34621 field34684 = 2;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message34624 field34685 = 18178548;
+ }
+}
+
+message Message34791 {
+ optional fixed64 field34793 = 1;
+ repeated group Message34792 = 2 {
+ required string field34808 = 3;
+ optional string field34809 = 4;
+ }
+ optional int32 field34795 = 5;
+ optional int32 field34796 = 6;
+ optional int32 field34797 = 7;
+ optional int32 field34798 = 8;
+ optional int32 field34799 = 9;
+ optional int32 field34800 = 10;
+ optional bool field34801 = 11;
+ optional float field34802 = 12;
+ optional int32 field34803 = 13;
+ optional string field34804 = 14;
+ optional int64 field34805 = 15;
+ repeated fixed64 field34806 = 17 [packed = true];
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message34791 field34807 = 6330340;
+ }
+}
+
+message Message35483 {
+ optional int32 field35499 = 1;
+ optional string field35500 = 2;
+ optional string field35501 = 3;
+ optional string field35502 = 4;
+ repeated .benchmarks.google_message3.Message35476 field35503 = 5;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field35504 = 6;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message35483 field35505 = 7913554;
+ }
+}
+
+message Message35807 {
+ optional int32 field35810 = 1;
+ optional int32 field35811 = 2;
+ optional int32 field35812 = 3;
+ optional int32 field35813 = 4;
+ optional int32 field35814 = 5;
+ optional int32 field35815 = 6;
+ optional int32 field35816 = 7;
+ optional int32 field35817 = 8;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message35807 field35818 = 3803299;
+ }
+}
+
+message Message37487 {
+ optional bytes field37501 = 2;
+ optional bool field37502 = 3;
+}
+
+message Message13062 {
+ optional int64 field13075 = 1;
+ optional string field13076 = 2;
+ optional int32 field13077 = 3;
+ optional string field13078 = 4;
+ optional int32 field13079 = 5;
+}
+
+message Message952 {
+ repeated .benchmarks.google_message3.Message949 field963 = 1;
+}
+
+message Message36876 {
+ optional .benchmarks.google_message3.Message2356 field36980 = 1;
+ repeated group Message36877 = 111 {
+ required string field37044 = 112;
+ optional int32 field37045 = 113;
+ optional bytes field37046 = 114;
+ optional int32 field37047 = 115;
+ optional int32 field37048 = 157;
+ }
+ repeated group Message36878 = 168 {
+ }
+ repeated group Message36879 = 55 {
+ required string field37050 = 56;
+ optional int32 field37051 = 69;
+ }
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field36984 = 78;
+ optional group Message36880 = 137 {
+ }
+ optional uint64 field36986 = 59;
+ optional bytes field36987 = 121;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field36988 = 2;
+ optional .benchmarks.google_message3.Message7029 field36989 = 118;
+ optional .benchmarks.google_message3.Message35573 field36990 = 11;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field36991 = 21;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field36992 = 22;
+ optional float field36993 = 13;
+ optional int32 field36994 = 20;
+ optional bool field36995 = 51;
+ optional bool field36996 = 57;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field36997 = 100;
+ optional int32 field36998 = 47;
+ optional int32 field36999 = 48;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37000 = 68;
+ repeated group Message36881 = 23 {
+ }
+ optional .benchmarks.google_message3.Message4144 field37002 = 125;
+ repeated group Message36882 = 35 {
+ }
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37004 = 49;
+ optional .benchmarks.google_message3.Message18921 field37005 = 52;
+ optional .benchmarks.google_message3.Message36858 field37006 = 46;
+ optional .benchmarks.google_message3.Message18831 field37007 = 54;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37008 = 58;
+ optional .benchmarks.google_message3.Message18283 field37009 = 10;
+ optional string field37010 = 44;
+ optional string field37011 = 103;
+ optional .benchmarks.google_message3.Message0 field37012 = 43;
+ optional .benchmarks.google_message3.Message0 field37013 = 143;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37014 = 53;
+ optional .benchmarks.google_message3.Message36869 field37015 = 15;
+ optional group Message36883 = 3 {
+ }
+ repeated group Message36884 = 16 {
+ }
+ repeated group Message36885 = 27 {
+ }
+ optional group Message36886 = 32 {
+ }
+ repeated .benchmarks.google_message3.UnusedEnum field37020 = 71;
+ repeated int32 field37021 = 70;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37022 = 66;
+ optional .benchmarks.google_message3.Message13090 field37023 = 67;
+ optional group Message36887 = 62 {
+ }
+ repeated .benchmarks.google_message3.Message10155 field37025 = 50;
+ repeated .benchmarks.google_message3.Message11874 field37026 = 151;
+ optional string field37027 = 12;
+ optional int64 field37028 = 72;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37029 = 73;
+ optional .benchmarks.google_message3.Message35546 field37030 = 108;
+ optional group Message36888 = 74 {
+ optional uint64 field37089 = 75;
+ optional bool field37090 = 76;
+ optional uint64 field37091 = 165;
+ optional double field37092 = 166;
+ optional uint64 field37093 = 109;
+ optional bytes field37094 = 122;
+ }
+ repeated .benchmarks.google_message3.Message19255 field37032 = 104;
+ optional .benchmarks.google_message3.Message33968 field37033 = 105;
+ optional bool field37034 = 106;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field37035 = 107;
+ optional .benchmarks.google_message3.Message6644 field37036 = 110;
+ optional bytes field37037 = 133;
+ optional group Message36889 = 116 {
+ optional int64 field37095 = 117;
+ optional string field37096 = 145;
+ optional int32 field37097 = 123;
+ optional bool field37098 = 163;
+ optional int32 field37099 = 164;
+ optional int32 field37100 = 149;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37101 = 129;
+ optional .benchmarks.google_message3.Message13174 field37102 = 124;
+ optional .benchmarks.google_message3.Message13169 field37103 = 128;
+ optional uint64 field37104 = 132;
+ repeated .benchmarks.google_message3.Enum36890 field37105 = 131;
+ optional bool field37106 = 134;
+ optional bool field37107 = 140;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37108 = 135;
+ optional float field37109 = 136;
+ optional float field37110 = 156;
+ optional bool field37111 = 142;
+ optional int64 field37112 = 167;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37113 = 146;
+ optional bool field37114 = 148;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37115 = 154;
+ optional .benchmarks.google_message3.UnusedEnum field37116 = 158;
+ repeated .benchmarks.google_message3.UnusedEnum field37117 = 159;
+ optional int32 field37118 = 160;
+ repeated string field37119 = 161;
+ }
+ repeated group Message36910 = 119 {
+ }
+ optional group Message36911 = 126 {
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37121 = 127;
+ optional .benchmarks.google_message3.Message35538 field37122 = 130;
+ optional .benchmarks.google_message3.Message35540 field37123 = 144;
+ optional .benchmarks.google_message3.Message35542 field37124 = 150;
+ }
+ optional group Message36912 = 152 {
+ optional .benchmarks.google_message3.Message3901 field37125 = 153;
+ optional .benchmarks.google_message3.Message3901 field37126 = 162;
+ }
+ optional .benchmarks.google_message3.UnusedEmptyMessage field37042 = 155;
+}
+
+message Message1328 {
+}
+
+message Message6850 {
+}
+
+message Message6863 {
+ optional .benchmarks.google_message3.Enum6858 field6931 = 1;
+ optional .benchmarks.google_message3.Enum6858 field6932 = 2;
+ optional .benchmarks.google_message3.UnusedEnum field6933 = 36;
+ optional bool field6934 = 27;
+ optional .benchmarks.google_message3.Message6773 field6935 = 26;
+ optional int32 field6936 = 30;
+ optional int32 field6937 = 37;
+ optional .benchmarks.google_message3.Enum6815 field6938 = 31;
+ optional string field6939 = 3;
+ optional int32 field6940 = 4;
+ optional .benchmarks.google_message3.Enum6822 field6941 = 15;
+ optional bool field6942 = 10;
+ optional bool field6943 = 17;
+ optional float field6944 = 18;
+ optional float field6945 = 19;
+ optional int32 field6946 = 5;
+ optional int32 field6947 = 6;
+ optional bool field6948 = 7;
+ optional int32 field6949 = 12;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6950 = 8;
+ optional uint64 field6951 = 9;
+ optional string field6952 = 11;
+ optional bytes field6953 = 13;
+ optional int32 field6954 = 14;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6955 = 16;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6956 = 22;
+ optional .benchmarks.google_message3.Message3886 field6957 = 38;
+ optional string field6958 = 20;
+ optional uint32 field6959 = 21;
+ optional .benchmarks.google_message3.Message6743 field6960 = 23;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6961 = 29;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6962 = 33;
+ optional bool field6963 = 34;
+}
+
+message Message6871 {
+}
+
+message Message7547 {
+ required bytes field7549 = 1;
+ required int32 field7550 = 2;
+}
+
+message Message7648 {
+ optional string field7669 = 1;
+ optional int32 field7670 = 2;
+ optional int32 field7671 = 3;
+ optional int32 field7672 = 4;
+ optional int32 field7673 = 5;
+ optional int32 field7674 = 6;
+ optional float field7675 = 7;
+ optional bool field7676 = 8;
+ optional bool field7677 = 9;
+ optional bool field7678 = 10;
+ optional bool field7679 = 11;
+ optional bool field7680 = 12;
+}
+
+message Message7865 {
+}
+
+message Message7928 {
+ optional string field7940 = 1;
+ optional int64 field7941 = 2;
+}
+
+message Message7919 {
+ optional fixed64 field7931 = 1;
+ optional int64 field7932 = 2;
+ optional bytes field7933 = 3;
+}
+
+message Message7920 {
+ optional int64 field7934 = 1;
+ optional int64 field7935 = 2;
+}
+
+message Message7921 {
+ optional int32 field7936 = 1;
+ optional int64 field7937 = 2;
+ optional float field7938 = 3;
+ optional .benchmarks.google_message3.UnusedEnum field7939 = 4;
+}
+
+message Message8511 {
+ optional .benchmarks.google_message3.Message8224 field8539 = 1;
+ optional string field8540 = 2;
+ optional bool field8541 = 3;
+ optional int64 field8542 = 4;
+ optional string field8543 = 5;
+}
+
+message Message8512 {
+ optional .benchmarks.google_message3.Message8301 field8544 = 1;
+ optional .benchmarks.google_message3.Message8302 field8545 = 2;
+ optional string field8546 = 3;
+ optional bool field8547 = 4;
+ optional int64 field8548 = 5;
+ optional string field8549 = 6;
+}
+
+message Message8513 {
+ repeated .benchmarks.google_message3.Message8392 field8550 = 1;
+ optional string field8551 = 2;
+ optional bool field8552 = 3;
+ optional string field8553 = 4;
+}
+
+message Message8514 {
+ optional string field8554 = 1;
+ optional int64 field8555 = 2;
+ optional bool field8556 = 3;
+ repeated .benchmarks.google_message3.Message8130 field8557 = 4;
+ optional string field8558 = 5;
+}
+
+message Message8515 {
+ optional .benchmarks.google_message3.Message8479 field8559 = 1;
+ optional .benchmarks.google_message3.Message8478 field8560 = 2;
+ optional string field8561 = 3;
+}
+
+message Message10320 {
+ optional .benchmarks.google_message3.Enum10335 field10347 = 1;
+ repeated .benchmarks.google_message3.Message10319 field10348 = 2;
+ optional int32 field10349 = 3;
+ optional int32 field10350 = 4;
+ optional int32 field10351 = 5;
+ optional int32 field10352 = 6;
+ optional .benchmarks.google_message3.Enum10337 field10353 = 7;
+}
+
+message Message10321 {
+ optional int32 field10354 = 1;
+ optional int32 field10355 = 2;
+ optional uint64 field10356 = 3;
+}
+
+message Message10322 {
+ optional .benchmarks.google_message3.Message4016 field10357 = 1;
+ optional bool field10358 = 2;
+ optional bool field10359 = 3;
+}
+
+message Message11988 {
+ optional string field12021 = 1;
+ optional string field12022 = 2;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field12023 = 3;
+ optional .benchmarks.google_message3.Message10155 field12024 = 4;
+}
+
+message Message12668 {
+ repeated .benchmarks.google_message3.Message12669 field12677 = 1;
+ optional int32 field12678 = 2;
+ optional int32 field12679 = 3;
+ optional int32 field12680 = 4;
+}
+
+message Message12825 {
+ repeated .benchmarks.google_message3.Message12818 field12862 = 1;
+ optional int32 field12863 = 2;
+ optional .benchmarks.google_message3.Message12819 field12864 = 3;
+ optional .benchmarks.google_message3.Message12820 field12865 = 4;
+ optional int32 field12866 = 5;
+ repeated .benchmarks.google_message3.Message12821 field12867 = 6;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field12868 = 7;
+}
+
+message Message16478 {
+ repeated .benchmarks.google_message3.Message16479 field16481 = 1;
+ optional bool field16482 = 3;
+ optional int32 field16483 = 2;
+}
+
+message Message16552 {
+ optional fixed64 field16565 = 1;
+ optional int32 field16566 = 2;
+ optional .benchmarks.google_message3.Enum16553 field16567 = 3;
+}
+
+message Message16660 {
+ optional string field16668 = 1;
+ optional string field16669 = 2;
+ optional int32 field16670 = 3;
+}
+
+message Message16727 {
+ required .benchmarks.google_message3.Enum16728 field16782 = 1;
+ required string field16783 = 2;
+ optional string field16784 = 3;
+ optional int32 field16785 = 23;
+ required string field16786 = 4;
+ optional string field16787 = 5;
+ optional string field16788 = 6;
+ required .benchmarks.google_message3.Enum16732 field16789 = 7;
+ optional string field16790 = 8;
+ optional string field16791 = 9;
+ optional string field16792 = 10;
+ optional .benchmarks.google_message3.Enum16738 field16793 = 11;
+ optional int32 field16794 = 12;
+ repeated .benchmarks.google_message3.Message16722 field16795 = 13;
+ optional bool field16796 = 19;
+ optional bool field16797 = 24;
+ optional string field16798 = 14;
+ optional int64 field16799 = 15;
+ optional bool field16800 = 16;
+ optional string field16801 = 17;
+ optional .benchmarks.google_message3.Enum16698 field16802 = 18;
+ optional .benchmarks.google_message3.Message16724 field16803 = 20;
+ optional bool field16804 = 22;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field16805 = 25;
+ extensions 1000 to 536870911;
+}
+
+message Message16725 {
+ optional .benchmarks.google_message3.Enum16728 field16774 = 1;
+ repeated string field16775 = 2;
+}
+
+message Message17726 {
+ optional string field17801 = 1;
+ repeated string field17802 = 2;
+ optional string field17803 = 3;
+ repeated string field17804 = 4;
+ optional string field17805 = 5;
+ repeated string field17806 = 6;
+ optional string field17807 = 7;
+ optional string field17808 = 8;
+ repeated string field17809 = 15;
+ repeated string field17810 = 16;
+ repeated string field17811 = 17;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field17812 = 18;
+ optional string field17813 = 9;
+ optional string field17814 = 10;
+ optional string field17815 = 11;
+ optional string field17816 = 12;
+ optional string field17817 = 13;
+ optional string field17818 = 14;
+ optional string field17819 = 19;
+ repeated .benchmarks.google_message3.Message17728 field17820 = 20;
+ repeated .benchmarks.google_message3.Message17728 field17821 = 21;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field17822 = 30;
+}
+
+message Message17782 {
+ optional string field18153 = 1;
+ optional string field18154 = 2;
+}
+
+message Message17783 {
+ optional string field18155 = 1;
+ optional string field18156 = 2;
+ optional string field18157 = 3;
+ repeated group Message17784 = 4 {
+ optional string field18162 = 5;
+ optional string field18163 = 6;
+ optional string field18164 = 7;
+ repeated string field18165 = 8;
+ optional string field18166 = 17;
+ optional string field18167 = 18;
+ }
+ repeated group Message17785 = 9 {
+ optional string field18168 = 10;
+ optional string field18169 = 11;
+ optional .benchmarks.google_message3.Message17783 field18170 = 12;
+ optional string field18171 = 13;
+ optional string field18172 = 14;
+ repeated string field18173 = 15;
+ }
+ repeated string field18160 = 16;
+}
+
+message Message16945 {
+ optional string field16946 = 1;
+ optional string field16947 = 2;
+ optional string field16948 = 3;
+ optional string field16949 = 4;
+ optional string field16950 = 5;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field16951 = 872;
+ repeated .benchmarks.google_message3.Message0 field16952 = 16;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16953 = 54;
+ repeated .benchmarks.google_message3.Message0 field16954 = 55;
+ repeated string field16955 = 58;
+ repeated string field16956 = 59;
+ repeated string field16957 = 62;
+ repeated string field16958 = 37;
+ repeated string field16959 = 18;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16960 = 38;
+ repeated .benchmarks.google_message3.Message0 field16961 = 67;
+ repeated .benchmarks.google_message3.Message0 field16962 = 130;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16963 = 136;
+ repeated string field16964 = 138;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16965 = 156;
+ repeated string field16966 = 139;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16967 = 126;
+ repeated string field16968 = 152;
+ repeated .benchmarks.google_message3.Message0 field16969 = 183;
+ repeated string field16970 = 168;
+ repeated string field16971 = 212;
+ repeated string field16972 = 213;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16973 = 189;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16974 = 190;
+ repeated string field16975 = 191;
+ repeated string field16976 = 192;
+ repeated .benchmarks.google_message3.Message0 field16977 = 193;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16978 = 194;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16979 = 195;
+ repeated int32 field16980 = 196;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16981 = 95;
+ repeated string field16982 = 96;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16983 = 97;
+ repeated string field16984 = 1086;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16985 = 98;
+ repeated string field16986 = 99;
+ repeated string field16987 = 100;
+ repeated string field16988 = 48;
+ optional string field16989 = 22;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field16990 = 51;
+ repeated string field16991 = 81;
+ repeated string field16992 = 85;
+ repeated string field16993 = 169;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field16994 = 260;
+ optional int32 field16995 = 198;
+ optional int32 field16996 = 204;
+ optional string field16997 = 1087;
+ repeated string field16998 = 197;
+ repeated string field16999 = 206;
+ optional string field17000 = 211;
+ repeated string field17001 = 205;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field17002 = 68;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field17003 = 69;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field17004 = 70;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field17005 = 71;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field17006 = 72;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field17007 = 19;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field17008 = 24;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field17009 = 23;
+ repeated .benchmarks.google_message3.Message0 field17010 = 131;
+ repeated string field17011 = 133;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field17012 = 142;
+ repeated string field17013 = 143;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field17014 = 153;
+ repeated .benchmarks.google_message3.Message0 field17015 = 170;
+ repeated string field17016 = 171;
+ repeated string field17017 = 172;
+ repeated string field17018 = 173;
+ repeated string field17019 = 174;
+ repeated string field17020 = 175;
+ repeated string field17021 = 186;
+ repeated string field17022 = 101;
+ repeated .benchmarks.google_message3.Message0 field17023 = 102;
+ repeated string field17024 = 274;
+ extensions 17 to 17;
+ extensions 21 to 21;
+ extensions 25 to 25;
+ extensions 27 to 27;
+ extensions 29 to 29;
+ extensions 30 to 30;
+ extensions 31 to 31;
+ extensions 32 to 32;
+ extensions 33 to 33;
+ extensions 34 to 34;
+ extensions 35 to 35;
+ extensions 36 to 36;
+ extensions 39 to 39;
+ extensions 40 to 40;
+ extensions 41 to 41;
+ extensions 42 to 42;
+ extensions 43 to 43;
+ extensions 44 to 44;
+ extensions 45 to 45;
+ extensions 46 to 46;
+ extensions 47 to 47;
+ extensions 49 to 49;
+ extensions 50 to 50;
+ extensions 52 to 52;
+ extensions 53 to 53;
+ extensions 56 to 56;
+ extensions 57 to 57;
+ extensions 60 to 60;
+ extensions 61 to 61;
+ extensions 63 to 63;
+ extensions 64 to 64;
+ extensions 65 to 65;
+ extensions 66 to 66;
+ extensions 73 to 73;
+ extensions 74 to 74;
+ extensions 75 to 75;
+ extensions 76 to 76;
+ extensions 77 to 77;
+ extensions 78 to 78;
+ extensions 79 to 79;
+ extensions 80 to 80;
+ extensions 82 to 82;
+ extensions 83 to 83;
+ extensions 84 to 84;
+ extensions 86 to 86;
+ extensions 87 to 87;
+ extensions 88 to 88;
+ extensions 89 to 89;
+ extensions 90 to 90;
+ extensions 91 to 91;
+ extensions 92 to 92;
+ extensions 93 to 93;
+ extensions 94 to 94;
+ extensions 103 to 103;
+ extensions 104 to 104;
+ extensions 105 to 105;
+ extensions 106 to 106;
+ extensions 107 to 107;
+ extensions 108 to 108;
+ extensions 109 to 109;
+ extensions 110 to 110;
+ extensions 111 to 111;
+ extensions 112 to 112;
+ extensions 113 to 113;
+ extensions 114 to 114;
+ extensions 115 to 115;
+ extensions 116 to 116;
+ extensions 117 to 117;
+ extensions 118 to 118;
+ extensions 119 to 119;
+ extensions 120 to 120;
+ extensions 121 to 121;
+ extensions 122 to 122;
+ extensions 123 to 123;
+ extensions 124 to 124;
+ extensions 125 to 125;
+ extensions 127 to 127;
+ extensions 128 to 128;
+ extensions 129 to 129;
+ extensions 132 to 132;
+ extensions 134 to 134;
+ extensions 135 to 135;
+ extensions 137 to 137;
+ extensions 140 to 140;
+ extensions 141 to 141;
+ extensions 144 to 144;
+ extensions 145 to 145;
+ extensions 146 to 146;
+ extensions 147 to 147;
+ extensions 148 to 148;
+ extensions 149 to 149;
+ extensions 150 to 150;
+ extensions 151 to 151;
+ extensions 154 to 154;
+ extensions 155 to 155;
+ extensions 157 to 157;
+ extensions 158 to 158;
+ extensions 159 to 159;
+ extensions 160 to 160;
+ extensions 161 to 161;
+ extensions 162 to 162;
+ extensions 163 to 163;
+ extensions 164 to 164;
+ extensions 165 to 165;
+ extensions 166 to 166;
+ extensions 167 to 167;
+ extensions 176 to 176;
+ extensions 177 to 177;
+ extensions 178 to 178;
+ extensions 179 to 179;
+ extensions 180 to 180;
+ extensions 181 to 181;
+ extensions 182 to 182;
+ extensions 184 to 184;
+ extensions 185 to 185;
+ extensions 187 to 187;
+ extensions 188 to 188;
+ extensions 199 to 199;
+ extensions 200 to 200;
+ extensions 201 to 201;
+ extensions 202 to 202;
+ extensions 203 to 203;
+ extensions 207 to 207;
+ extensions 208 to 208;
+ extensions 209 to 209;
+ extensions 210 to 210;
+ extensions 214 to 214;
+ extensions 215 to 215;
+ extensions 216 to 216;
+ extensions 217 to 217;
+ extensions 218 to 218;
+ extensions 219 to 219;
+ extensions 220 to 220;
+ extensions 221 to 221;
+ extensions 222 to 222;
+ extensions 223 to 223;
+ extensions 224 to 224;
+ extensions 225 to 225;
+ extensions 226 to 226;
+ extensions 227 to 227;
+ extensions 228 to 228;
+ extensions 229 to 229;
+ extensions 230 to 230;
+ extensions 231 to 231;
+ extensions 232 to 232;
+ extensions 233 to 233;
+ extensions 234 to 234;
+ extensions 235 to 235;
+ extensions 236 to 236;
+ extensions 237 to 237;
+ extensions 238 to 238;
+ extensions 239 to 239;
+ extensions 240 to 240;
+ extensions 241 to 241;
+ extensions 242 to 242;
+ extensions 243 to 243;
+ extensions 244 to 244;
+ extensions 245 to 245;
+ extensions 246 to 246;
+ extensions 247 to 247;
+ extensions 248 to 248;
+ extensions 249 to 249;
+ extensions 250 to 250;
+ extensions 251 to 251;
+ extensions 252 to 252;
+ extensions 253 to 253;
+ extensions 254 to 254;
+ extensions 255 to 255;
+ extensions 256 to 256;
+ extensions 257 to 257;
+ extensions 258 to 258;
+ extensions 259 to 259;
+ extensions 261 to 261;
+ extensions 262 to 262;
+ extensions 263 to 263;
+ extensions 264 to 264;
+ extensions 265 to 265;
+ extensions 266 to 266;
+ extensions 267 to 267;
+ extensions 268 to 268;
+ extensions 269 to 269;
+ extensions 270 to 270;
+ extensions 271 to 271;
+ extensions 272 to 272;
+ extensions 273 to 273;
+ extensions 275 to 275;
+ extensions 276 to 276;
+ extensions 277 to 277;
+ extensions 278 to 278;
+ extensions 279 to 279;
+ extensions 280 to 280;
+ extensions 281 to 281;
+ extensions 282 to 282;
+ extensions 283 to 283;
+ extensions 284 to 284;
+ extensions 285 to 285;
+ extensions 286 to 286;
+ extensions 290 to 290;
+ extensions 291 to 291;
+ extensions 292 to 292;
+ extensions 293 to 293;
+ extensions 294 to 294;
+ extensions 295 to 295;
+ extensions 296 to 296;
+ extensions 297 to 297;
+ extensions 298 to 298;
+ extensions 299 to 299;
+ extensions 300 to 300;
+ extensions 301 to 301;
+ extensions 302 to 302;
+ extensions 303 to 303;
+ extensions 304 to 304;
+ extensions 305 to 305;
+ extensions 306 to 306;
+ extensions 307 to 307;
+ extensions 308 to 308;
+ extensions 309 to 309;
+ extensions 310 to 310;
+ extensions 311 to 311;
+ extensions 312 to 312;
+ extensions 313 to 313;
+ extensions 314 to 314;
+ extensions 315 to 315;
+ extensions 316 to 316;
+ extensions 317 to 317;
+ extensions 318 to 318;
+ extensions 319 to 319;
+ extensions 320 to 320;
+ extensions 321 to 321;
+ extensions 322 to 322;
+ extensions 323 to 323;
+ extensions 324 to 324;
+ extensions 325 to 325;
+ extensions 326 to 326;
+ extensions 327 to 327;
+ extensions 328 to 328;
+ extensions 329 to 329;
+ extensions 330 to 330;
+ extensions 331 to 331;
+ extensions 332 to 332;
+ extensions 333 to 333;
+ extensions 334 to 334;
+ extensions 335 to 335;
+ extensions 336 to 336;
+ extensions 337 to 337;
+ extensions 338 to 338;
+ extensions 339 to 339;
+ extensions 340 to 340;
+ extensions 341 to 341;
+ extensions 342 to 342;
+ extensions 343 to 343;
+ extensions 344 to 344;
+ extensions 345 to 345;
+ extensions 346 to 346;
+ extensions 347 to 347;
+ extensions 348 to 348;
+ extensions 349 to 349;
+ extensions 350 to 350;
+ extensions 351 to 351;
+ extensions 352 to 352;
+ extensions 353 to 353;
+ extensions 354 to 354;
+ extensions 355 to 355;
+ extensions 356 to 356;
+ extensions 357 to 357;
+ extensions 358 to 358;
+ extensions 359 to 359;
+ extensions 360 to 360;
+ extensions 361 to 361;
+ extensions 362 to 362;
+ extensions 363 to 363;
+ extensions 364 to 364;
+ extensions 365 to 365;
+ extensions 366 to 366;
+ extensions 367 to 367;
+ extensions 368 to 368;
+ extensions 369 to 369;
+ extensions 370 to 370;
+ extensions 371 to 371;
+ extensions 372 to 372;
+ extensions 373 to 373;
+ extensions 374 to 374;
+ extensions 375 to 375;
+ extensions 376 to 376;
+ extensions 377 to 377;
+ extensions 378 to 378;
+ extensions 379 to 379;
+ extensions 380 to 380;
+ extensions 381 to 381;
+ extensions 382 to 382;
+ extensions 383 to 383;
+ extensions 384 to 384;
+ extensions 385 to 385;
+ extensions 386 to 386;
+ extensions 387 to 387;
+ extensions 388 to 388;
+ extensions 389 to 389;
+ extensions 390 to 390;
+ extensions 391 to 391;
+ extensions 392 to 392;
+ extensions 393 to 393;
+ extensions 394 to 394;
+ extensions 395 to 395;
+ extensions 396 to 396;
+ extensions 397 to 397;
+ extensions 398 to 398;
+ extensions 399 to 399;
+ extensions 400 to 400;
+ extensions 401 to 401;
+ extensions 402 to 402;
+ extensions 403 to 403;
+ extensions 404 to 404;
+ extensions 405 to 405;
+ extensions 406 to 406;
+ extensions 407 to 407;
+ extensions 408 to 408;
+ extensions 409 to 409;
+ extensions 410 to 410;
+ extensions 411 to 411;
+ extensions 412 to 412;
+ extensions 413 to 413;
+ extensions 414 to 414;
+ extensions 415 to 415;
+ extensions 416 to 416;
+ extensions 417 to 417;
+ extensions 418 to 418;
+ extensions 419 to 419;
+ extensions 420 to 420;
+ extensions 421 to 421;
+ extensions 422 to 422;
+ extensions 423 to 423;
+ extensions 424 to 424;
+ extensions 425 to 425;
+ extensions 426 to 426;
+ extensions 427 to 427;
+ extensions 428 to 428;
+ extensions 429 to 429;
+ extensions 430 to 430;
+ extensions 431 to 431;
+ extensions 432 to 432;
+ extensions 433 to 433;
+ extensions 434 to 434;
+ extensions 435 to 435;
+ extensions 436 to 436;
+ extensions 437 to 437;
+ extensions 438 to 438;
+ extensions 439 to 439;
+ extensions 440 to 440;
+ extensions 441 to 441;
+ extensions 442 to 442;
+ extensions 443 to 443;
+ extensions 444 to 444;
+ extensions 445 to 445;
+ extensions 446 to 446;
+ extensions 447 to 447;
+ extensions 448 to 448;
+ extensions 449 to 449;
+ extensions 450 to 450;
+ extensions 451 to 451;
+ extensions 452 to 452;
+ extensions 453 to 453;
+ extensions 454 to 454;
+ extensions 455 to 455;
+ extensions 456 to 456;
+ extensions 457 to 457;
+ extensions 458 to 458;
+ extensions 459 to 459;
+ extensions 460 to 460;
+ extensions 461 to 461;
+ extensions 462 to 462;
+ extensions 463 to 463;
+ extensions 464 to 464;
+ extensions 465 to 465;
+ extensions 466 to 466;
+ extensions 467 to 467;
+ extensions 468 to 468;
+ extensions 469 to 469;
+ extensions 470 to 470;
+ extensions 471 to 471;
+ extensions 472 to 472;
+ extensions 473 to 473;
+ extensions 474 to 474;
+ extensions 509 to 509;
+ extensions 511 to 511;
+ extensions 512 to 512;
+ extensions 513 to 513;
+ extensions 514 to 514;
+ extensions 515 to 515;
+ extensions 516 to 516;
+ extensions 517 to 517;
+ extensions 518 to 518;
+ extensions 519 to 519;
+ extensions 520 to 520;
+ extensions 521 to 521;
+ extensions 522 to 522;
+ extensions 523 to 523;
+ extensions 524 to 524;
+ extensions 525 to 525;
+ extensions 526 to 526;
+ extensions 527 to 527;
+ extensions 528 to 528;
+ extensions 529 to 529;
+ extensions 530 to 530;
+ extensions 531 to 531;
+ extensions 532 to 532;
+ extensions 533 to 533;
+ extensions 534 to 534;
+ extensions 535 to 535;
+ extensions 536 to 536;
+ extensions 537 to 537;
+ extensions 538 to 538;
+ extensions 539 to 539;
+ extensions 540 to 540;
+ extensions 541 to 541;
+ extensions 542 to 542;
+ extensions 543 to 543;
+ extensions 544 to 544;
+ extensions 545 to 545;
+ extensions 546 to 546;
+ extensions 547 to 547;
+ extensions 548 to 548;
+ extensions 549 to 549;
+ extensions 550 to 550;
+ extensions 551 to 551;
+ extensions 552 to 552;
+ extensions 553 to 553;
+ extensions 554 to 554;
+ extensions 555 to 555;
+ extensions 556 to 556;
+ extensions 557 to 557;
+ extensions 558 to 558;
+ extensions 559 to 559;
+ extensions 560 to 560;
+ extensions 561 to 561;
+ extensions 562 to 562;
+ extensions 563 to 563;
+ extensions 564 to 564;
+ extensions 565 to 565;
+ extensions 566 to 566;
+ extensions 567 to 567;
+ extensions 568 to 568;
+ extensions 569 to 569;
+ extensions 570 to 570;
+ extensions 571 to 571;
+ extensions 572 to 572;
+ extensions 573 to 573;
+ extensions 574 to 574;
+ extensions 575 to 575;
+ extensions 576 to 576;
+ extensions 577 to 577;
+ extensions 578 to 578;
+ extensions 579 to 579;
+ extensions 580 to 580;
+ extensions 581 to 581;
+ extensions 582 to 582;
+ extensions 583 to 583;
+ extensions 584 to 584;
+ extensions 585 to 585;
+ extensions 586 to 586;
+ extensions 587 to 587;
+ extensions 588 to 588;
+ extensions 589 to 589;
+ extensions 590 to 590;
+ extensions 604 to 604;
+ extensions 605 to 605;
+ extensions 606 to 606;
+ extensions 607 to 607;
+ extensions 608 to 608;
+ extensions 609 to 609;
+ extensions 610 to 610;
+ extensions 611 to 611;
+ extensions 612 to 612;
+ extensions 613 to 613;
+ extensions 614 to 614;
+ extensions 615 to 615;
+ extensions 616 to 616;
+ extensions 617 to 617;
+ extensions 618 to 618;
+ extensions 619 to 619;
+ extensions 620 to 620;
+ extensions 621 to 621;
+ extensions 622 to 622;
+ extensions 623 to 623;
+ extensions 624 to 624;
+ extensions 625 to 625;
+ extensions 626 to 626;
+ extensions 627 to 627;
+ extensions 628 to 628;
+ extensions 629 to 629;
+ extensions 813 to 813;
+ extensions 814 to 814;
+ extensions 815 to 815;
+ extensions 816 to 816;
+ extensions 817 to 817;
+ extensions 818 to 818;
+ extensions 819 to 819;
+ extensions 820 to 820;
+ extensions 821 to 821;
+ extensions 822 to 822;
+ extensions 823 to 823;
+ extensions 824 to 824;
+ extensions 827 to 827;
+ extensions 828 to 828;
+ extensions 829 to 829;
+ extensions 830 to 830;
+ extensions 831 to 831;
+ extensions 832 to 832;
+ extensions 833 to 833;
+ extensions 834 to 834;
+ extensions 835 to 835;
+ extensions 836 to 836;
+ extensions 837 to 837;
+ extensions 838 to 838;
+ extensions 839 to 839;
+ extensions 840 to 840;
+ extensions 841 to 841;
+ extensions 842 to 842;
+ extensions 843 to 843;
+ extensions 844 to 844;
+ extensions 845 to 845;
+ extensions 846 to 846;
+ extensions 847 to 847;
+ extensions 848 to 848;
+ extensions 849 to 849;
+ extensions 850 to 850;
+ extensions 851 to 851;
+ extensions 852 to 852;
+ extensions 853 to 853;
+ extensions 854 to 854;
+ extensions 855 to 855;
+ extensions 856 to 856;
+ extensions 857 to 857;
+ extensions 858 to 858;
+ extensions 859 to 859;
+ extensions 860 to 860;
+ extensions 861 to 861;
+ extensions 862 to 862;
+ extensions 863 to 863;
+ extensions 864 to 864;
+ extensions 865 to 865;
+ extensions 866 to 866;
+ extensions 867 to 867;
+ extensions 868 to 868;
+ extensions 869 to 869;
+ extensions 870 to 870;
+ extensions 871 to 871;
+ extensions 880 to 880;
+ extensions 881 to 881;
+ extensions 882 to 882;
+ extensions 883 to 883;
+ extensions 884 to 884;
+ extensions 885 to 885;
+ extensions 886 to 886;
+ extensions 887 to 887;
+ extensions 888 to 888;
+ extensions 890 to 890;
+ extensions 891 to 891;
+ extensions 892 to 892;
+ extensions 912 to 912;
+ extensions 914 to 914;
+ extensions 915 to 915;
+ extensions 916 to 916;
+ extensions 917 to 917;
+ extensions 918 to 918;
+ extensions 919 to 919;
+ extensions 920 to 920;
+ extensions 921 to 921;
+ extensions 922 to 922;
+ extensions 923 to 923;
+ extensions 924 to 924;
+ extensions 925 to 925;
+ extensions 926 to 926;
+ extensions 927 to 927;
+ extensions 928 to 928;
+ extensions 929 to 929;
+ extensions 930 to 930;
+ extensions 931 to 931;
+ extensions 932 to 932;
+ extensions 933 to 933;
+ extensions 934 to 934;
+ extensions 935 to 935;
+ extensions 936 to 936;
+ extensions 937 to 937;
+ extensions 938 to 938;
+ extensions 939 to 939;
+ extensions 940 to 940;
+ extensions 941 to 941;
+ extensions 942 to 942;
+ extensions 943 to 943;
+ extensions 944 to 944;
+ extensions 945 to 945;
+ extensions 946 to 946;
+ extensions 947 to 947;
+ extensions 949 to 949;
+ extensions 950 to 950;
+ extensions 951 to 951;
+ extensions 952 to 952;
+ extensions 954 to 954;
+ extensions 955 to 955;
+ extensions 956 to 956;
+ extensions 957 to 957;
+ extensions 958 to 958;
+ extensions 959 to 959;
+ extensions 960 to 960;
+ extensions 961 to 961;
+ extensions 962 to 962;
+ extensions 963 to 963;
+ extensions 964 to 964;
+ extensions 965 to 965;
+ extensions 966 to 966;
+ extensions 967 to 967;
+ extensions 968 to 968;
+ extensions 969 to 969;
+ extensions 970 to 970;
+ extensions 971 to 971;
+ extensions 972 to 972;
+ extensions 973 to 973;
+ extensions 974 to 974;
+ extensions 975 to 975;
+ extensions 976 to 976;
+ extensions 977 to 977;
+ extensions 978 to 978;
+ extensions 979 to 979;
+ extensions 980 to 980;
+ extensions 981 to 981;
+ extensions 982 to 982;
+ extensions 983 to 983;
+ extensions 984 to 984;
+ extensions 985 to 985;
+ extensions 987 to 987;
+ extensions 988 to 988;
+ extensions 1000 to 1000;
+ extensions 1001 to 1001;
+ extensions 1002 to 1002;
+ extensions 1003 to 1003;
+ extensions 1004 to 1004;
+ extensions 1005 to 1005;
+ extensions 1006 to 1006;
+ extensions 1007 to 1007;
+ extensions 1008 to 1008;
+ extensions 1009 to 1009;
+ extensions 1010 to 1010;
+ extensions 1011 to 1011;
+ extensions 1012 to 1012;
+ extensions 1013 to 1013;
+ extensions 1014 to 1014;
+ extensions 1015 to 1015;
+ extensions 1016 to 1016;
+ extensions 1017 to 1017;
+ extensions 1018 to 1018;
+ extensions 1019 to 1019;
+ extensions 1020 to 1020;
+ extensions 1021 to 1021;
+ extensions 1022 to 1022;
+ extensions 1023 to 1023;
+ extensions 1024 to 1024;
+ extensions 1025 to 1025;
+ extensions 1026 to 1026;
+ extensions 1027 to 1027;
+ extensions 1028 to 1028;
+ extensions 1029 to 1029;
+ extensions 1030 to 1030;
+ extensions 1031 to 1031;
+ extensions 1032 to 1032;
+ extensions 1033 to 1033;
+ extensions 1034 to 1034;
+ extensions 1035 to 1035;
+ extensions 1036 to 1036;
+ extensions 1037 to 1037;
+ extensions 1038 to 1038;
+ extensions 1039 to 1039;
+ extensions 1040 to 1040;
+ extensions 1041 to 1041;
+ extensions 1042 to 1042;
+ extensions 1043 to 1043;
+ extensions 1044 to 1044;
+ extensions 1045 to 1045;
+ extensions 1046 to 1046;
+ extensions 1047 to 1047;
+ extensions 1048 to 1048;
+ extensions 1049 to 1049;
+ extensions 1050 to 1050;
+ extensions 1051 to 1051;
+ extensions 1052 to 1052;
+ extensions 1053 to 1053;
+ extensions 1054 to 1054;
+ extensions 1055 to 1055;
+ extensions 1056 to 1056;
+ extensions 1057 to 1057;
+ extensions 1058 to 1058;
+ extensions 1079 to 1079;
+ extensions 1080 to 1080;
+ extensions 1081 to 1081;
+ extensions 1082 to 1082;
+ extensions 1083 to 1083;
+ extensions 1084 to 1084;
+ extensions 1085 to 1085;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message16945 field17025 = 22068132;
+ }
+}
+
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_2.proto b/benchmarks/datasets/google_message3/benchmark_message3_2.proto
new file mode 100644
index 00000000..7ab993ba
--- /dev/null
+++ b/benchmarks/datasets/google_message3/benchmark_message3_2.proto
@@ -0,0 +1,499 @@
+syntax = "proto2";
+
+import "datasets/google_message3/benchmark_message3_3.proto";
+import "datasets/google_message3/benchmark_message3_4.proto";
+import "datasets/google_message3/benchmark_message3_5.proto";
+import "datasets/google_message3/benchmark_message3_7.proto";
+import "datasets/google_message3/benchmark_message3_8.proto";
+package benchmarks.google_message3;
+
+option cc_enable_arenas = true;
+option java_package = "com.google.protobuf.benchmarks";
+
+message Message22853 {
+ optional .benchmarks.google_message3.Enum22854 field22869 = 1;
+ repeated uint32 field22870 = 2 [packed = true];
+ repeated float field22871 = 3 [packed = true];
+ repeated float field22872 = 5 [packed = true];
+ optional .benchmarks.google_message3.UnusedEmptyMessage field22873 = 4;
+}
+
+message Message24345 {
+ optional string field24533 = 1;
+ optional .benchmarks.google_message3.UnusedEnum field24534 = 22;
+ optional .benchmarks.google_message3.Message24346 field24535 = 2;
+ optional string field24536 = 3;
+ optional string field24537 = 4;
+ optional .benchmarks.google_message3.UnusedEnum field24538 = 23;
+ optional string field24539 = 5;
+ required string field24540 = 6;
+ optional string field24541 = 7;
+ optional string field24542 = 8;
+ optional .benchmarks.google_message3.Message24316 field24543 = 9;
+ optional .benchmarks.google_message3.Message24376 field24544 = 10;
+ optional string field24545 = 11;
+ optional string field24546 = 19;
+ optional string field24547 = 20;
+ optional string field24548 = 21;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24549 = 12;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24550 = 13;
+ repeated string field24551 = 14;
+ optional string field24552 = 15;
+ optional int32 field24553 = 18;
+ optional .benchmarks.google_message3.Message24379 field24554 = 16;
+ optional string field24555 = 17;
+ repeated .benchmarks.google_message3.Message24356 field24556 = 24;
+ repeated .benchmarks.google_message3.Message24366 field24557 = 25;
+}
+
+message Message24403 {
+ optional .benchmarks.google_message3.Message24401 field24681 = 1;
+ optional .benchmarks.google_message3.Message24402 field24682 = 2;
+}
+
+message Message24391 {
+ optional string field24631 = 1;
+ optional string field24632 = 2;
+ repeated string field24633 = 3;
+ optional string field24634 = 4;
+ repeated string field24635 = 5;
+ repeated string field24636 = 16;
+ optional string field24637 = 17;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24638 = 25;
+ optional string field24639 = 7;
+ optional string field24640 = 18;
+ optional string field24641 = 19;
+ optional string field24642 = 20;
+ optional int32 field24643 = 24;
+ optional .benchmarks.google_message3.Message24379 field24644 = 8;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field24645 = 9;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24646 = 10;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24647 = 11;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24648 = 12;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field24649 = 13;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24650 = 14;
+ optional string field24651 = 21;
+ optional int32 field24652 = 22;
+ optional int32 field24653 = 23;
+ repeated string field24654 = 15;
+ repeated string field24655 = 6;
+}
+
+message Message27454 {
+}
+
+message Message27357 {
+ optional string field27410 = 1;
+ optional float field27411 = 2;
+ optional string field27412 = 3;
+ optional bool field27413 = 4;
+ optional bool field27414 = 5;
+}
+
+message Message27360 {
+ optional .benchmarks.google_message3.Message27358 field27426 = 1;
+ optional .benchmarks.google_message3.Enum27361 field27427 = 2;
+ optional .benchmarks.google_message3.Message27358 field27428 = 3;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field27429 = 4;
+}
+
+message Message34387 {
+ optional string field34446 = 1;
+ repeated .benchmarks.google_message3.Message34381 field34447 = 2;
+ optional .benchmarks.google_message3.UnusedEnum field34448 = 3;
+ optional .benchmarks.google_message3.Enum34388 field34449 = 4;
+ optional int64 field34450 = 5;
+}
+
+message Message34621 {
+ optional double field34651 = 1;
+ optional double field34652 = 2;
+ optional double field34653 = 3;
+ optional double field34654 = 4;
+ optional double field34655 = 11;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field34656 = 13;
+ optional .benchmarks.google_message3.Message34619 field34657 = 14;
+ optional string field34658 = 5;
+ optional string field34659 = 9;
+ optional double field34660 = 12;
+ optional bytes field34661 = 19;
+ optional string field34662 = 15;
+ optional string field34663 = 16;
+ optional string field34664 = 17;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field34665 = 18;
+ optional .benchmarks.google_message3.Message34621 field34666 = 20;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field34667 = 100;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field34668 = 101;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message34621 field34669 = 17562023;
+ }
+}
+
+message Message35476 {
+ optional string field35484 = 1;
+ optional string field35485 = 2;
+ optional string field35486 = 3;
+ optional .benchmarks.google_message3.Enum35477 field35487 = 4;
+ optional float field35488 = 5;
+ optional float field35489 = 6;
+ optional float field35490 = 7;
+ optional float field35491 = 8;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field35492 = 9;
+ optional int32 field35493 = 10;
+ optional int32 field35494 = 11;
+ optional int32 field35495 = 12;
+ optional string field35496 = 13;
+ optional string field35497 = 14;
+}
+
+message Message949 {
+ optional string field955 = 1;
+ optional int64 field956 = 2;
+ optional int64 field957 = 3;
+ optional .benchmarks.google_message3.Message730 field958 = 4;
+ repeated string field959 = 5;
+ optional string field960 = 6;
+ optional bool field961 = 7;
+}
+
+message Message36869 {
+ optional int32 field36970 = 1;
+ optional int32 field36971 = 2;
+}
+
+message Message33968 {
+ repeated group Message33969 = 1 {
+ }
+ repeated .benchmarks.google_message3.Message33958 field33989 = 3;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field33990 = 106;
+ optional bool field33991 = 108;
+ optional .benchmarks.google_message3.UnusedEnum field33992 = 107;
+}
+
+message Message6644 {
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6701 = 8;
+ optional string field6702 = 1;
+ optional double field6703 = 2;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6704 = 9;
+ optional bytes field6705 = 3;
+ optional bytes field6706 = 19;
+ optional .benchmarks.google_message3.Message6637 field6707 = 4;
+ repeated .benchmarks.google_message3.Message6126 field6708 = 18;
+ optional bool field6709 = 6;
+ optional .benchmarks.google_message3.Message6643 field6710 = 10;
+ optional string field6711 = 12;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6712 = 14;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6713 = 15;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6714 = 16;
+ optional int32 field6715 = 17;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6716 = 20;
+}
+
+message Message18831 {
+ repeated group Message18832 = 1 {
+ optional int32 field18836 = 2;
+ optional string field18837 = 5;
+ optional float field18838 = 3;
+ optional float field18839 = 9;
+ optional int32 field18840 = 11;
+ repeated uint64 field18841 = 4;
+ repeated group Message18833 = 6 {
+ required uint64 field18843 = 7;
+ optional string field18844 = 8;
+ optional float field18845 = 10;
+ optional int32 field18846 = 12;
+ optional bool field18847 = 13;
+ }
+ }
+}
+
+message Message13090 {
+ optional .benchmarks.google_message3.Message13083 field13141 = 1;
+ optional .benchmarks.google_message3.Message13088 field13142 = 2;
+}
+
+message Message11874 {
+ optional .benchmarks.google_message3.Message10391 field11888 = 3;
+ optional string field11889 = 4;
+ optional .benchmarks.google_message3.Message11873 field11890 = 6;
+ optional bool field11891 = 7;
+ extensions 1 to 1;
+ extensions 2 to 2;
+ extensions 5 to 5;
+}
+
+message Message4144 {
+ repeated group Message4145 = 1 {
+ required .benchmarks.google_message3.Enum4146 field4165 = 2;
+ required int32 field4166 = 3;
+ optional .benchmarks.google_message3.Enum4160 field4167 = 9;
+ optional bytes field4168 = 4;
+ optional .benchmarks.google_message3.Enum4152 field4169 = 5;
+ optional string field4170 = 6;
+ }
+}
+
+message Message35573 {
+ optional fixed64 field35695 = 16;
+ optional string field35696 = 1000;
+ optional string field35697 = 1004;
+ optional int32 field35698 = 1003;
+ repeated group Message35574 = 1012 {
+ }
+ optional int64 field35700 = 1011;
+ optional int64 field35701 = 1005;
+ optional int64 field35702 = 1006;
+ optional int64 field35703 = 1007;
+ optional int64 field35704 = 1008;
+ repeated group Message35575 = 1 {
+ optional int64 field35709 = 2;
+ optional string field35710 = 3;
+ optional string field35711 = 19;
+ optional int32 field35712 = 20;
+ optional int32 field35713 = 21;
+ optional int32 field35714 = 22;
+ optional bool field35715 = 23;
+ optional int32 field35716 = 47;
+ optional int32 field35717 = 48;
+ optional bool field35718 = 24;
+ optional fixed64 field35719 = 25;
+ optional bytes field35720 = 52;
+ optional int32 field35721 = 18;
+ optional fixed32 field35722 = 43;
+ optional bool field35723 = 26;
+ optional int32 field35724 = 27;
+ optional int32 field35725 = 17;
+ optional bool field35726 = 45;
+ repeated int32 field35727 = 33;
+ repeated int32 field35728 = 58;
+ optional float field35729 = 34;
+ optional float field35730 = 1009;
+ optional int32 field35731 = 28;
+ repeated fixed64 field35732 = 1001;
+ repeated fixed64 field35733 = 1002;
+ optional int32 field35734 = 44;
+ optional int32 field35735 = 50;
+ optional int32 field35736 = 36;
+ optional int32 field35737 = 40;
+ optional bool field35738 = 1016;
+ optional bool field35739 = 1010;
+ optional int32 field35740 = 37;
+ optional int32 field35741 = 38;
+ optional string field35742 = 46;
+ optional uint32 field35743 = 60;
+ repeated bytes field35744 = 56;
+ optional .benchmarks.google_message3.Message0 field35745 = 57;
+ required group Message35576 = 4 {
+ optional fixed64 field35747 = 5;
+ optional int32 field35748 = 6;
+ optional int32 field35749 = 49;
+ optional int32 field35750 = 7;
+ optional uint32 field35751 = 59;
+ optional int32 field35752 = 14;
+ optional int32 field35753 = 15;
+ optional int32 field35754 = 35;
+ optional bytes field35755 = 53;
+ optional int32 field35756 = 8;
+ optional string field35757 = 9;
+ optional fixed64 field35758 = 10;
+ optional int32 field35759 = 11;
+ optional int32 field35760 = 12;
+ optional int32 field35761 = 41;
+ optional int32 field35762 = 30;
+ optional int32 field35763 = 31;
+ optional int32 field35764 = 13;
+ optional bytes field35765 = 39;
+ optional string field35766 = 29;
+ optional int32 field35767 = 42;
+ repeated int32 field35768 = 32;
+ repeated int32 field35769 = 51;
+ optional int64 field35770 = 54;
+ optional .benchmarks.google_message3.Message0 field35771 = 55;
+ }
+ }
+}
+
+message Message36858 {
+ repeated int32 field36956 = 1;
+ repeated string field36957 = 2;
+ repeated string field36958 = 12;
+ optional int32 field36959 = 3;
+ optional int32 field36960 = 4;
+ optional int32 field36961 = 14;
+ optional string field36962 = 11;
+ optional bool field36963 = 5;
+ optional bool field36964 = 13;
+ optional int64 field36965 = 6;
+ optional .benchmarks.google_message3.Message35506 field36966 = 7;
+ repeated group Message36859 = 8 {
+ required .benchmarks.google_message3.Enum36860 field36968 = 9;
+ optional float field36969 = 10;
+ }
+}
+
+message Message13174 {
+ required int32 field13237 = 6;
+ optional int32 field13238 = 3;
+ required int32 field13239 = 4;
+ optional int32 field13240 = 8;
+ optional double field13241 = 5;
+ optional double field13242 = 7;
+ optional int32 field13243 = 17;
+ optional int32 field13244 = 19;
+ optional double field13245 = 20;
+ optional int32 field13246 = 9;
+ optional double field13247 = 10;
+ optional int32 field13248 = 11;
+ optional .benchmarks.google_message3.Message13151 field13249 = 21;
+ optional int32 field13250 = 1;
+ optional double field13251 = 2;
+ optional double field13252 = 15;
+ optional double field13253 = 16;
+ optional double field13254 = 12;
+ optional double field13255 = 13;
+ optional double field13256 = 14;
+ optional int32 field13257 = 18;
+}
+
+message Message18283 {
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18478 = 1;
+ optional int32 field18479 = 4;
+ optional int32 field18480 = 106;
+ optional int32 field18481 = 107;
+ optional int32 field18482 = 108;
+ optional int32 field18483 = 109;
+ optional int32 field18484 = 105;
+ optional int32 field18485 = 113;
+ optional int32 field18486 = 114;
+ optional int32 field18487 = 124;
+ optional int32 field18488 = 125;
+ optional int32 field18489 = 128;
+ optional int32 field18490 = 135;
+ optional bool field18491 = 166;
+ optional bool field18492 = 136;
+ optional int32 field18493 = 140;
+ optional int32 field18494 = 171;
+ optional int32 field18495 = 148;
+ optional int32 field18496 = 145;
+ optional float field18497 = 117;
+ optional int32 field18498 = 146;
+ optional string field18499 = 3;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18500 = 5;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18501 = 6;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18502 = 9;
+ optional .benchmarks.google_message3.Message18253 field18503 = 155;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18504 = 184;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18505 = 163;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18506 = 16;
+ repeated int32 field18507 = 20;
+ repeated int32 field18508 = 7;
+ repeated string field18509 = 194;
+ optional bytes field18510 = 30;
+ optional int32 field18511 = 31;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18512 = 178;
+ optional string field18513 = 8;
+ optional float field18514 = 2;
+ optional float field18515 = 100;
+ optional float field18516 = 101;
+ optional float field18517 = 102;
+ optional int32 field18518 = 103;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field18519 = 104;
+ optional int32 field18520 = 110;
+ optional int32 field18521 = 112;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18522 = 111;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18523 = 115;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18524 = 119;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18525 = 127;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18526 = 185;
+ optional int32 field18527 = 120;
+ optional int32 field18528 = 132;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18529 = 126;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18530 = 129;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18531 = 131;
+ optional fixed64 field18532 = 150;
+ optional int32 field18533 = 133;
+ optional int32 field18534 = 134;
+ optional int32 field18535 = 139;
+ optional fixed64 field18536 = 137;
+ optional fixed64 field18537 = 138;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18538 = 141;
+ optional int32 field18539 = 142;
+ optional int32 field18540 = 181;
+ optional .benchmarks.google_message3.Message16816 field18541 = 143;
+ optional .benchmarks.google_message3.Message16685 field18542 = 154;
+ optional int32 field18543 = 144;
+ optional int64 field18544 = 147;
+ optional int64 field18545 = 149;
+ optional int32 field18546 = 151;
+ optional int32 field18547 = 152;
+ optional int32 field18548 = 153;
+ optional float field18549 = 161;
+ optional .benchmarks.google_message3.Message0 field18550 = 123;
+ repeated int64 field18551 = 156;
+ optional int32 field18552 = 157;
+ repeated fixed64 field18553 = 188;
+ optional int32 field18554 = 158;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18555 = 159;
+ optional bool field18556 = 160;
+ optional uint64 field18557 = 162;
+ optional int32 field18558 = 164;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18559 = 10;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18560 = 167;
+ optional int32 field18561 = 168;
+ repeated fixed64 field18562 = 169;
+ repeated string field18563 = 170;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18564 = 172;
+ optional int64 field18565 = 173;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18566 = 174;
+ optional int64 field18567 = 175;
+ optional uint32 field18568 = 189;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18569 = 176;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18570 = 177;
+ optional uint32 field18571 = 179;
+ optional uint32 field18572 = 180;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18573 = 182;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18574 = 183;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18575 = 121;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18576 = 186;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18577 = 187;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18578 = 190;
+ optional int32 field18579 = 191;
+ optional float field18580 = 192;
+ optional bool field18581 = 193;
+ extensions 116 to 116;
+ extensions 118 to 118;
+ extensions 130 to 130;
+ extensions 165 to 165;
+}
+
+message Message13169 {
+ repeated .benchmarks.google_message3.Message13168 field13223 = 1;
+ required .benchmarks.google_message3.Message13167 field13224 = 2;
+ optional string field13225 = 3;
+}
+
+message Message19255 {
+ optional string field19257 = 1;
+}
+
+message Message35542 {
+ optional bool field35543 = 1;
+ optional bool field35544 = 2;
+ optional bool field35545 = 3;
+}
+
+message Message3901 {
+ optional int32 field3990 = 1;
+ optional int32 field3991 = 2;
+ optional int32 field3992 = 3;
+ optional int32 field3993 = 4;
+ optional int32 field3994 = 7;
+ optional int32 field3995 = 8;
+ optional int32 field3996 = 9;
+ optional int32 field3997 = 10;
+ optional int32 field3998 = 11;
+ optional int32 field3999 = 12;
+ optional .benchmarks.google_message3.UnusedEnum field4000 = 6;
+ optional int32 field4001 = 5;
+}
+
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_3.proto b/benchmarks/datasets/google_message3/benchmark_message3_3.proto
new file mode 100644
index 00000000..e71d2661
--- /dev/null
+++ b/benchmarks/datasets/google_message3/benchmark_message3_3.proto
@@ -0,0 +1,466 @@
+syntax = "proto2";
+
+import "datasets/google_message3/benchmark_message3_4.proto";
+import "datasets/google_message3/benchmark_message3_5.proto";
+import "datasets/google_message3/benchmark_message3_7.proto";
+import "datasets/google_message3/benchmark_message3_8.proto";
+package benchmarks.google_message3;
+
+option cc_enable_arenas = true;
+option java_package = "com.google.protobuf.benchmarks";
+
+message Message35546 {
+ optional int64 field35556 = 1;
+ optional int32 field35557 = 2;
+ optional bool field35558 = 3;
+ optional int64 field35559 = 13;
+ optional group Message35547 = 4 {
+ required int32 field35569 = 5;
+ required int32 field35570 = 6;
+ }
+ optional group Message35548 = 10 {
+ required int64 field35571 = 11;
+ required int64 field35572 = 12;
+ }
+ optional bool field35562 = 14;
+ optional bool field35563 = 15;
+ optional int32 field35564 = 16;
+ optional bool field35565 = 17;
+ optional bool field35566 = 18;
+ optional string field35567 = 100;
+}
+
+message Message2356 {
+ optional .benchmarks.google_message3.Message1374 field2368 = 121;
+ optional uint64 field2369 = 1;
+ optional int32 field2370 = 2;
+ optional int32 field2371 = 17;
+ required string field2372 = 3;
+ optional int32 field2373 = 7;
+ optional bytes field2374 = 8;
+ optional string field2375 = 4;
+ optional string field2376 = 101;
+ optional int32 field2377 = 102;
+ optional int32 field2378 = 103;
+ optional int32 field2379 = 104;
+ optional int32 field2380 = 113;
+ optional int32 field2381 = 114;
+ optional int32 field2382 = 115;
+ optional int32 field2383 = 117;
+ optional int32 field2384 = 118;
+ optional int32 field2385 = 119;
+ optional int32 field2386 = 105;
+ optional bytes field2387 = 5;
+ optional group Message2357 = 6 {
+ optional int64 field2399 = 9;
+ optional int32 field2400 = 10;
+ optional int32 field2401 = 11;
+ optional int32 field2402 = 12;
+ optional int32 field2403 = 13;
+ optional int32 field2404 = 116;
+ optional int32 field2405 = 106;
+ required bytes field2406 = 14;
+ optional int32 field2407 = 45;
+ optional int32 field2408 = 112;
+ optional bool field2409 = 122;
+ optional bytes field2410 = 124;
+ }
+ optional string field2389 = 120;
+ optional group Message2358 = 107 {
+ }
+ repeated group Message2359 = 40 {
+ optional string field2413 = 41;
+ optional string field2414 = 42;
+ optional string field2415 = 43;
+ optional string field2416 = 44;
+ optional int32 field2417 = 46;
+ optional string field2418 = 47;
+ optional float field2419 = 110;
+ optional float field2420 = 111;
+ }
+ optional int32 field2392 = 50;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field2393 = 60;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field2394 = 70;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field2395 = 80;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field2396 = 90;
+ optional string field2397 = 100;
+ optional string field2398 = 123;
+}
+
+message Message7029 {
+ required int32 field7183 = 1;
+ optional int32 field7184 = 2;
+ optional int32 field7185 = 3;
+ optional int32 field7186 = 4;
+ optional int32 field7187 = 5;
+ optional int32 field7188 = 6;
+ optional int32 field7189 = 17;
+ optional int32 field7190 = 18;
+ optional int32 field7191 = 49;
+ optional int32 field7192 = 28;
+ optional int32 field7193 = 33;
+ optional int32 field7194 = 25;
+ optional int32 field7195 = 26;
+ optional int32 field7196 = 40;
+ optional int32 field7197 = 41;
+ optional int32 field7198 = 42;
+ optional int32 field7199 = 43;
+ optional int32 field7200 = 19;
+ optional int32 field7201 = 7;
+ optional int32 field7202 = 8;
+ optional int32 field7203 = 9;
+ optional int32 field7204 = 10;
+ optional int32 field7205 = 11;
+ optional int32 field7206 = 12;
+ repeated group Message7030 = 13 {
+ optional string field7226 = 14;
+ optional string field7227 = 15;
+ optional int64 field7228 = 16;
+ }
+ repeated group Message7031 = 21 {
+ optional string field7229 = 22;
+ optional int32 field7230 = 23;
+ optional int32 field7231 = 24;
+ optional int32 field7232 = 30;
+ optional int32 field7233 = 31;
+ optional int32 field7234 = 35;
+ }
+ optional int32 field7209 = 20;
+ optional float field7210 = 27;
+ optional int32 field7211 = 29;
+ optional int32 field7212 = 32;
+ optional string field7213 = 48;
+ optional bool field7214 = 34;
+ optional int32 field7215 = 36;
+ optional float field7216 = 37;
+ optional bool field7217 = 38;
+ optional bool field7218 = 39;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field7219 = 44;
+ optional int32 field7220 = 45;
+ optional int32 field7221 = 46;
+ optional int32 field7222 = 47;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field7223 = 50;
+ optional int32 field7224 = 51;
+}
+
+message Message35538 {
+ required int64 field35539 = 1;
+}
+
+message Message18921 {
+ optional string field18946 = 1;
+ optional fixed64 field18947 = 2;
+ optional int32 field18948 = 3;
+ optional double field18949 = 4;
+ optional bool field18950 = 17;
+ optional bool field18951 = 23;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18952 = 24;
+ repeated group Message18922 = 5 {
+ optional uint64 field18959 = 6;
+ optional string field18960 = 13;
+ optional bool field18961 = 21;
+ optional bool field18962 = 33;
+ optional int32 field18963 = 7;
+ optional int32 field18964 = 8;
+ optional string field18965 = 9;
+ optional .benchmarks.google_message3.Message18856 field18966 = 10;
+ optional uint64 field18967 = 34;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18968 = 11;
+ optional uint64 field18969 = 35;
+ optional float field18970 = 12;
+ repeated string field18971 = 14;
+ optional bool field18972 = 15;
+ optional bool field18973 = 16;
+ optional float field18974 = 22;
+ optional int32 field18975 = 18;
+ optional int32 field18976 = 19;
+ optional int32 field18977 = 20;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field18978 = 25;
+ optional .benchmarks.google_message3.UnusedEnum field18979 = 26;
+ repeated string field18980 = 27;
+ optional float field18981 = 28;
+ }
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field18954 = 29;
+ repeated .benchmarks.google_message3.Message18943 field18955 = 30;
+ repeated .benchmarks.google_message3.Message18944 field18956 = 31;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field18957 = 32;
+}
+
+message Message35540 {
+ optional bool field35541 = 1;
+}
+
+message Message3886 {
+ repeated group Message3887 = 1 {
+ required string field3932 = 2;
+ optional string field3933 = 9;
+ optional .benchmarks.google_message3.Message3850 field3934 = 3;
+ optional bytes field3935 = 8;
+ }
+}
+
+message Message6743 {
+ optional .benchmarks.google_message3.Message6721 field6759 = 1;
+ optional .benchmarks.google_message3.Message6723 field6760 = 2;
+ optional .benchmarks.google_message3.Message6723 field6761 = 8;
+ optional .benchmarks.google_message3.Message6725 field6762 = 3;
+ optional .benchmarks.google_message3.Message6726 field6763 = 4;
+ optional .benchmarks.google_message3.Message6733 field6764 = 5;
+ optional .benchmarks.google_message3.Message6734 field6765 = 6;
+ optional .benchmarks.google_message3.Message6742 field6766 = 7;
+}
+
+message Message6773 {
+ optional .benchmarks.google_message3.Enum6769 field6794 = 1;
+ optional int32 field6795 = 9;
+ optional .benchmarks.google_message3.UnusedEnum field6796 = 10;
+ optional int32 field6797 = 11;
+ optional int32 field6798 = 2;
+ optional .benchmarks.google_message3.Enum6774 field6799 = 3;
+ optional double field6800 = 5;
+ optional double field6801 = 7;
+ optional double field6802 = 8;
+ optional .benchmarks.google_message3.Enum6782 field6803 = 6;
+}
+
+message Message8224 {
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8255 = 1;
+ optional .benchmarks.google_message3.Message8184 field8256 = 2;
+ optional .benchmarks.google_message3.Message7966 field8257 = 3;
+ optional string field8258 = 4;
+ optional string field8259 = 5;
+ optional bool field8260 = 6;
+ optional int64 field8261 = 7;
+ optional string field8262 = 8;
+ optional int64 field8263 = 9;
+ optional double field8264 = 10;
+ optional int64 field8265 = 11;
+ repeated string field8266 = 12;
+ optional int64 field8267 = 13;
+ optional int32 field8268 = 14;
+ optional int32 field8269 = 15;
+ optional int64 field8270 = 16;
+ optional double field8271 = 17;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8272 = 18;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8273 = 19;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field8274 = 20;
+ optional bool field8275 = 21;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8276 = 22;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8277 = 23;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field8278 = 24;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8279 = 25;
+ optional bool field8280 = 26;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field8281 = 27;
+}
+
+message Message8392 {
+ optional string field8395 = 1;
+ optional string field8396 = 2;
+ optional .benchmarks.google_message3.Message7966 field8397 = 3;
+ optional string field8398 = 4;
+ optional string field8399 = 5;
+ optional string field8400 = 6;
+ optional string field8401 = 7;
+ optional string field8402 = 8;
+ optional string field8403 = 9;
+}
+
+message Message8130 {
+ optional string field8156 = 1;
+ optional string field8157 = 2;
+ optional string field8158 = 4;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8159 = 6;
+ repeated string field8160 = 7;
+ optional int64 field8161 = 8;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8162 = 9;
+ optional string field8163 = 10;
+ optional string field8164 = 11;
+ optional string field8165 = 12;
+ optional string field8166 = 13;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8167 = 14;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8168 = 15;
+ optional string field8169 = 16;
+ optional .benchmarks.google_message3.UnusedEnum field8170 = 17;
+ optional .benchmarks.google_message3.UnusedEnum field8171 = 18;
+ optional bool field8172 = 19;
+ optional bool field8173 = 20;
+ optional double field8174 = 21;
+ optional int32 field8175 = 22;
+ optional int32 field8176 = 23;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8177 = 24;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field8178 = 25;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field8179 = 26;
+}
+
+message Message8478 {
+ optional string field8489 = 7;
+ optional .benchmarks.google_message3.Message7966 field8490 = 1;
+ optional .benchmarks.google_message3.Message8476 field8491 = 2;
+ optional int64 field8492 = 3;
+ optional .benchmarks.google_message3.Message8476 field8493 = 4;
+ repeated .benchmarks.google_message3.Message8477 field8494 = 5;
+ optional .benchmarks.google_message3.Message8454 field8495 = 6;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8496 = 8;
+}
+
+message Message8479 {
+ optional .benchmarks.google_message3.Message8475 field8497 = 1;
+ optional .benchmarks.google_message3.Message7966 field8498 = 2;
+ optional .benchmarks.google_message3.Message8476 field8499 = 3;
+ optional .benchmarks.google_message3.Message8476 field8500 = 4;
+ optional string field8501 = 6;
+ optional string field8502 = 7;
+ optional .benchmarks.google_message3.Message7966 field8503 = 8;
+ optional .benchmarks.google_message3.Message8455 field8504 = 5;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8505 = 9;
+}
+
+message Message10319 {
+ optional .benchmarks.google_message3.Enum10325 field10340 = 1;
+ optional int32 field10341 = 4;
+ optional int32 field10342 = 5;
+ optional bytes field10343 = 3;
+ optional string field10344 = 2;
+ optional string field10345 = 6;
+ optional string field10346 = 7;
+}
+
+message Message4016 {
+ required int32 field4017 = 1;
+ required int32 field4018 = 2;
+ required int32 field4019 = 3;
+ required int32 field4020 = 4;
+}
+
+message Message12669 {
+ optional .benchmarks.google_message3.Message12559 field12681 = 1;
+ optional float field12682 = 2;
+ optional bool field12683 = 3;
+ optional .benchmarks.google_message3.Enum12670 field12684 = 4;
+}
+
+message Message12819 {
+ optional double field12834 = 1;
+ optional double field12835 = 2;
+ optional double field12836 = 3;
+ optional double field12837 = 4;
+ optional double field12838 = 5;
+ optional double field12839 = 6;
+}
+
+message Message12820 {
+ optional int32 field12840 = 1;
+ optional int32 field12841 = 2;
+ optional int32 field12842 = 3;
+ optional int32 field12843 = 8;
+ optional int32 field12844 = 4;
+ optional int32 field12845 = 5;
+ optional int32 field12846 = 6;
+ optional int32 field12847 = 7;
+}
+
+message Message12821 {
+ optional int32 field12848 = 1;
+ optional int32 field12849 = 2;
+ optional int32 field12850 = 3;
+ optional int32 field12851 = 4;
+ optional int32 field12852 = 5;
+}
+
+message Message12818 {
+ optional uint64 field12829 = 1;
+ optional int32 field12830 = 2;
+ optional int32 field12831 = 3;
+ optional int32 field12832 = 5;
+ repeated .benchmarks.google_message3.Message12817 field12833 = 4;
+}
+
+message Message16479 {
+ optional .benchmarks.google_message3.Message16480 field16484 = 1;
+ optional int32 field16485 = 5;
+ optional float field16486 = 2;
+ optional uint32 field16487 = 4;
+ optional bool field16488 = 3;
+ optional uint32 field16489 = 6;
+}
+
+message Message16722 {
+ optional string field16752 = 1;
+ optional string field16753 = 2;
+ optional string field16754 = 3;
+ optional int32 field16755 = 5;
+ optional string field16756 = 4;
+}
+
+message Message16724 {
+ optional int64 field16761 = 1;
+ optional float field16762 = 2;
+ optional int64 field16763 = 3;
+ optional int64 field16764 = 4;
+ optional bool field16765 = 5;
+ repeated string field16766 = 6;
+ repeated string field16767 = 7;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field16768 = 8;
+ optional bool field16769 = 9;
+ optional uint32 field16770 = 10;
+ optional .benchmarks.google_message3.Enum16728 field16771 = 11;
+ repeated int32 field16772 = 12;
+ optional bool field16773 = 13;
+}
+
+message Message17728 {
+}
+
+message Message24356 {
+ optional string field24559 = 1;
+ optional string field24560 = 2;
+ optional int32 field24561 = 14;
+ optional string field24562 = 3;
+ optional string field24563 = 4;
+ optional string field24564 = 5;
+ optional .benchmarks.google_message3.UnusedEnum field24565 = 13;
+ optional string field24566 = 6;
+ optional .benchmarks.google_message3.Enum24361 field24567 = 12;
+ optional string field24568 = 7;
+ optional string field24569 = 8;
+ optional string field24570 = 9;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field24571 = 10;
+ repeated string field24572 = 11;
+ repeated string field24573 = 15;
+}
+
+message Message24376 {
+ optional string field24589 = 1;
+ optional string field24590 = 2;
+ optional string field24591 = 3;
+ required .benchmarks.google_message3.Message24377 field24592 = 4;
+ optional .benchmarks.google_message3.Message24317 field24593 = 5;
+ optional string field24594 = 6;
+ optional .benchmarks.google_message3.Message24378 field24595 = 7;
+ repeated string field24596 = 8;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field24597 = 14;
+ repeated string field24598 = 9;
+ repeated string field24599 = 10;
+ repeated string field24600 = 11;
+ optional string field24601 = 12;
+ repeated string field24602 = 13;
+}
+
+message Message24366 {
+ optional string field24574 = 1;
+ optional string field24575 = 2;
+ optional string field24576 = 3;
+ optional int32 field24577 = 10;
+ optional string field24578 = 13;
+ optional string field24579 = 4;
+ optional string field24580 = 5;
+ optional .benchmarks.google_message3.UnusedEnum field24581 = 9;
+ optional string field24582 = 14;
+ optional .benchmarks.google_message3.UnusedEnum field24583 = 15;
+ optional string field24584 = 6;
+ optional string field24585 = 12;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field24586 = 7;
+ repeated string field24587 = 8;
+ repeated string field24588 = 11;
+}
+
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_4.proto b/benchmarks/datasets/google_message3/benchmark_message3_4.proto
new file mode 100644
index 00000000..597cec6d
--- /dev/null
+++ b/benchmarks/datasets/google_message3/benchmark_message3_4.proto
@@ -0,0 +1,491 @@
+syntax = "proto2";
+
+import "datasets/google_message3/benchmark_message3_5.proto";
+import "datasets/google_message3/benchmark_message3_6.proto";
+import "datasets/google_message3/benchmark_message3_7.proto";
+import "datasets/google_message3/benchmark_message3_8.proto";
+package benchmarks.google_message3;
+
+option cc_enable_arenas = true;
+option java_package = "com.google.protobuf.benchmarks";
+
+message Message24346 {
+}
+
+message Message24401 {
+ optional .benchmarks.google_message3.Message24400 field24679 = 1;
+}
+
+message Message24402 {
+ optional .benchmarks.google_message3.Message24400 field24680 = 1;
+}
+
+message Message24379 {
+ optional string field24603 = 1;
+ optional string field24604 = 2;
+ optional string field24605 = 3;
+ required .benchmarks.google_message3.Message24380 field24606 = 4;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24607 = 5;
+ optional string field24608 = 6;
+ optional .benchmarks.google_message3.Message24381 field24609 = 7;
+ repeated string field24610 = 8;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field24611 = 17;
+ repeated string field24612 = 9;
+ repeated string field24613 = 10;
+ repeated string field24614 = 11;
+ optional string field24615 = 14;
+ optional string field24616 = 12;
+ optional string field24617 = 16;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field24618 = 13;
+ repeated string field24619 = 15;
+ repeated string field24620 = 18;
+}
+
+message Message27358 {
+ optional int32 field27415 = 1;
+ optional int32 field27416 = 2;
+}
+
+message Message34381 {
+ optional string field34398 = 1;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field34399 = 2;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field34400 = 3;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field34401 = 4;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field34402 = 5;
+ optional bool field34403 = 6;
+ optional bool field34404 = 7;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field34405 = 8;
+ optional bool field34406 = 9;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field34407 = 10;
+}
+
+message Message34619 {
+ optional double field34641 = 1;
+ optional double field34642 = 2;
+ optional double field34643 = 3;
+ optional double field34644 = 4;
+ optional double field34645 = 11;
+ optional double field34646 = 5;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field34647 = 100;
+}
+
+message Message730 {
+ optional string field897 = 19;
+ repeated string field898 = 27;
+ repeated string field899 = 28;
+ repeated string field900 = 21;
+ optional string field901 = 30;
+ repeated uint32 field902 = 20;
+ repeated uint32 field903 = 32;
+ repeated string field904 = 16;
+ repeated .benchmarks.google_message3.Message697 field905 = 6;
+ repeated .benchmarks.google_message3.Message704 field906 = 7;
+ repeated string field907 = 18;
+ repeated .benchmarks.google_message3.Message703 field908 = 8;
+ repeated string field909 = 9;
+ optional .benchmarks.google_message3.Message716 field910 = 10;
+ optional .benchmarks.google_message3.Message718 field911 = 11;
+ optional bool field912 = 14;
+ repeated .benchmarks.google_message3.Message715 field913 = 4;
+ repeated string field914 = 17;
+ repeated string field915 = 23;
+ repeated .benchmarks.google_message3.Message719 field916 = 24;
+ repeated .benchmarks.google_message3.Message728 field917 = 26;
+ repeated .benchmarks.google_message3.Message702 field918 = 35;
+ optional string field919 = 36;
+ repeated string field920 = 37;
+ optional int64 field921 = 38;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field922 = 39;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field923 = 1;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field924 = 2;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field925 = 3;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field926 = 5;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field927 = 13;
+ repeated string field928 = 22;
+ optional bytes field929 = 31;
+ extensions 25 to 25;
+ extensions 29 to 29;
+ extensions 34 to 34;
+ extensions 15 to 15;
+}
+
+message Message33958 {
+ optional string field33977 = 1;
+ optional string field33978 = 9;
+ repeated group Message33959 = 2 {
+ required string field33982 = 3;
+ optional string field33983 = 4;
+ optional string field33984 = 5;
+ optional fixed64 field33985 = 8;
+ optional bool field33986 = 10;
+ optional .benchmarks.google_message3.Message0 field33987 = 6;
+ }
+ optional .benchmarks.google_message3.Enum33960 field33980 = 7;
+ extend .benchmarks.google_message3.Message0 {
+ optional .benchmarks.google_message3.Message33958 field33981 = 10747482;
+ }
+}
+
+message Message6637 {
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6670 = 2;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field6671 = 1;
+ optional int32 field6672 = 3;
+ repeated string field6673 = 4;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6674 = 5;
+}
+
+message Message6643 {
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6683 = 3;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6684 = 4;
+ optional double field6685 = 5;
+ optional double field6686 = 6;
+ optional int32 field6687 = 1;
+ optional int32 field6688 = 2;
+ optional double field6689 = 9;
+ optional bytes field6690 = 10;
+ optional int32 field6691 = 11;
+ optional bool field6692 = 12;
+ optional bool field6693 = 13;
+ optional .benchmarks.google_message3.Message6578 field6694 = 15;
+ optional .benchmarks.google_message3.UnusedEnum field6695 = 16;
+ optional int64 field6696 = 17;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field6697 = 22;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6698 = 19;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6699 = 20;
+ optional int32 field6700 = 21;
+}
+
+message Message6126 {
+ required string field6152 = 1;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field6153 = 9;
+ optional int32 field6154 = 14;
+ optional bytes field6155 = 10;
+ optional .benchmarks.google_message3.Message6024 field6156 = 12;
+ optional int32 field6157 = 4;
+ optional string field6158 = 5;
+ optional int32 field6159 = 6;
+ repeated int32 field6160 = 2;
+ repeated int32 field6161 = 3;
+ repeated .benchmarks.google_message3.Message6052 field6162 = 7;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field6163 = 11;
+ optional .benchmarks.google_message3.Enum6065 field6164 = 15;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field6165 = 8;
+ optional bool field6166 = 13;
+ optional bool field6167 = 16;
+ optional bool field6168 = 18;
+ repeated .benchmarks.google_message3.Message6054 field6169 = 17;
+ optional int32 field6170 = 19;
+}
+
+message Message13083 {
+ optional float field13096 = 1;
+ repeated group Message13084 = 2 {
+ required float field13107 = 3;
+ required int32 field13108 = 4;
+ optional float field13109 = 5;
+ repeated .benchmarks.google_message3.Enum13092 field13110 = 6;
+ }
+ optional float field13098 = 44;
+ optional float field13099 = 45;
+ optional uint64 field13100 = 46;
+ optional float field13101 = 47;
+ optional group Message13085 = 16 {
+ }
+ repeated group Message13086 = 23 {
+ }
+ repeated group Message13087 = 29 {
+ }
+ optional .benchmarks.google_message3.UnusedEmptyMessage field13105 = 43;
+}
+
+message Message13088 {
+ repeated group Message13089 = 1 {
+ required string field13139 = 2;
+ optional float field13140 = 3;
+ }
+ optional int64 field13136 = 4;
+ optional bool field13137 = 5;
+}
+
+message Message10391 {
+ optional .benchmarks.google_message3.Enum10392 field10411 = 1;
+ optional .benchmarks.google_message3.UnusedEnum field10412 = 2;
+ optional int64 field10413 = 3;
+ optional string field10414 = 4;
+ optional string field10415 = 5;
+ optional bytes field10416 = 6;
+ optional bool field10417 = 8;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field10418 = 9;
+ optional bool field10419 = 10;
+}
+
+message Message11873 {
+ optional string field11876 = 1;
+ optional string field11877 = 4;
+ optional .benchmarks.google_message3.Message10573 field11878 = 5;
+ optional .benchmarks.google_message3.Message10582 field11879 = 6;
+ optional .benchmarks.google_message3.Message10824 field11880 = 7;
+ optional .benchmarks.google_message3.Message10773 field11881 = 12;
+ optional .benchmarks.google_message3.Message11866 field11882 = 8;
+ optional .benchmarks.google_message3.Message10818 field11883 = 13;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field11884 = 16;
+ optional .benchmarks.google_message3.Message10155 field11885 = 11;
+ optional .benchmarks.google_message3.Message10469 field11886 = 14;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field11887 = 15;
+ extensions 9 to 9;
+ extensions 10 to 10;
+}
+
+message Message35506 {
+ optional int32 field35524 = 1;
+ optional string field35525 = 2;
+ optional .benchmarks.google_message3.Enum35507 field35526 = 3;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field35527 = 4;
+}
+
+message Message13151 {
+ repeated .benchmarks.google_message3.Message13145 field13158 = 1;
+}
+
+message Message18253 {
+ repeated group Message18254 = 1 {
+ required fixed64 field18362 = 2;
+ required double field18363 = 3;
+ }
+}
+
+message Message16685 {
+ repeated .benchmarks.google_message3.Message16686 field16694 = 2;
+}
+
+message Message16816 {
+ optional float field16826 = 1;
+ optional .benchmarks.google_message3.Enum16819 field16827 = 2;
+ optional float field16828 = 3;
+ repeated group Message16817 = 4 {
+ }
+ optional bool field16830 = 7;
+ optional bool field16831 = 8;
+ repeated group Message16818 = 12 {
+ }
+ optional string field16833 = 10;
+ optional bool field16834 = 13;
+ optional bool field16835 = 14;
+}
+
+message Message13168 {
+ required int32 field13212 = 1;
+ optional fixed64 field13213 = 7;
+ optional bool field13214 = 8;
+ optional fixed64 field13215 = 10;
+ optional bool field13216 = 11;
+ optional .benchmarks.google_message3.Message12796 field13217 = 9;
+ required double field13218 = 2;
+ required bool field13219 = 3;
+ optional int32 field13220 = 4;
+ required bool field13221 = 5;
+ optional int32 field13222 = 6;
+}
+
+message Message13167 {
+ required int32 field13199 = 1;
+ optional int32 field13200 = 2;
+ optional int32 field13201 = 3;
+ optional bool field13202 = 8;
+ optional fixed64 field13203 = 12;
+ optional bool field13204 = 13;
+ optional .benchmarks.google_message3.Message12796 field13205 = 11;
+ optional fixed64 field13206 = 9;
+ optional bool field13207 = 10;
+ repeated int32 field13208 = 4;
+ optional int32 field13209 = 5;
+ optional int32 field13210 = 6;
+ optional int32 field13211 = 7;
+}
+
+message Message1374 {
+ required string field1375 = 1;
+ optional string field1376 = 2;
+}
+
+message Message18943 {
+}
+
+message Message18944 {
+}
+
+message Message18856 {
+ optional string field18857 = 1;
+ optional string field18858 = 2;
+ optional bool field18859 = 31;
+ optional string field18860 = 26;
+ optional string field18861 = 3;
+ optional string field18862 = 4;
+ optional string field18863 = 5;
+ optional string field18864 = 17;
+ optional string field18865 = 6;
+ optional string field18866 = 7;
+ optional string field18867 = 8;
+ optional string field18868 = 9;
+ optional string field18869 = 10;
+ optional string field18870 = 11;
+ optional string field18871 = 21;
+ optional string field18872 = 18;
+ optional string field18873 = 19;
+ optional string field18874 = 20;
+ optional string field18875 = 22;
+ optional string field18876 = 23;
+ optional string field18877 = 24;
+ optional string field18878 = 25;
+ optional string field18879 = 12;
+ optional string field18880 = 13;
+ optional string field18881 = 29;
+ optional string field18882 = 30;
+ optional string field18883 = 15;
+ optional string field18884 = 16;
+ repeated string field18885 = 14;
+ optional string field18886 = 27;
+ optional string field18887 = 28;
+}
+
+message Message3850 {
+ optional .benchmarks.google_message3.Enum3851 field3924 = 2;
+ optional bool field3925 = 12;
+ optional int32 field3926 = 4;
+ optional bool field3927 = 10;
+ optional bool field3928 = 13;
+ optional bool field3929 = 14;
+}
+
+message Message6721 {
+ optional .benchmarks.google_message3.Message6722 field6744 = 1;
+ optional bool field6745 = 2;
+ optional bool field6746 = 3;
+ optional bool field6747 = 4;
+}
+
+message Message6742 {
+ optional bool field6758 = 1;
+}
+
+message Message6726 {
+ optional int64 field6752 = 1;
+ repeated .benchmarks.google_message3.Message6727 field6753 = 2;
+}
+
+message Message6733 {
+ optional int64 field6754 = 1;
+ optional int64 field6755 = 2;
+ optional bool field6756 = 3;
+}
+
+message Message6723 {
+ optional int64 field6748 = 1;
+ repeated .benchmarks.google_message3.Message6724 field6749 = 2;
+}
+
+message Message6725 {
+ optional int32 field6750 = 1;
+ optional int32 field6751 = 2;
+}
+
+message Message6734 {
+ repeated .benchmarks.google_message3.Message6735 field6757 = 1;
+}
+
+message Message8184 {
+ optional .benchmarks.google_message3.Message7966 field8228 = 1;
+ optional bool field8229 = 2;
+ repeated .benchmarks.google_message3.Message8183 field8230 = 3;
+}
+
+message Message8477 {
+ optional .benchmarks.google_message3.Message7966 field8486 = 1;
+ optional int64 field8487 = 2;
+ optional string field8488 = 3;
+}
+
+message Message8454 {
+ optional .benchmarks.google_message3.Message8449 field8465 = 1;
+ optional int64 field8466 = 3;
+ optional int32 field8467 = 4;
+ optional bool field8468 = 5;
+ extend .benchmarks.google_message3.Message8301 {
+ optional .benchmarks.google_message3.Message8454 field8469 = 66;
+ }
+}
+
+message Message8476 {
+ optional string field8483 = 1;
+ optional string field8484 = 2;
+ optional string field8485 = 3;
+}
+
+message Message8455 {
+ optional .benchmarks.google_message3.Message8449 field8470 = 1;
+ repeated .benchmarks.google_message3.Message8456 field8471 = 2;
+ optional .benchmarks.google_message3.Message8457 field8472 = 5;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8473 = 6;
+ extend .benchmarks.google_message3.Message8302 {
+ optional .benchmarks.google_message3.Message8455 field8474 = 66;
+ }
+}
+
+message Message8475 {
+ optional string field8481 = 1;
+ optional int64 field8482 = 2;
+}
+
+message Message12559 {
+}
+
+message Message12817 {
+ optional int32 field12826 = 1;
+ optional int32 field12827 = 2;
+ optional int32 field12828 = 3;
+}
+
+message Message16480 {
+ optional .benchmarks.google_message3.Message13358 field16490 = 1;
+ optional .benchmarks.google_message3.Enum16042 field16491 = 2;
+ optional .benchmarks.google_message3.Message13912 field16492 = 3;
+ optional string field16493 = 4;
+ optional string field16494 = 5;
+ optional string field16495 = 6;
+ optional string field16496 = 7;
+ optional .benchmarks.google_message3.Message13358 field16497 = 8;
+ optional fixed32 field16498 = 9;
+}
+
+message Message24317 {
+ optional string field24446 = 1;
+ optional .benchmarks.google_message3.Message24312 field24447 = 2;
+ repeated .benchmarks.google_message3.Message24315 field24448 = 3;
+ repeated .benchmarks.google_message3.Message24313 field24449 = 4;
+ repeated .benchmarks.google_message3.Message24316 field24450 = 5;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field24451 = 6;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field24452 = 7;
+ repeated string field24453 = 8;
+ repeated string field24454 = 9;
+ repeated string field24455 = 10;
+ repeated string field24456 = 28;
+ optional string field24457 = 11;
+ optional string field24458 = 12;
+ optional string field24459 = 13;
+ optional string field24460 = 14;
+ repeated string field24461 = 15;
+ optional string field24462 = 16;
+ repeated string field24463 = 17;
+ repeated string field24464 = 18;
+ repeated string field24465 = 19;
+ repeated string field24466 = 20;
+ repeated string field24467 = 21;
+ repeated string field24468 = 22;
+ repeated string field24469 = 23;
+ repeated string field24470 = 24;
+ optional string field24471 = 25;
+ optional string field24472 = 26;
+ repeated string field24473 = 27;
+ optional bool field24474 = 40;
+}
+
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_5.proto b/benchmarks/datasets/google_message3/benchmark_message3_5.proto
new file mode 100644
index 00000000..bc6cbc1c
--- /dev/null
+++ b/benchmarks/datasets/google_message3/benchmark_message3_5.proto
@@ -0,0 +1,473 @@
+syntax = "proto2";
+
+import "datasets/google_message3/benchmark_message3_6.proto";
+import "datasets/google_message3/benchmark_message3_7.proto";
+import "datasets/google_message3/benchmark_message3_8.proto";
+package benchmarks.google_message3;
+
+option cc_enable_arenas = true;
+option java_package = "com.google.protobuf.benchmarks";
+
+message Message24377 {
+}
+
+message Message24378 {
+}
+
+message Message24400 {
+ optional int32 field24674 = 1;
+ optional int32 field24675 = 2;
+ optional int32 field24676 = 3;
+ optional int32 field24677 = 4;
+ optional int32 field24678 = 5;
+}
+
+message Message24380 {
+}
+
+message Message24381 {
+}
+
+message Message719 {
+ repeated string field881 = 1;
+ repeated string field882 = 2;
+ repeated string field883 = 3;
+ optional .benchmarks.google_message3.Enum720 field884 = 4;
+}
+
+message Message728 {
+ required string field887 = 1;
+ repeated string field888 = 2;
+ repeated .benchmarks.google_message3.Message703 field889 = 3;
+ repeated .benchmarks.google_message3.Message715 field890 = 4;
+ repeated string field891 = 5;
+ repeated string field892 = 6;
+ optional .benchmarks.google_message3.Message718 field893 = 7;
+ optional .benchmarks.google_message3.Message716 field894 = 8;
+ repeated string field895 = 9;
+ extensions 10 to 10;
+ extensions 11 to 11;
+ extensions 12 to 12;
+}
+
+message Message704 {
+ optional string field800 = 1;
+ optional string field801 = 7;
+ optional string field802 = 2;
+ optional string field803 = 3;
+ optional string field804 = 4;
+ optional string field805 = 5;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field806 = 6;
+}
+
+message Message697 {
+ optional string field743 = 7;
+ repeated string field744 = 1;
+ repeated string field745 = 2;
+ repeated string field746 = 33;
+ repeated string field747 = 29;
+ repeated string field748 = 30;
+ repeated string field749 = 31;
+ repeated string field750 = 32;
+ repeated string field751 = 13;
+ repeated string field752 = 6;
+ repeated string field753 = 3;
+ repeated string field754 = 14;
+ repeated string field755 = 15;
+ repeated string field756 = 16;
+ repeated string field757 = 4;
+ repeated string field758 = 34;
+ repeated string field759 = 35;
+ repeated string field760 = 5;
+ repeated string field761 = 17;
+ repeated string field762 = 18;
+ repeated string field763 = 19;
+ optional bool field764 = 36;
+ repeated string field765 = 8;
+ repeated string field766 = 9;
+ optional string field767 = 27;
+ optional bool field768 = 25;
+ optional .benchmarks.google_message3.Message700 field769 = 10;
+ optional bool field770 = 11;
+ optional bool field771 = 24;
+ repeated string field772 = 12;
+ repeated string field773 = 20;
+ repeated string field774 = 21;
+ repeated string field775 = 22;
+ repeated .benchmarks.google_message3.Message699 field776 = 23;
+ repeated .benchmarks.google_message3.Message698 field777 = 37;
+ optional int64 field778 = 38;
+ extensions 28 to 28;
+ extensions 26 to 26;
+}
+
+message Message0 {
+ option message_set_wire_format = true;
+ extensions 4 to 2147483646;
+}
+
+message Message6578 {
+ optional .benchmarks.google_message3.Enum6579 field6632 = 1;
+ optional .benchmarks.google_message3.Enum6588 field6633 = 2;
+}
+
+message Message6024 {
+ optional .benchmarks.google_message3.Enum6025 field6048 = 1;
+ optional string field6049 = 2;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field6050 = 3;
+}
+
+message Message6052 {
+ required string field6084 = 1;
+ required bytes field6085 = 2;
+}
+
+message Message6054 {
+ required string field6089 = 1;
+ optional string field6090 = 2;
+}
+
+message Message10573 {
+ repeated .benchmarks.google_message3.Message10576 field10580 = 1;
+ optional string field10581 = 2;
+ extensions 10000 to 536870911;
+}
+
+message Message10824 {
+ required string field10825 = 1;
+ optional int32 field10826 = 2;
+}
+
+message Message10582 {
+ required bool field10583 = 1;
+ required double field10584 = 2;
+ optional bool field10585 = 3;
+ optional double field10586 = 4;
+ optional double field10587 = 5;
+ optional bool field10588 = 6;
+}
+
+message Message10155 {
+ required int32 field10195 = 1;
+ required int32 field10196 = 2;
+ optional .benchmarks.google_message3.Enum10157 field10197 = 59;
+ optional int32 field10198 = 18;
+ optional int32 field10199 = 19;
+ optional int32 field10200 = 21;
+ repeated group Message10156 = 50 {
+ optional .benchmarks.google_message3.Enum8862 field10266 = 51;
+ optional int32 field10267 = 52;
+ optional int32 field10268 = 53;
+ optional int32 field10269 = 54;
+ }
+ optional int32 field10202 = 3;
+ optional int32 field10203 = 4;
+ optional int32 field10204 = 5;
+ optional bool field10205 = 84;
+ optional bool field10206 = 33;
+ optional int32 field10207 = 75;
+ optional float field10208 = 26;
+ optional int32 field10209 = 27;
+ optional int32 field10210 = 49;
+ optional int32 field10211 = 10;
+ optional float field10212 = 78;
+ optional .benchmarks.google_message3.Message9151 field10213 = 91;
+ optional int32 field10214 = 11;
+ optional int32 field10215 = 12;
+ optional float field10216 = 41;
+ optional .benchmarks.google_message3.Message10154 field10217 = 61;
+ optional int32 field10218 = 23;
+ optional bytes field10219 = 24;
+ optional int32 field10220 = 65;
+ repeated bytes field10221 = 66;
+ optional int32 field10222 = 70;
+ optional bytes field10223 = 71;
+ repeated fixed64 field10224 = 73;
+ optional float field10225 = 29;
+ optional int32 field10226 = 30;
+ optional float field10227 = 31;
+ optional int32 field10228 = 32;
+ optional float field10229 = 34;
+ optional int32 field10230 = 35;
+ optional string field10231 = 22;
+ optional fixed64 field10232 = 13;
+ optional fixed64 field10233 = 20;
+ optional bool field10234 = 79;
+ repeated .benchmarks.google_message3.Enum10167 field10235 = 80 [packed = true];
+ optional int32 field10236 = 14;
+ optional int32 field10237 = 15;
+ optional int32 field10238 = 28;
+ repeated string field10239 = 16;
+ optional .benchmarks.google_message3.Message9182 field10240 = 17;
+ optional int32 field10241 = 63;
+ optional float field10242 = 64;
+ optional float field10243 = 37;
+ repeated float field10244 = 43;
+ optional int32 field10245 = 44;
+ optional .benchmarks.google_message3.Message9242 field10246 = 45;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field10247 = 46;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field10248 = 62;
+ optional .benchmarks.google_message3.Message8944 field10249 = 48;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field10250 = 87;
+ optional int32 field10251 = 58;
+ optional int32 field10252 = 92;
+ optional .benchmarks.google_message3.Message9123 field10253 = 93;
+ optional .benchmarks.google_message3.Message9160 field10254 = 60;
+ optional .benchmarks.google_message3.Message8890 field10255 = 67;
+ optional string field10256 = 69;
+ optional int64 field10257 = 74;
+ optional float field10258 = 82;
+ optional float field10259 = 85;
+ optional float field10260 = 86;
+ optional int64 field10261 = 83;
+ optional string field10262 = 77;
+ optional bool field10263 = 88;
+ repeated .benchmarks.google_message3.Message9628 field10264 = 94;
+ extensions 57 to 57;
+ extensions 1000 to 536870911;
+}
+
+message Message11866 {
+ required .benchmarks.google_message3.Message11014 field11868 = 1;
+ optional bool field11869 = 2;
+ optional double field11870 = 3;
+ optional double field11871 = 4;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field11872 = 5;
+}
+
+message Message10469 {
+ optional string field10473 = 1;
+ optional float field10474 = 2;
+ optional int32 field10475 = 3;
+ optional int32 field10476 = 4;
+ optional int32 field10477 = 5;
+ optional bool field10478 = 6;
+ optional bool field10479 = 7;
+ optional int32 field10480 = 8;
+ optional float field10481 = 9;
+}
+
+message Message10818 {
+ optional .benchmarks.google_message3.Message10800 field10819 = 1;
+ optional .benchmarks.google_message3.Message10801 field10820 = 2;
+}
+
+message Message10773 {
+ optional bool field10774 = 9;
+ optional bool field10775 = 1;
+ optional bool field10776 = 23;
+ optional bool field10777 = 2;
+ optional bool field10778 = 3;
+ optional int32 field10779 = 4;
+ optional int32 field10780 = 5;
+ optional int32 field10781 = 6;
+ optional int32 field10782 = 7;
+ optional int32 field10783 = 8;
+ optional int32 field10784 = 10;
+ optional .benchmarks.google_message3.Message10749 field10785 = 11;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field10786 = 12;
+ optional bool field10787 = 13;
+ optional bool field10788 = 15;
+ optional bool field10789 = 16;
+ optional int32 field10790 = 17;
+ optional int32 field10791 = 18;
+ optional bool field10792 = 19;
+ optional bool field10793 = 20;
+ optional bool field10794 = 21;
+ optional .benchmarks.google_message3.UnusedEnum field10795 = 14;
+ optional .benchmarks.google_message3.UnusedEnum field10796 = 22;
+}
+
+message Message13145 {
+ required .benchmarks.google_message3.Enum13146 field13155 = 1;
+ optional float field13156 = 2;
+ optional float field13157 = 3;
+ extensions 1000 to 536870911;
+}
+
+message Message16686 {
+}
+
+message Message12796 {
+ repeated fixed64 field12800 = 1;
+ optional uint64 field12801 = 2;
+}
+
+message Message6722 {
+}
+
+message Message6727 {
+}
+
+message Message6724 {
+}
+
+message Message6735 {
+}
+
+message Message8183 {
+ optional string field8226 = 1;
+ optional string field8227 = 2;
+}
+
+message Message8301 {
+ optional string field8328 = 1;
+ optional .benchmarks.google_message3.Message7966 field8329 = 2;
+ optional string field8330 = 3;
+ optional string field8331 = 4;
+ repeated .benchmarks.google_message3.Message8290 field8332 = 5;
+ optional .benchmarks.google_message3.Message7966 field8333 = 6;
+ repeated .benchmarks.google_message3.Message8298 field8334 = 7;
+ optional .benchmarks.google_message3.Message8300 field8335 = 8;
+ optional int64 field8336 = 9;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8337 = 10;
+ optional .benchmarks.google_message3.Message7965 field8338 = 11;
+ extensions 64 to 536870911;
+}
+
+message Message8456 {
+}
+
+message Message8302 {
+ optional string field8339 = 1;
+ optional .benchmarks.google_message3.Message7966 field8340 = 2;
+ optional string field8341 = 3;
+ optional string field8342 = 4;
+ optional string field8343 = 5;
+ optional string field8344 = 6;
+ optional string field8345 = 7;
+ optional int64 field8346 = 8;
+ optional int64 field8347 = 9;
+ repeated .benchmarks.google_message3.Message8290 field8348 = 10;
+ optional string field8349 = 11;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8350 = 12;
+ optional .benchmarks.google_message3.Message8291 field8351 = 13;
+ optional int64 field8352 = 14;
+ optional .benchmarks.google_message3.Message8296 field8353 = 15;
+ optional string field8354 = 16;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field8355 = 17;
+ repeated int32 field8356 = 18;
+ repeated int32 field8357 = 19;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field8358 = 20;
+ optional .benchmarks.google_message3.Message7965 field8359 = 21;
+ extensions 64 to 536870911;
+}
+
+message Message8457 {
+}
+
+message Message8449 {
+ optional string field8458 = 1;
+ optional bool field8459 = 2;
+ optional .benchmarks.google_message3.Enum8450 field8460 = 3;
+ repeated string field8461 = 4;
+ optional string field8462 = 5;
+ optional string field8463 = 6;
+ optional .benchmarks.google_message3.Message7966 field8464 = 7;
+}
+
+message Message13358 {
+ required fixed64 field13359 = 1;
+ required fixed64 field13360 = 2;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field13361 = 3;
+}
+
+message Message13912 {
+ required fixed32 field13913 = 1;
+ required fixed32 field13914 = 2;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field13915 = 500;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field13916 = 15;
+}
+
+message Message24316 {
+ repeated string field24443 = 1;
+ repeated string field24444 = 2;
+ repeated string field24445 = 3;
+}
+
+message Message24312 {
+ optional string field24421 = 1;
+ optional string field24422 = 2;
+ repeated string field24423 = 3;
+ repeated string field24424 = 4;
+ repeated string field24425 = 5;
+ repeated string field24426 = 6;
+}
+
+message Message24313 {
+ optional string field24427 = 1;
+ optional string field24428 = 2;
+ repeated string field24429 = 3;
+ optional string field24430 = 4;
+ optional string field24431 = 5;
+ optional string field24432 = 6;
+ optional string field24433 = 7;
+ repeated string field24434 = 8;
+ optional string field24435 = 9;
+ repeated string field24436 = 10;
+}
+
+message Message24315 {
+ required string field24440 = 1;
+ repeated string field24441 = 2;
+ repeated string field24442 = 3;
+}
+
+message Message716 {
+ required string field872 = 1;
+ required int32 field873 = 2;
+ optional bool field874 = 3;
+ optional .benchmarks.google_message3.Message717 field875 = 4;
+}
+
+message Message718 {
+ repeated string field878 = 1;
+ repeated string field879 = 2;
+ optional string field880 = 3;
+}
+
+message Message703 {
+ required string field795 = 1;
+ repeated string field796 = 2;
+ repeated string field797 = 3;
+ optional string field798 = 4;
+ repeated string field799 = 5;
+}
+
+message Message715 {
+ required string field859 = 1;
+ optional string field860 = 7;
+ repeated .benchmarks.google_message3.Message707 field861 = 2;
+ repeated .benchmarks.google_message3.Message708 field862 = 3;
+ repeated .benchmarks.google_message3.Message711 field863 = 4;
+ repeated .benchmarks.google_message3.Message712 field864 = 5;
+ repeated .benchmarks.google_message3.Message713 field865 = 6;
+ repeated .benchmarks.google_message3.Message714 field866 = 8;
+ repeated .benchmarks.google_message3.Message710 field867 = 9;
+ repeated .benchmarks.google_message3.Message709 field868 = 10;
+ repeated .benchmarks.google_message3.Message705 field869 = 11;
+ repeated .benchmarks.google_message3.Message702 field870 = 12;
+ repeated .benchmarks.google_message3.Message706 field871 = 13;
+}
+
+message Message700 {
+ repeated string field789 = 1;
+ repeated string field790 = 2;
+}
+
+message Message699 {
+ required string field787 = 1;
+ repeated string field788 = 2;
+}
+
+message Message698 {
+ optional string field779 = 1;
+ optional string field780 = 2;
+ optional string field781 = 3;
+ optional string field782 = 4;
+ optional uint64 field783 = 5;
+ optional uint32 field784 = 6;
+ optional int64 field785 = 7;
+ repeated string field786 = 8;
+}
+
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_6.proto b/benchmarks/datasets/google_message3/benchmark_message3_6.proto
new file mode 100644
index 00000000..98e1529e
--- /dev/null
+++ b/benchmarks/datasets/google_message3/benchmark_message3_6.proto
@@ -0,0 +1,454 @@
+syntax = "proto2";
+
+import "datasets/google_message3/benchmark_message3_7.proto";
+import "datasets/google_message3/benchmark_message3_8.proto";
+package benchmarks.google_message3;
+
+option cc_enable_arenas = true;
+option java_package = "com.google.protobuf.benchmarks";
+
+message Message10576 {
+}
+
+message Message10154 {
+ optional bytes field10192 = 1;
+ optional int32 field10193 = 2;
+}
+
+message Message8944 {
+ optional string field9045 = 2;
+ optional string field9046 = 3;
+ optional string field9047 = 23;
+ optional string field9048 = 52;
+ optional int32 field9049 = 53;
+ optional int32 field9050 = 54;
+ optional float field9051 = 55;
+ optional float field9052 = 56;
+ optional string field9053 = 57;
+ optional int64 field9054 = 1;
+ optional bool field9055 = 4;
+ optional int32 field9056 = 5;
+ optional int32 field9057 = 6;
+ optional int32 field9058 = 7;
+ optional float field9059 = 8;
+ optional float field9060 = 11;
+ optional float field9061 = 9;
+ optional float field9062 = 10;
+ optional float field9063 = 13;
+ optional bool field9064 = 14;
+ optional float field9065 = 70;
+ optional int32 field9066 = 71;
+ optional .benchmarks.google_message3.Enum8945 field9067 = 15;
+ optional int32 field9068 = 16;
+ optional int32 field9069 = 17;
+ optional float field9070 = 18;
+ optional float field9071 = 19;
+ optional int32 field9072 = 28;
+ optional int32 field9073 = 29;
+ optional float field9074 = 60;
+ optional float field9075 = 61;
+ optional int32 field9076 = 72;
+ optional int32 field9077 = 73;
+ optional .benchmarks.google_message3.Enum8951 field9078 = 62;
+ optional string field9079 = 20;
+ optional string field9080 = 21;
+ optional string field9081 = 22;
+ optional double field9082 = 31;
+ optional double field9083 = 32;
+ optional double field9084 = 33;
+ optional double field9085 = 36;
+ optional .benchmarks.google_message3.UnusedEnum field9086 = 37;
+ optional double field9087 = 38;
+ optional double field9088 = 39;
+ optional double field9089 = 63;
+ optional double field9090 = 64;
+ optional double field9091 = 65;
+ optional double field9092 = 34;
+ optional .benchmarks.google_message3.UnusedEnum field9093 = 35;
+ optional .benchmarks.google_message3.UnusedEnum field9094 = 66;
+ optional string field9095 = 40;
+ optional string field9096 = 41;
+ optional string field9097 = 42;
+ optional string field9098 = 43;
+ optional string field9099 = 44;
+ optional string field9100 = 45;
+ optional string field9101 = 46;
+ optional string field9102 = 47;
+ optional string field9103 = 48;
+ optional string field9104 = 49;
+ optional .benchmarks.google_message3.Message8939 field9105 = 100;
+ optional int64 field9106 = 101;
+}
+
+message Message9182 {
+ optional string field9205 = 1;
+ optional string field9206 = 2;
+ optional float field9207 = 16;
+ optional int32 field9208 = 17;
+ optional int32 field9209 = 27;
+ optional int32 field9210 = 7;
+ optional int32 field9211 = 8;
+ optional float field9212 = 26;
+ optional float field9213 = 22;
+ optional bool field9214 = 28;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field9215 = 21;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field9216 = 25;
+ repeated .benchmarks.google_message3.Message9181 field9217 = 29;
+ optional bool field9218 = 18;
+ optional bool field9219 = 19;
+ optional bool field9220 = 20;
+ optional .benchmarks.google_message3.Message9164 field9221 = 30;
+ optional .benchmarks.google_message3.Message9165 field9222 = 31;
+ optional .benchmarks.google_message3.Message9166 field9223 = 32;
+ optional float field9224 = 33;
+ optional .benchmarks.google_message3.Message9151 field9225 = 34;
+ optional float field9226 = 35;
+ optional float field9227 = 36;
+ optional float field9228 = 37;
+ optional float field9229 = 38;
+ optional float field9230 = 39;
+ extensions 3 to 6;
+ extensions 9 to 15;
+ extensions 23 to 23;
+ extensions 24 to 24;
+ extensions 1000 to 536870911;
+}
+
+message Message9160 {
+ optional int32 field9161 = 1;
+ optional bytes field9162 = 2;
+}
+
+message Message9242 {
+ repeated .benchmarks.google_message3.Enum9243 field9327 = 1;
+}
+
+message Message8890 {
+ repeated .benchmarks.google_message3.Message8888 field8916 = 1;
+}
+
+message Message9123 {
+ optional float field9135 = 1;
+}
+
+message Message9628 {
+ optional .benchmarks.google_message3.Message9627 field9673 = 1;
+ optional string field9674 = 2;
+ repeated int32 field9675 = 3;
+ optional int32 field9676 = 4;
+}
+
+message Message11014 {
+ optional int32 field11780 = 40;
+ optional string field11781 = 46;
+ optional bool field11782 = 47;
+ optional .benchmarks.google_message3.Enum11107 field11783 = 1;
+ optional int32 field11784 = 2;
+ optional double field11785 = 4;
+ optional int32 field11786 = 5;
+ optional int32 field11787 = 6;
+ optional double field11788 = 7;
+ optional double field11789 = 8;
+ optional int64 field11790 = 9;
+ optional bool field11791 = 10;
+ optional int64 field11792 = 28;
+ optional bool field11793 = 37;
+ optional .benchmarks.google_message3.Enum11541 field11794 = 44;
+ optional double field11795 = 49;
+ optional double field11796 = 51;
+ optional int64 field11797 = 54;
+ optional int64 field11798 = 55;
+ optional .benchmarks.google_message3.UnusedEnum field11799 = 57;
+ optional .benchmarks.google_message3.Enum11468 field11800 = 58;
+ optional int32 field11801 = 59;
+ optional .benchmarks.google_message3.UnusedEnum field11802 = 60;
+ optional int32 field11803 = 61;
+ optional int32 field11804 = 62;
+ optional int32 field11805 = 69;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field11806 = 68;
+ repeated .benchmarks.google_message3.Message11018 field11807 = 71;
+ optional bool field11808 = 50;
+ optional bool field11809 = 56;
+ optional bool field11810 = 66;
+ optional bool field11811 = 63;
+ optional bool field11812 = 64;
+ optional bool field11813 = 65;
+ optional bool field11814 = 67;
+ optional .benchmarks.google_message3.Enum11107 field11815 = 15;
+ optional int64 field11816 = 16;
+ optional double field11817 = 17;
+ optional int64 field11818 = 18;
+ optional int32 field11819 = 19;
+ optional int64 field11820 = 20;
+ optional int32 field11821 = 42;
+ optional int64 field11822 = 52;
+ optional int64 field11823 = 53;
+ optional int64 field11824 = 41;
+ optional double field11825 = 48;
+ repeated .benchmarks.google_message3.Message11020 field11826 = 70;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field11827 = 72;
+ optional double field11828 = 25;
+ optional string field11829 = 26;
+ optional int64 field11830 = 27;
+ optional int64 field11831 = 32;
+ optional uint64 field11832 = 33;
+ optional bool field11833 = 29;
+ optional bool field11834 = 34;
+ optional string field11835 = 30;
+ optional int32 field11836 = 3;
+ optional int32 field11837 = 31;
+ optional int32 field11838 = 73;
+ optional int32 field11839 = 35;
+ optional .benchmarks.google_message3.Enum11022 field11840 = 36;
+ optional .benchmarks.google_message3.Message11013 field11841 = 38;
+ optional double field11842 = 39;
+ optional int32 field11843 = 45;
+ optional bool field11844 = 74;
+}
+
+message Message10801 {
+ optional .benchmarks.google_message3.Message10800 field10812 = 1;
+ repeated .benchmarks.google_message3.Message10802 field10813 = 2;
+ optional int32 field10814 = 3;
+}
+
+message Message10749 {
+ repeated .benchmarks.google_message3.Message10748 field10754 = 1;
+}
+
+message Message8298 {
+ optional .benchmarks.google_message3.Message7966 field8321 = 1;
+ optional int64 field8322 = 2;
+ optional string field8323 = 3;
+}
+
+message Message8300 {
+ optional string field8326 = 1;
+ optional .benchmarks.google_message3.Message7966 field8327 = 2;
+}
+
+message Message8291 {
+ optional string field8306 = 1;
+ optional int32 field8307 = 2;
+ optional string field8308 = 3;
+ optional string field8309 = 4;
+ optional .benchmarks.google_message3.Enum8292 field8310 = 5;
+}
+
+message Message8296 {
+ optional .benchmarks.google_message3.Message7966 field8311 = 1;
+ optional string field8312 = 2;
+ optional .benchmarks.google_message3.Message7966 field8313 = 3;
+ optional int32 field8314 = 4;
+ optional int32 field8315 = 5;
+ optional string field8316 = 6;
+}
+
+message Message7965 {
+ optional int32 field7967 = 1;
+ optional int32 field7968 = 2;
+}
+
+message Message8290 {
+ optional string field8304 = 1;
+ optional string field8305 = 2;
+}
+
+message Message717 {
+ repeated string field876 = 1;
+ optional double field877 = 2;
+}
+
+message Message713 {
+ required .benchmarks.google_message3.Message708 field852 = 1;
+ repeated string field853 = 2;
+}
+
+message Message705 {
+ required string field807 = 1;
+ optional string field808 = 2;
+ optional string field809 = 3;
+ optional bool field810 = 4;
+ optional string field811 = 5;
+ optional string field812 = 6;
+ repeated string field813 = 7;
+}
+
+message Message709 {
+ repeated string field829 = 1;
+ repeated string field830 = 2;
+ repeated string field831 = 3;
+ repeated string field832 = 4;
+ repeated string field833 = 5;
+}
+
+message Message702 {
+ optional string field793 = 1;
+ optional string field794 = 2;
+}
+
+message Message714 {
+ optional string field854 = 1;
+ optional string field855 = 2;
+ optional string field856 = 3;
+ optional string field857 = 4;
+ optional uint32 field858 = 5;
+}
+
+message Message710 {
+ repeated string field834 = 1;
+ optional string field835 = 2;
+ optional string field836 = 3;
+ repeated string field837 = 4;
+ repeated string field838 = 5;
+}
+
+message Message706 {
+ repeated string field814 = 1;
+ optional string field815 = 2;
+ repeated string field816 = 3;
+ repeated string field817 = 4;
+}
+
+message Message707 {
+ required string field818 = 1;
+ required string field819 = 2;
+ required string field820 = 3;
+ optional bool field821 = 4;
+ repeated string field822 = 5;
+}
+
+message Message711 {
+ optional .benchmarks.google_message3.UnusedEmptyMessage field839 = 1;
+ repeated string field840 = 4;
+ repeated string field841 = 2;
+ repeated string field842 = 3;
+}
+
+message Message712 {
+ repeated string field843 = 1;
+ required string field844 = 2;
+ optional string field845 = 3;
+ repeated string field846 = 4;
+ repeated string field847 = 5;
+ optional string field848 = 6;
+ repeated string field849 = 7;
+ optional string field850 = 8;
+ optional string field851 = 9;
+}
+
+message Message8939 {
+ optional string field9010 = 1;
+ optional string field9011 = 2;
+ optional string field9012 = 3;
+ repeated string field9013 = 4;
+ optional string field9014 = 5;
+ repeated group Message8940 = 11 {
+ }
+ optional int64 field9016 = 21;
+ optional int64 field9017 = 22;
+ optional int64 field9018 = 23;
+ optional group Message8941 = 31 {
+ optional string field9033 = 32;
+ optional string field9034 = 33;
+ optional string field9035 = 34;
+ optional string field9036 = 35;
+ optional string field9037 = 36;
+ optional string field9038 = 37;
+ }
+ optional .benchmarks.google_message3.Message8942 field9020 = 38;
+ repeated .benchmarks.google_message3.UnusedEmptyMessage field9021 = 39;
+ repeated string field9022 = 41;
+ optional string field9023 = 42;
+ optional string field9024 = 43;
+ optional string field9025 = 44;
+ optional string field9026 = 45;
+ optional string field9027 = 46;
+ optional string field9028 = 47;
+ optional .benchmarks.google_message3.UnusedEnum field9029 = 48;
+ optional .benchmarks.google_message3.UnusedEnum field9030 = 49;
+ optional group Message8943 = 51 {
+ optional string field9039 = 1;
+ optional string field9040 = 2;
+ optional string field9041 = 3;
+ optional string field9042 = 4;
+ optional string field9043 = 5;
+ optional string field9044 = 6;
+ }
+}
+
+message Message9181 {
+ optional string field9204 = 1;
+}
+
+message Message9164 {
+ optional int32 field9168 = 1;
+ optional int32 field9169 = 2;
+ optional int32 field9170 = 3;
+}
+
+message Message9165 {
+ optional float field9171 = 1;
+ optional float field9172 = 2;
+}
+
+message Message9166 {
+ optional float field9173 = 1;
+ optional int32 field9174 = 2;
+}
+
+message Message9151 {
+ optional double field9152 = 1;
+ optional double field9153 = 2;
+ optional float field9154 = 3;
+ optional float field9155 = 4;
+ optional float field9156 = 5;
+ optional float field9157 = 6;
+ optional float field9158 = 7;
+ optional float field9159 = 8;
+}
+
+message Message8888 {
+ optional int32 field8908 = 1;
+ optional .benchmarks.google_message3.Enum8900 field8909 = 4;
+ repeated int32 field8910 = 2 [packed = true];
+ optional bytes field8911 = 3;
+}
+
+message Message9627 {
+ required int32 field9668 = 1;
+ required int32 field9669 = 2;
+ required int32 field9670 = 3;
+ required int32 field9671 = 4;
+ optional float field9672 = 5;
+}
+
+message Message11020 {
+}
+
+message Message11013 {
+ optional bytes field11757 = 19;
+ optional bytes field11758 = 1;
+ optional bytes field11759 = 2;
+ optional bytes field11760 = 3;
+ optional bytes field11761 = 4;
+ optional bytes field11762 = 5;
+ optional bytes field11763 = 6;
+ optional bytes field11764 = 7;
+ optional bytes field11765 = 8;
+ optional bytes field11766 = 9;
+ optional bytes field11767 = 10;
+ optional bytes field11768 = 11;
+ optional bytes field11769 = 12;
+ optional bytes field11770 = 13;
+ optional bytes field11771 = 14;
+ optional bytes field11772 = 15;
+ optional bytes field11773 = 16;
+ optional bytes field11774 = 17;
+ optional bytes field11775 = 18;
+ optional bytes field11776 = 20;
+ optional bytes field11777 = 21;
+ optional .benchmarks.google_message3.UnusedEmptyMessage field11778 = 23;
+ repeated .benchmarks.google_message3.Message11011 field11779 = 22;
+}
+
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_7.proto b/benchmarks/datasets/google_message3/benchmark_message3_7.proto
new file mode 100644
index 00000000..2497db5e
--- /dev/null
+++ b/benchmarks/datasets/google_message3/benchmark_message3_7.proto
@@ -0,0 +1,56 @@
+syntax = "proto2";
+
+package benchmarks.google_message3;
+
+option cc_enable_arenas = true;
+option java_package = "com.google.protobuf.benchmarks";
+
+message Message11018 {
+}
+
+message Message10800 {
+ optional string field10808 = 1;
+ optional int64 field10809 = 2;
+ optional bool field10810 = 3;
+ optional float field10811 = 4;
+}
+
+message Message10802 {
+}
+
+message Message10748 {
+ optional string field10750 = 1;
+ optional int32 field10751 = 2;
+ optional int32 field10752 = 3;
+ optional int32 field10753 = 4;
+}
+
+message Message7966 {
+ optional string field7969 = 1;
+ optional bool field7970 = 2;
+}
+
+message Message708 {
+ optional .benchmarks.google_message3.Message741 field823 = 1;
+ repeated string field824 = 6;
+ optional string field825 = 2;
+ optional string field826 = 3;
+ repeated string field827 = 4;
+ repeated string field828 = 5;
+}
+
+message Message8942 {
+}
+
+message Message11011 {
+ required bytes field11752 = 1;
+ required bytes field11753 = 2;
+}
+
+message UnusedEmptyMessage {
+}
+
+message Message741 {
+ repeated string field936 = 1;
+}
+
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_8.proto b/benchmarks/datasets/google_message3/benchmark_message3_8.proto
new file mode 100644
index 00000000..1d2b1472
--- /dev/null
+++ b/benchmarks/datasets/google_message3/benchmark_message3_8.proto
@@ -0,0 +1,1900 @@
+syntax = "proto2";
+
+package benchmarks.google_message3;
+
+option cc_enable_arenas = true;
+option java_package = "com.google.protobuf.benchmarks";
+
+enum Enum720 {
+ ENUM_VALUE721 = 1;
+ ENUM_VALUE722 = 2;
+}
+
+enum Enum3476 {
+ ENUM_VALUE3477 = 0;
+ ENUM_VALUE3478 = 1;
+ ENUM_VALUE3479 = 2;
+ ENUM_VALUE3480 = 3;
+ ENUM_VALUE3481 = 4;
+ ENUM_VALUE3482 = 5;
+ ENUM_VALUE3483 = 6;
+ ENUM_VALUE3484 = 7;
+ ENUM_VALUE3485 = 8;
+ ENUM_VALUE3486 = 9;
+ ENUM_VALUE3487 = 10;
+ ENUM_VALUE3488 = 11;
+ ENUM_VALUE3489 = 12;
+ ENUM_VALUE3490 = 13;
+ ENUM_VALUE3491 = 14;
+ ENUM_VALUE3492 = 15;
+ ENUM_VALUE3493 = 16;
+ ENUM_VALUE3494 = 17;
+ ENUM_VALUE3495 = 18;
+ ENUM_VALUE3496 = 19;
+ ENUM_VALUE3497 = 20;
+ ENUM_VALUE3498 = 21;
+ ENUM_VALUE3499 = 22;
+ ENUM_VALUE3500 = 23;
+ ENUM_VALUE3501 = 24;
+ ENUM_VALUE3502 = 25;
+ ENUM_VALUE3503 = 26;
+ ENUM_VALUE3504 = 27;
+ ENUM_VALUE3505 = 28;
+ ENUM_VALUE3506 = 29;
+ ENUM_VALUE3507 = 30;
+ ENUM_VALUE3508 = 31;
+ ENUM_VALUE3509 = 32;
+ ENUM_VALUE3510 = 33;
+ ENUM_VALUE3511 = 34;
+ ENUM_VALUE3512 = 35;
+ ENUM_VALUE3513 = 36;
+ ENUM_VALUE3514 = 37;
+ ENUM_VALUE3515 = 38;
+ ENUM_VALUE3516 = 39;
+ ENUM_VALUE3517 = 40;
+ ENUM_VALUE3518 = 41;
+ ENUM_VALUE3519 = 42;
+ ENUM_VALUE3520 = 43;
+ ENUM_VALUE3521 = 44;
+ ENUM_VALUE3522 = 45;
+ ENUM_VALUE3523 = 46;
+ ENUM_VALUE3524 = 47;
+ ENUM_VALUE3525 = 48;
+ ENUM_VALUE3526 = 49;
+ ENUM_VALUE3527 = 50;
+ ENUM_VALUE3528 = 51;
+ ENUM_VALUE3529 = 52;
+ ENUM_VALUE3530 = 53;
+ ENUM_VALUE3531 = 54;
+ ENUM_VALUE3532 = 55;
+ ENUM_VALUE3533 = 56;
+ ENUM_VALUE3534 = 57;
+ ENUM_VALUE3535 = 58;
+ ENUM_VALUE3536 = 59;
+ ENUM_VALUE3537 = 60;
+ ENUM_VALUE3538 = 61;
+ ENUM_VALUE3539 = 62;
+ ENUM_VALUE3540 = 63;
+ ENUM_VALUE3541 = 64;
+ ENUM_VALUE3542 = 65;
+ ENUM_VALUE3543 = 66;
+ ENUM_VALUE3544 = 67;
+ ENUM_VALUE3545 = 68;
+ ENUM_VALUE3546 = 69;
+ ENUM_VALUE3547 = 70;
+ ENUM_VALUE3548 = 71;
+ ENUM_VALUE3549 = 72;
+ ENUM_VALUE3550 = 73;
+ ENUM_VALUE3551 = 74;
+ ENUM_VALUE3552 = 75;
+ ENUM_VALUE3553 = 76;
+ ENUM_VALUE3554 = 77;
+ ENUM_VALUE3555 = 78;
+ ENUM_VALUE3556 = 79;
+ ENUM_VALUE3557 = 80;
+ ENUM_VALUE3558 = 81;
+ ENUM_VALUE3559 = 82;
+ ENUM_VALUE3560 = 83;
+ ENUM_VALUE3561 = 84;
+ ENUM_VALUE3562 = 85;
+ ENUM_VALUE3563 = 86;
+ ENUM_VALUE3564 = 87;
+ ENUM_VALUE3565 = 88;
+ ENUM_VALUE3566 = 89;
+ ENUM_VALUE3567 = 90;
+ ENUM_VALUE3568 = 91;
+ ENUM_VALUE3569 = 92;
+ ENUM_VALUE3570 = 93;
+ ENUM_VALUE3571 = 94;
+ ENUM_VALUE3572 = 95;
+ ENUM_VALUE3573 = 96;
+ ENUM_VALUE3574 = 97;
+ ENUM_VALUE3575 = 98;
+ ENUM_VALUE3576 = 99;
+ ENUM_VALUE3577 = 100;
+ ENUM_VALUE3578 = 101;
+ ENUM_VALUE3579 = 102;
+ ENUM_VALUE3580 = 103;
+ ENUM_VALUE3581 = 104;
+ ENUM_VALUE3582 = 105;
+ ENUM_VALUE3583 = 106;
+ ENUM_VALUE3584 = 107;
+ ENUM_VALUE3585 = 108;
+ ENUM_VALUE3586 = 109;
+ ENUM_VALUE3587 = 110;
+ ENUM_VALUE3588 = 111;
+ ENUM_VALUE3589 = 112;
+ ENUM_VALUE3590 = 113;
+ ENUM_VALUE3591 = 114;
+ ENUM_VALUE3592 = 115;
+ ENUM_VALUE3593 = 116;
+ ENUM_VALUE3594 = 117;
+ ENUM_VALUE3595 = 118;
+ ENUM_VALUE3596 = 119;
+ ENUM_VALUE3597 = 120;
+ ENUM_VALUE3598 = 121;
+ ENUM_VALUE3599 = 122;
+ ENUM_VALUE3600 = 123;
+ ENUM_VALUE3601 = 124;
+ ENUM_VALUE3602 = 125;
+ ENUM_VALUE3603 = 126;
+ ENUM_VALUE3604 = 127;
+ ENUM_VALUE3605 = 128;
+ ENUM_VALUE3606 = 129;
+ ENUM_VALUE3607 = 130;
+ ENUM_VALUE3608 = 131;
+ ENUM_VALUE3609 = 132;
+ ENUM_VALUE3610 = 133;
+ ENUM_VALUE3611 = 134;
+ ENUM_VALUE3612 = 135;
+ ENUM_VALUE3613 = 136;
+ ENUM_VALUE3614 = 137;
+ ENUM_VALUE3615 = 138;
+ ENUM_VALUE3616 = 139;
+ ENUM_VALUE3617 = 140;
+ ENUM_VALUE3618 = 141;
+ ENUM_VALUE3619 = 142;
+ ENUM_VALUE3620 = 143;
+ ENUM_VALUE3621 = 144;
+ ENUM_VALUE3622 = 145;
+ ENUM_VALUE3623 = 146;
+ ENUM_VALUE3624 = 147;
+ ENUM_VALUE3625 = 148;
+ ENUM_VALUE3626 = 149;
+ ENUM_VALUE3627 = 150;
+ ENUM_VALUE3628 = 151;
+ ENUM_VALUE3629 = 152;
+ ENUM_VALUE3630 = 153;
+ ENUM_VALUE3631 = 154;
+ ENUM_VALUE3632 = 155;
+ ENUM_VALUE3633 = 156;
+ ENUM_VALUE3634 = 157;
+ ENUM_VALUE3635 = 158;
+ ENUM_VALUE3636 = 159;
+ ENUM_VALUE3637 = 160;
+ ENUM_VALUE3638 = 161;
+ ENUM_VALUE3639 = 162;
+ ENUM_VALUE3640 = 163;
+ ENUM_VALUE3641 = 164;
+ ENUM_VALUE3642 = 165;
+ ENUM_VALUE3643 = 166;
+ ENUM_VALUE3644 = 167;
+ ENUM_VALUE3645 = 168;
+ ENUM_VALUE3646 = 169;
+ ENUM_VALUE3647 = 170;
+ ENUM_VALUE3648 = 171;
+ ENUM_VALUE3649 = 172;
+ ENUM_VALUE3650 = 173;
+ ENUM_VALUE3651 = 174;
+ ENUM_VALUE3652 = 175;
+ ENUM_VALUE3653 = 176;
+ ENUM_VALUE3654 = 177;
+ ENUM_VALUE3655 = 178;
+ ENUM_VALUE3656 = 179;
+ ENUM_VALUE3657 = 180;
+ ENUM_VALUE3658 = 181;
+ ENUM_VALUE3659 = 182;
+ ENUM_VALUE3660 = 183;
+}
+
+enum Enum3805 {
+ ENUM_VALUE3806 = 0;
+ ENUM_VALUE3807 = 1;
+ ENUM_VALUE3808 = 2;
+ ENUM_VALUE3809 = 3;
+ ENUM_VALUE3810 = 4;
+ ENUM_VALUE3811 = 5;
+ ENUM_VALUE3812 = 6;
+ ENUM_VALUE3813 = 7;
+ ENUM_VALUE3814 = 8;
+ ENUM_VALUE3815 = 9;
+ ENUM_VALUE3816 = 11;
+ ENUM_VALUE3817 = 10;
+}
+
+enum Enum3783 {
+ ENUM_VALUE3784 = 0;
+ ENUM_VALUE3785 = 1;
+ ENUM_VALUE3786 = 2;
+ ENUM_VALUE3787 = 3;
+ ENUM_VALUE3788 = 4;
+ ENUM_VALUE3789 = 5;
+ ENUM_VALUE3790 = 6;
+ ENUM_VALUE3791 = 7;
+ ENUM_VALUE3792 = 8;
+ ENUM_VALUE3793 = 9;
+ ENUM_VALUE3794 = 10;
+ ENUM_VALUE3795 = 11;
+ ENUM_VALUE3796 = 12;
+ ENUM_VALUE3797 = 13;
+ ENUM_VALUE3798 = 14;
+ ENUM_VALUE3799 = 15;
+ ENUM_VALUE3800 = 16;
+ ENUM_VALUE3801 = 20;
+ ENUM_VALUE3802 = 21;
+ ENUM_VALUE3803 = 50;
+}
+
+enum Enum3851 {
+ ENUM_VALUE3852 = 0;
+ ENUM_VALUE3853 = 1;
+ ENUM_VALUE3854 = 2;
+ ENUM_VALUE3855 = 3;
+ ENUM_VALUE3856 = 4;
+ ENUM_VALUE3857 = 5;
+ ENUM_VALUE3858 = 6;
+ ENUM_VALUE3859 = 7;
+ ENUM_VALUE3860 = 8;
+ ENUM_VALUE3861 = 9;
+ ENUM_VALUE3862 = 10;
+ ENUM_VALUE3863 = 11;
+ ENUM_VALUE3864 = 12;
+ ENUM_VALUE3865 = 13;
+ ENUM_VALUE3866 = 14;
+ ENUM_VALUE3867 = 15;
+ ENUM_VALUE3868 = 16;
+ ENUM_VALUE3869 = 17;
+}
+
+enum UnusedEnum {
+ UNUSED_ENUM_VALUE1 = 0;
+ UNUSED_ENUM_VALUE2 = 1;
+}
+
+enum Enum4146 {
+ ENUM_VALUE4147 = 0;
+ ENUM_VALUE4148 = 1;
+ ENUM_VALUE4149 = 2;
+ ENUM_VALUE4150 = 3;
+ ENUM_VALUE4151 = 4;
+}
+
+enum Enum4160 {
+ ENUM_VALUE4161 = 0;
+ ENUM_VALUE4162 = 1;
+}
+
+enum Enum4152 {
+ ENUM_VALUE4153 = 0;
+ ENUM_VALUE4154 = 1;
+ ENUM_VALUE4155 = 2;
+ ENUM_VALUE4156 = 3;
+ ENUM_VALUE4157 = 4;
+ ENUM_VALUE4158 = 5;
+ ENUM_VALUE4159 = 6;
+}
+
+enum Enum6025 {
+ ENUM_VALUE6026 = 0;
+ ENUM_VALUE6027 = 1;
+ ENUM_VALUE6028 = 2;
+ ENUM_VALUE6029 = 3;
+ ENUM_VALUE6030 = 4;
+ ENUM_VALUE6031 = 5;
+ ENUM_VALUE6032 = 6;
+ ENUM_VALUE6033 = 7;
+ ENUM_VALUE6034 = 8;
+ ENUM_VALUE6035 = 9;
+ ENUM_VALUE6036 = 10;
+ ENUM_VALUE6037 = 11;
+ ENUM_VALUE6038 = 12;
+ ENUM_VALUE6039 = 13;
+ ENUM_VALUE6040 = 14;
+ ENUM_VALUE6041 = 15;
+ ENUM_VALUE6042 = 16;
+ ENUM_VALUE6043 = 17;
+ ENUM_VALUE6044 = 18;
+ ENUM_VALUE6045 = 19;
+ ENUM_VALUE6046 = 20;
+ ENUM_VALUE6047 = 21;
+}
+
+enum Enum6065 {
+ ENUM_VALUE6066 = 0;
+ ENUM_VALUE6067 = 1;
+ ENUM_VALUE6068 = 2;
+ ENUM_VALUE6069 = 3;
+ ENUM_VALUE6070 = 4;
+ ENUM_VALUE6071 = 5;
+ ENUM_VALUE6072 = 6;
+ ENUM_VALUE6073 = 7;
+ ENUM_VALUE6074 = 8;
+ ENUM_VALUE6075 = 9;
+ ENUM_VALUE6076 = 10;
+ ENUM_VALUE6077 = 11;
+ ENUM_VALUE6078 = 12;
+ ENUM_VALUE6079 = 13;
+ ENUM_VALUE6080 = 14;
+}
+
+enum Enum6579 {
+ ENUM_VALUE6580 = 0;
+ ENUM_VALUE6581 = 2;
+ ENUM_VALUE6582 = 3;
+ ENUM_VALUE6583 = 5;
+ ENUM_VALUE6584 = 10;
+ ENUM_VALUE6585 = 15;
+ ENUM_VALUE6586 = 25;
+ ENUM_VALUE6587 = 30;
+}
+
+enum Enum6588 {
+ ENUM_VALUE6589 = 0;
+ ENUM_VALUE6590 = 1;
+ ENUM_VALUE6591 = 2;
+ ENUM_VALUE6592 = 3;
+ ENUM_VALUE6593 = 4;
+ ENUM_VALUE6594 = 5;
+ ENUM_VALUE6595 = 6;
+ ENUM_VALUE6596 = 7;
+ ENUM_VALUE6597 = 8;
+ ENUM_VALUE6598 = 9;
+ ENUM_VALUE6599 = 10;
+ ENUM_VALUE6600 = 11;
+ ENUM_VALUE6601 = 12;
+ ENUM_VALUE6602 = 13;
+ ENUM_VALUE6603 = 14;
+ ENUM_VALUE6604 = 15;
+ ENUM_VALUE6605 = 16;
+ ENUM_VALUE6606 = 17;
+ ENUM_VALUE6607 = 19;
+ ENUM_VALUE6608 = 20;
+ ENUM_VALUE6609 = 21;
+ ENUM_VALUE6610 = 22;
+ ENUM_VALUE6611 = 23;
+ ENUM_VALUE6612 = 24;
+ ENUM_VALUE6613 = 25;
+ ENUM_VALUE6614 = 26;
+ ENUM_VALUE6615 = 27;
+ ENUM_VALUE6616 = 28;
+ ENUM_VALUE6617 = 29;
+ ENUM_VALUE6618 = 30;
+ ENUM_VALUE6619 = 31;
+ ENUM_VALUE6620 = 32;
+ ENUM_VALUE6621 = 33;
+ ENUM_VALUE6622 = 34;
+}
+
+enum Enum6769 {
+ ENUM_VALUE6770 = 0;
+ ENUM_VALUE6771 = 1;
+ ENUM_VALUE6772 = 2;
+}
+
+enum Enum6774 {
+ ENUM_VALUE6775 = 0;
+ ENUM_VALUE6776 = 1;
+ ENUM_VALUE6777 = 2;
+ ENUM_VALUE6778 = 3;
+ ENUM_VALUE6779 = 4;
+ ENUM_VALUE6780 = 5;
+ ENUM_VALUE6781 = 6;
+}
+
+enum Enum6782 {
+ ENUM_VALUE6783 = 0;
+ ENUM_VALUE6784 = 1;
+ ENUM_VALUE6785 = 2;
+ ENUM_VALUE6786 = 3;
+ ENUM_VALUE6787 = 4;
+ ENUM_VALUE6788 = 5;
+}
+
+enum Enum6858 {
+ ENUM_VALUE6859 = 1;
+ ENUM_VALUE6860 = 2;
+ ENUM_VALUE6861 = 3;
+ ENUM_VALUE6862 = 4;
+}
+
+enum Enum6815 {
+ ENUM_VALUE6816 = 0;
+ ENUM_VALUE6817 = 1;
+ ENUM_VALUE6818 = 2;
+ ENUM_VALUE6819 = 3;
+ ENUM_VALUE6820 = 4;
+ ENUM_VALUE6821 = 5;
+}
+
+enum Enum6822 {
+ ENUM_VALUE6823 = 0;
+ ENUM_VALUE6824 = 1;
+ ENUM_VALUE6825 = 2;
+ ENUM_VALUE6826 = 3;
+}
+
+enum Enum7654 {
+ ENUM_VALUE7655 = 1;
+ ENUM_VALUE7656 = 2;
+ ENUM_VALUE7657 = 3;
+}
+
+enum Enum8292 {
+ ENUM_VALUE8293 = 0;
+ ENUM_VALUE8294 = 1;
+ ENUM_VALUE8295 = 2;
+}
+
+enum Enum8450 {
+ ENUM_VALUE8451 = 0;
+ ENUM_VALUE8452 = 1;
+ ENUM_VALUE8453 = 2;
+}
+
+enum Enum8900 {
+ ENUM_VALUE8901 = 0;
+ ENUM_VALUE8902 = 1;
+ ENUM_VALUE8903 = 2;
+ ENUM_VALUE8904 = 3;
+ ENUM_VALUE8905 = 4;
+}
+
+enum Enum8945 {
+ ENUM_VALUE8946 = 0;
+ ENUM_VALUE8947 = 1;
+ ENUM_VALUE8948 = 2;
+ ENUM_VALUE8949 = 3;
+ ENUM_VALUE8950 = 4;
+}
+
+enum Enum8951 {
+ ENUM_VALUE8952 = 1;
+ ENUM_VALUE8953 = 2;
+ ENUM_VALUE8954 = 3;
+ ENUM_VALUE8955 = 4;
+ ENUM_VALUE8956 = 5;
+ ENUM_VALUE8957 = 6;
+ ENUM_VALUE8958 = 7;
+ ENUM_VALUE8959 = 8;
+}
+
+enum Enum9243 {
+ ENUM_VALUE9244 = -1;
+ ENUM_VALUE9245 = 0;
+ ENUM_VALUE9246 = 1;
+ ENUM_VALUE9247 = 2;
+ ENUM_VALUE9248 = 3;
+ ENUM_VALUE9249 = 4;
+ ENUM_VALUE9250 = 5;
+ ENUM_VALUE9251 = 6;
+ ENUM_VALUE9252 = 7;
+ ENUM_VALUE9253 = 8;
+ ENUM_VALUE9254 = 9;
+ ENUM_VALUE9255 = 10;
+ ENUM_VALUE9256 = 11;
+ ENUM_VALUE9257 = 12;
+ ENUM_VALUE9258 = 13;
+ ENUM_VALUE9259 = 14;
+ ENUM_VALUE9260 = 15;
+ ENUM_VALUE9261 = 16;
+ ENUM_VALUE9262 = 17;
+ ENUM_VALUE9263 = 71;
+ ENUM_VALUE9264 = 72;
+ ENUM_VALUE9265 = 73;
+ ENUM_VALUE9266 = 74;
+ ENUM_VALUE9267 = 18;
+ ENUM_VALUE9268 = 20;
+ ENUM_VALUE9269 = 21;
+ ENUM_VALUE9270 = 22;
+ ENUM_VALUE9271 = 23;
+ ENUM_VALUE9272 = 61;
+ ENUM_VALUE9273 = 62;
+ ENUM_VALUE9274 = 63;
+ ENUM_VALUE9275 = 64;
+ ENUM_VALUE9276 = 66;
+ ENUM_VALUE9277 = 67;
+ ENUM_VALUE9278 = 24;
+ ENUM_VALUE9279 = 25;
+ ENUM_VALUE9280 = 26;
+ ENUM_VALUE9281 = 27;
+ ENUM_VALUE9282 = 28;
+ ENUM_VALUE9283 = 29;
+ ENUM_VALUE9284 = 30;
+ ENUM_VALUE9285 = 31;
+ ENUM_VALUE9286 = 32;
+ ENUM_VALUE9287 = 33;
+ ENUM_VALUE9288 = 34;
+ ENUM_VALUE9289 = 35;
+ ENUM_VALUE9290 = 36;
+ ENUM_VALUE9291 = 37;
+ ENUM_VALUE9292 = 38;
+ ENUM_VALUE9293 = 39;
+ ENUM_VALUE9294 = 40;
+ ENUM_VALUE9295 = 41;
+ ENUM_VALUE9296 = 42;
+ ENUM_VALUE9297 = 43;
+ ENUM_VALUE9298 = 44;
+ ENUM_VALUE9299 = 45;
+ ENUM_VALUE9300 = 46;
+ ENUM_VALUE9301 = 47;
+ ENUM_VALUE9302 = 48;
+ ENUM_VALUE9303 = 49;
+ ENUM_VALUE9304 = 50;
+ ENUM_VALUE9305 = 51;
+ ENUM_VALUE9306 = 52;
+ ENUM_VALUE9307 = 53;
+ ENUM_VALUE9308 = 54;
+ ENUM_VALUE9309 = 55;
+ ENUM_VALUE9310 = 56;
+ ENUM_VALUE9311 = 57;
+ ENUM_VALUE9312 = 58;
+ ENUM_VALUE9313 = 59;
+ ENUM_VALUE9314 = 60;
+ ENUM_VALUE9315 = 68;
+ ENUM_VALUE9316 = 69;
+ ENUM_VALUE9317 = 70;
+ ENUM_VALUE9318 = 1000;
+ ENUM_VALUE9319 = 1001;
+ ENUM_VALUE9320 = 1002;
+ ENUM_VALUE9321 = 1003;
+ ENUM_VALUE9322 = 1004;
+ ENUM_VALUE9323 = 1005;
+ ENUM_VALUE9324 = 1006;
+ ENUM_VALUE9325 = 1007;
+ ENUM_VALUE9326 = 65;
+}
+
+enum Enum10157 {
+ ENUM_VALUE10158 = 0;
+ ENUM_VALUE10159 = 1;
+ ENUM_VALUE10160 = 2;
+ ENUM_VALUE10161 = 3;
+ ENUM_VALUE10162 = 4;
+ ENUM_VALUE10163 = 5;
+ ENUM_VALUE10164 = 6;
+ ENUM_VALUE10165 = 7;
+ ENUM_VALUE10166 = 8;
+}
+
+enum Enum10167 {
+ ENUM_VALUE10168 = 0;
+ ENUM_VALUE10169 = 1;
+ ENUM_VALUE10170 = 2;
+ ENUM_VALUE10171 = 3;
+ ENUM_VALUE10172 = 4;
+ ENUM_VALUE10173 = 5;
+ ENUM_VALUE10174 = 6;
+ ENUM_VALUE10175 = 7;
+ ENUM_VALUE10176 = 8;
+}
+
+enum Enum8862 {
+ ENUM_VALUE8863 = 0;
+ ENUM_VALUE8864 = 1;
+ ENUM_VALUE8865 = 2;
+ ENUM_VALUE8866 = 3;
+ ENUM_VALUE8867 = 4;
+ ENUM_VALUE8868 = 5;
+ ENUM_VALUE8869 = 6;
+ ENUM_VALUE8870 = 7;
+ ENUM_VALUE8871 = 13;
+ ENUM_VALUE8872 = 14;
+ ENUM_VALUE8873 = 8;
+ ENUM_VALUE8874 = 9;
+ ENUM_VALUE8875 = 10;
+ ENUM_VALUE8876 = 11;
+ ENUM_VALUE8877 = 12;
+ ENUM_VALUE8878 = 15;
+}
+
+enum Enum10325 {
+ ENUM_VALUE10326 = 0;
+ ENUM_VALUE10327 = 1;
+ ENUM_VALUE10328 = 2;
+ ENUM_VALUE10329 = 3;
+ ENUM_VALUE10330 = 4;
+ ENUM_VALUE10331 = 5;
+ ENUM_VALUE10332 = 6;
+ ENUM_VALUE10333 = 7;
+ ENUM_VALUE10334 = 8;
+}
+
+enum Enum10335 {
+ ENUM_VALUE10336 = 0;
+}
+
+enum Enum10337 {
+ ENUM_VALUE10338 = 0;
+ ENUM_VALUE10339 = 1;
+}
+
+enum Enum10392 {
+ ENUM_VALUE10393 = 0;
+ ENUM_VALUE10394 = 1;
+ ENUM_VALUE10395 = 2;
+ ENUM_VALUE10396 = 3;
+ ENUM_VALUE10397 = 4;
+ ENUM_VALUE10398 = 5;
+ ENUM_VALUE10399 = 6;
+ ENUM_VALUE10400 = 7;
+ ENUM_VALUE10401 = 8;
+ ENUM_VALUE10402 = 15;
+ ENUM_VALUE10403 = 9;
+ ENUM_VALUE10404 = 10;
+ ENUM_VALUE10405 = 11;
+ ENUM_VALUE10406 = 12;
+ ENUM_VALUE10407 = 13;
+ ENUM_VALUE10408 = 14;
+ ENUM_VALUE10409 = 101;
+ ENUM_VALUE10410 = 102;
+}
+
+enum Enum11107 {
+ ENUM_VALUE11108 = 0;
+ ENUM_VALUE11109 = 1;
+ ENUM_VALUE11110 = 2;
+ ENUM_VALUE11111 = 3;
+ ENUM_VALUE11112 = 4;
+ ENUM_VALUE11113 = 5;
+ ENUM_VALUE11114 = 6;
+ ENUM_VALUE11115 = 7;
+ ENUM_VALUE11116 = 8;
+ ENUM_VALUE11117 = 9;
+ ENUM_VALUE11118 = 10;
+ ENUM_VALUE11119 = 11;
+ ENUM_VALUE11120 = 12;
+ ENUM_VALUE11121 = 13;
+ ENUM_VALUE11122 = 14;
+ ENUM_VALUE11123 = 15;
+ ENUM_VALUE11124 = 16;
+ ENUM_VALUE11125 = 17;
+ ENUM_VALUE11126 = 18;
+ ENUM_VALUE11127 = 19;
+ ENUM_VALUE11128 = 20;
+ ENUM_VALUE11129 = 21;
+ ENUM_VALUE11130 = 22;
+ ENUM_VALUE11131 = 23;
+ ENUM_VALUE11132 = 24;
+ ENUM_VALUE11133 = 25;
+ ENUM_VALUE11134 = 26;
+ ENUM_VALUE11135 = 27;
+ ENUM_VALUE11136 = 28;
+ ENUM_VALUE11137 = 29;
+ ENUM_VALUE11138 = 30;
+ ENUM_VALUE11139 = 31;
+ ENUM_VALUE11140 = 32;
+ ENUM_VALUE11141 = 33;
+ ENUM_VALUE11142 = 34;
+ ENUM_VALUE11143 = 35;
+ ENUM_VALUE11144 = 36;
+ ENUM_VALUE11145 = 37;
+ ENUM_VALUE11146 = 38;
+ ENUM_VALUE11147 = 39;
+ ENUM_VALUE11148 = 40;
+ ENUM_VALUE11149 = 41;
+ ENUM_VALUE11150 = 42;
+ ENUM_VALUE11151 = 43;
+ ENUM_VALUE11152 = 44;
+ ENUM_VALUE11153 = 45;
+ ENUM_VALUE11154 = 46;
+ ENUM_VALUE11155 = 47;
+ ENUM_VALUE11156 = 48;
+ ENUM_VALUE11157 = 49;
+ ENUM_VALUE11158 = 50;
+ ENUM_VALUE11159 = 51;
+ ENUM_VALUE11160 = 52;
+ ENUM_VALUE11161 = 53;
+ ENUM_VALUE11162 = 54;
+ ENUM_VALUE11163 = 55;
+ ENUM_VALUE11164 = 56;
+ ENUM_VALUE11165 = 57;
+ ENUM_VALUE11166 = 58;
+ ENUM_VALUE11167 = 59;
+ ENUM_VALUE11168 = 60;
+ ENUM_VALUE11169 = 61;
+ ENUM_VALUE11170 = 62;
+ ENUM_VALUE11171 = 63;
+ ENUM_VALUE11172 = 64;
+ ENUM_VALUE11173 = 65;
+ ENUM_VALUE11174 = 66;
+ ENUM_VALUE11175 = 67;
+ ENUM_VALUE11176 = 68;
+ ENUM_VALUE11177 = 69;
+ ENUM_VALUE11178 = 70;
+ ENUM_VALUE11179 = 71;
+ ENUM_VALUE11180 = 72;
+ ENUM_VALUE11181 = 73;
+ ENUM_VALUE11182 = 74;
+ ENUM_VALUE11183 = 75;
+ ENUM_VALUE11184 = 76;
+ ENUM_VALUE11185 = 77;
+ ENUM_VALUE11186 = 78;
+ ENUM_VALUE11187 = 79;
+ ENUM_VALUE11188 = 80;
+ ENUM_VALUE11189 = 81;
+ ENUM_VALUE11190 = 82;
+ ENUM_VALUE11191 = 83;
+ ENUM_VALUE11192 = 84;
+ ENUM_VALUE11193 = 85;
+ ENUM_VALUE11194 = 86;
+ ENUM_VALUE11195 = 87;
+ ENUM_VALUE11196 = 88;
+ ENUM_VALUE11197 = 89;
+ ENUM_VALUE11198 = 90;
+ ENUM_VALUE11199 = 91;
+ ENUM_VALUE11200 = 92;
+ ENUM_VALUE11201 = 93;
+ ENUM_VALUE11202 = 94;
+ ENUM_VALUE11203 = 95;
+ ENUM_VALUE11204 = 96;
+ ENUM_VALUE11205 = 97;
+ ENUM_VALUE11206 = 98;
+ ENUM_VALUE11207 = 99;
+ ENUM_VALUE11208 = 100;
+ ENUM_VALUE11209 = 101;
+ ENUM_VALUE11210 = 102;
+ ENUM_VALUE11211 = 103;
+ ENUM_VALUE11212 = 104;
+ ENUM_VALUE11213 = 105;
+ ENUM_VALUE11214 = 106;
+ ENUM_VALUE11215 = 107;
+ ENUM_VALUE11216 = 108;
+ ENUM_VALUE11217 = 109;
+ ENUM_VALUE11218 = 110;
+ ENUM_VALUE11219 = 111;
+ ENUM_VALUE11220 = 112;
+ ENUM_VALUE11221 = 113;
+ ENUM_VALUE11222 = 114;
+ ENUM_VALUE11223 = 115;
+ ENUM_VALUE11224 = 116;
+ ENUM_VALUE11225 = 117;
+ ENUM_VALUE11226 = 118;
+ ENUM_VALUE11227 = 119;
+ ENUM_VALUE11228 = 120;
+ ENUM_VALUE11229 = 121;
+ ENUM_VALUE11230 = 122;
+ ENUM_VALUE11231 = 123;
+ ENUM_VALUE11232 = 124;
+ ENUM_VALUE11233 = 125;
+ ENUM_VALUE11234 = 126;
+ ENUM_VALUE11235 = 127;
+ ENUM_VALUE11236 = 128;
+ ENUM_VALUE11237 = 129;
+ ENUM_VALUE11238 = 130;
+ ENUM_VALUE11239 = 131;
+ ENUM_VALUE11240 = 132;
+ ENUM_VALUE11241 = 133;
+ ENUM_VALUE11242 = 134;
+ ENUM_VALUE11243 = 135;
+ ENUM_VALUE11244 = 136;
+ ENUM_VALUE11245 = 137;
+ ENUM_VALUE11246 = 138;
+ ENUM_VALUE11247 = 139;
+ ENUM_VALUE11248 = 140;
+ ENUM_VALUE11249 = 141;
+ ENUM_VALUE11250 = 142;
+ ENUM_VALUE11251 = 143;
+ ENUM_VALUE11252 = 144;
+ ENUM_VALUE11253 = 145;
+ ENUM_VALUE11254 = 146;
+ ENUM_VALUE11255 = 147;
+ ENUM_VALUE11256 = 148;
+ ENUM_VALUE11257 = 149;
+ ENUM_VALUE11258 = 150;
+ ENUM_VALUE11259 = 151;
+ ENUM_VALUE11260 = 152;
+ ENUM_VALUE11261 = 153;
+ ENUM_VALUE11262 = 154;
+ ENUM_VALUE11263 = 155;
+ ENUM_VALUE11264 = 156;
+ ENUM_VALUE11265 = 157;
+ ENUM_VALUE11266 = 158;
+ ENUM_VALUE11267 = 159;
+ ENUM_VALUE11268 = 160;
+ ENUM_VALUE11269 = 161;
+ ENUM_VALUE11270 = 163;
+ ENUM_VALUE11271 = 164;
+ ENUM_VALUE11272 = 165;
+ ENUM_VALUE11273 = 166;
+ ENUM_VALUE11274 = 167;
+ ENUM_VALUE11275 = 168;
+ ENUM_VALUE11276 = 169;
+ ENUM_VALUE11277 = 170;
+ ENUM_VALUE11278 = 171;
+ ENUM_VALUE11279 = 172;
+ ENUM_VALUE11280 = 173;
+ ENUM_VALUE11281 = 174;
+ ENUM_VALUE11282 = 175;
+ ENUM_VALUE11283 = 176;
+ ENUM_VALUE11284 = 177;
+ ENUM_VALUE11285 = 178;
+ ENUM_VALUE11286 = 179;
+ ENUM_VALUE11287 = 180;
+ ENUM_VALUE11288 = 181;
+ ENUM_VALUE11289 = 182;
+ ENUM_VALUE11290 = 183;
+ ENUM_VALUE11291 = 184;
+ ENUM_VALUE11292 = 185;
+ ENUM_VALUE11293 = 187;
+ ENUM_VALUE11294 = 188;
+ ENUM_VALUE11295 = 189;
+ ENUM_VALUE11296 = 190;
+ ENUM_VALUE11297 = 191;
+ ENUM_VALUE11298 = 192;
+ ENUM_VALUE11299 = 193;
+ ENUM_VALUE11300 = 194;
+ ENUM_VALUE11301 = 195;
+ ENUM_VALUE11302 = 196;
+ ENUM_VALUE11303 = 197;
+ ENUM_VALUE11304 = 198;
+ ENUM_VALUE11305 = 65535;
+ ENUM_VALUE11306 = 65536;
+ ENUM_VALUE11307 = 65537;
+ ENUM_VALUE11308 = 65538;
+ ENUM_VALUE11309 = 65539;
+ ENUM_VALUE11310 = 65540;
+ ENUM_VALUE11311 = 65541;
+ ENUM_VALUE11312 = 65542;
+ ENUM_VALUE11313 = 65543;
+ ENUM_VALUE11314 = 65544;
+ ENUM_VALUE11315 = 65545;
+ ENUM_VALUE11316 = 65546;
+ ENUM_VALUE11317 = 65547;
+ ENUM_VALUE11318 = 65548;
+ ENUM_VALUE11319 = 65549;
+ ENUM_VALUE11320 = 65550;
+ ENUM_VALUE11321 = 65551;
+ ENUM_VALUE11322 = 65552;
+ ENUM_VALUE11323 = 65553;
+ ENUM_VALUE11324 = 65554;
+ ENUM_VALUE11325 = 65555;
+ ENUM_VALUE11326 = 65556;
+ ENUM_VALUE11327 = 65557;
+ ENUM_VALUE11328 = 65558;
+ ENUM_VALUE11329 = 65559;
+ ENUM_VALUE11330 = 65560;
+ ENUM_VALUE11331 = 65561;
+ ENUM_VALUE11332 = 65562;
+ ENUM_VALUE11333 = 65563;
+ ENUM_VALUE11334 = 69632;
+ ENUM_VALUE11335 = 69633;
+ ENUM_VALUE11336 = 69634;
+ ENUM_VALUE11337 = 69635;
+ ENUM_VALUE11338 = 69636;
+ ENUM_VALUE11339 = 69637;
+ ENUM_VALUE11340 = 69638;
+ ENUM_VALUE11341 = 69639;
+ ENUM_VALUE11342 = 69640;
+ ENUM_VALUE11343 = 69641;
+ ENUM_VALUE11344 = 69642;
+ ENUM_VALUE11345 = 69643;
+ ENUM_VALUE11346 = 69644;
+ ENUM_VALUE11347 = 69645;
+ ENUM_VALUE11348 = 69646;
+ ENUM_VALUE11349 = 69647;
+ ENUM_VALUE11350 = 69648;
+ ENUM_VALUE11351 = 69649;
+ ENUM_VALUE11352 = 69650;
+ ENUM_VALUE11353 = 69651;
+ ENUM_VALUE11354 = 69652;
+ ENUM_VALUE11355 = 69653;
+ ENUM_VALUE11356 = 69654;
+ ENUM_VALUE11357 = 69655;
+ ENUM_VALUE11358 = 69656;
+ ENUM_VALUE11359 = 69657;
+ ENUM_VALUE11360 = 69658;
+ ENUM_VALUE11361 = 69659;
+ ENUM_VALUE11362 = 69660;
+ ENUM_VALUE11363 = 69661;
+ ENUM_VALUE11364 = 69662;
+ ENUM_VALUE11365 = 73728;
+ ENUM_VALUE11366 = 73729;
+ ENUM_VALUE11367 = 77824;
+ ENUM_VALUE11368 = 77825;
+ ENUM_VALUE11369 = 81920;
+ ENUM_VALUE11370 = 81921;
+ ENUM_VALUE11371 = 81922;
+ ENUM_VALUE11372 = 81923;
+ ENUM_VALUE11373 = 86016;
+ ENUM_VALUE11374 = 86017;
+ ENUM_VALUE11375 = 86018;
+ ENUM_VALUE11376 = 86019;
+ ENUM_VALUE11377 = 86020;
+ ENUM_VALUE11378 = 86021;
+ ENUM_VALUE11379 = 86022;
+ ENUM_VALUE11380 = 86023;
+ ENUM_VALUE11381 = 86024;
+ ENUM_VALUE11382 = 86025;
+ ENUM_VALUE11383 = 86026;
+ ENUM_VALUE11384 = 86027;
+ ENUM_VALUE11385 = 86028;
+ ENUM_VALUE11386 = 86029;
+ ENUM_VALUE11387 = 86030;
+ ENUM_VALUE11388 = 86031;
+ ENUM_VALUE11389 = 86032;
+ ENUM_VALUE11390 = 86033;
+ ENUM_VALUE11391 = 86034;
+ ENUM_VALUE11392 = 86035;
+ ENUM_VALUE11393 = 86036;
+ ENUM_VALUE11394 = 86037;
+ ENUM_VALUE11395 = 86038;
+ ENUM_VALUE11396 = 86039;
+ ENUM_VALUE11397 = 86040;
+ ENUM_VALUE11398 = 86041;
+ ENUM_VALUE11399 = 86042;
+ ENUM_VALUE11400 = 86043;
+ ENUM_VALUE11401 = 86044;
+ ENUM_VALUE11402 = 86045;
+ ENUM_VALUE11403 = 86046;
+ ENUM_VALUE11404 = 86047;
+ ENUM_VALUE11405 = 86048;
+ ENUM_VALUE11406 = 86049;
+ ENUM_VALUE11407 = 86050;
+ ENUM_VALUE11408 = 86051;
+ ENUM_VALUE11409 = 86052;
+ ENUM_VALUE11410 = 86053;
+ ENUM_VALUE11411 = 86054;
+ ENUM_VALUE11412 = 86055;
+ ENUM_VALUE11413 = 86056;
+ ENUM_VALUE11414 = 86057;
+ ENUM_VALUE11415 = 86058;
+ ENUM_VALUE11416 = 86059;
+ ENUM_VALUE11417 = 86060;
+ ENUM_VALUE11418 = 86061;
+ ENUM_VALUE11419 = 86062;
+ ENUM_VALUE11420 = 86063;
+ ENUM_VALUE11421 = 86064;
+ ENUM_VALUE11422 = 86065;
+ ENUM_VALUE11423 = 86066;
+ ENUM_VALUE11424 = 86067;
+ ENUM_VALUE11425 = 86068;
+ ENUM_VALUE11426 = 86069;
+ ENUM_VALUE11427 = 86070;
+ ENUM_VALUE11428 = 86071;
+ ENUM_VALUE11429 = 86072;
+ ENUM_VALUE11430 = 86073;
+ ENUM_VALUE11431 = 86074;
+ ENUM_VALUE11432 = 86077;
+ ENUM_VALUE11433 = 86078;
+ ENUM_VALUE11434 = 86079;
+ ENUM_VALUE11435 = 86080;
+ ENUM_VALUE11436 = 86081;
+ ENUM_VALUE11437 = 86082;
+ ENUM_VALUE11438 = 86083;
+ ENUM_VALUE11439 = 86084;
+ ENUM_VALUE11440 = 90112;
+ ENUM_VALUE11441 = 94208;
+ ENUM_VALUE11442 = 94209;
+ ENUM_VALUE11443 = 94210;
+ ENUM_VALUE11444 = 94211;
+ ENUM_VALUE11445 = 94212;
+ ENUM_VALUE11446 = 94213;
+ ENUM_VALUE11447 = 94214;
+ ENUM_VALUE11448 = 94215;
+ ENUM_VALUE11449 = 94216;
+ ENUM_VALUE11450 = 94217;
+ ENUM_VALUE11451 = 94218;
+ ENUM_VALUE11452 = 94219;
+ ENUM_VALUE11453 = 94220;
+ ENUM_VALUE11454 = 94221;
+ ENUM_VALUE11455 = 94222;
+ ENUM_VALUE11456 = 94223;
+ ENUM_VALUE11457 = 94224;
+ ENUM_VALUE11458 = 98304;
+ ENUM_VALUE11459 = 98305;
+ ENUM_VALUE11460 = 98306;
+ ENUM_VALUE11461 = 98307;
+ ENUM_VALUE11462 = 98308;
+ ENUM_VALUE11463 = 102400;
+ ENUM_VALUE11464 = 131072;
+ ENUM_VALUE11465 = 131073;
+ ENUM_VALUE11466 = 135168;
+ ENUM_VALUE11467 = 9439507;
+}
+
+enum Enum11541 {
+ ENUM_VALUE11542 = -1;
+ ENUM_VALUE11543 = 0;
+ ENUM_VALUE11544 = 1;
+ ENUM_VALUE11545 = 2;
+ ENUM_VALUE11546 = 3;
+ ENUM_VALUE11547 = 4;
+ ENUM_VALUE11548 = 5;
+ ENUM_VALUE11549 = 6;
+ ENUM_VALUE11550 = 7;
+ ENUM_VALUE11551 = 8;
+ ENUM_VALUE11552 = 9;
+ ENUM_VALUE11553 = 10;
+ ENUM_VALUE11554 = 11;
+ ENUM_VALUE11555 = 12;
+ ENUM_VALUE11556 = 13;
+ ENUM_VALUE11557 = 14;
+ ENUM_VALUE11558 = 15;
+ ENUM_VALUE11559 = 16;
+ ENUM_VALUE11560 = 17;
+ ENUM_VALUE11561 = 18;
+ ENUM_VALUE11562 = 19;
+ ENUM_VALUE11563 = 20;
+ ENUM_VALUE11564 = 21;
+ ENUM_VALUE11565 = 22;
+ ENUM_VALUE11566 = 23;
+ ENUM_VALUE11567 = 24;
+ ENUM_VALUE11568 = 25;
+ ENUM_VALUE11569 = 26;
+ ENUM_VALUE11570 = 27;
+ ENUM_VALUE11571 = 28;
+ ENUM_VALUE11572 = 29;
+ ENUM_VALUE11573 = 30;
+ ENUM_VALUE11574 = 31;
+ ENUM_VALUE11575 = 32;
+ ENUM_VALUE11576 = 33;
+ ENUM_VALUE11577 = 34;
+ ENUM_VALUE11578 = 35;
+ ENUM_VALUE11579 = 36;
+ ENUM_VALUE11580 = 37;
+ ENUM_VALUE11581 = 38;
+ ENUM_VALUE11582 = 39;
+ ENUM_VALUE11583 = 40;
+ ENUM_VALUE11584 = 41;
+ ENUM_VALUE11585 = 42;
+ ENUM_VALUE11586 = 43;
+ ENUM_VALUE11587 = 44;
+ ENUM_VALUE11588 = 45;
+ ENUM_VALUE11589 = 46;
+ ENUM_VALUE11590 = 47;
+ ENUM_VALUE11591 = 48;
+ ENUM_VALUE11592 = 49;
+ ENUM_VALUE11593 = 50;
+ ENUM_VALUE11594 = 51;
+ ENUM_VALUE11595 = 52;
+ ENUM_VALUE11596 = 53;
+ ENUM_VALUE11597 = 54;
+ ENUM_VALUE11598 = 55;
+ ENUM_VALUE11599 = 56;
+ ENUM_VALUE11600 = 57;
+ ENUM_VALUE11601 = 58;
+ ENUM_VALUE11602 = 59;
+ ENUM_VALUE11603 = 60;
+ ENUM_VALUE11604 = 61;
+ ENUM_VALUE11605 = 62;
+ ENUM_VALUE11606 = 63;
+ ENUM_VALUE11607 = 64;
+ ENUM_VALUE11608 = 65;
+ ENUM_VALUE11609 = 66;
+ ENUM_VALUE11610 = 67;
+ ENUM_VALUE11611 = 68;
+ ENUM_VALUE11612 = 69;
+ ENUM_VALUE11613 = 70;
+ ENUM_VALUE11614 = 71;
+ ENUM_VALUE11615 = 72;
+ ENUM_VALUE11616 = 73;
+ ENUM_VALUE11617 = 74;
+ ENUM_VALUE11618 = 75;
+ ENUM_VALUE11619 = 76;
+ ENUM_VALUE11620 = 77;
+ ENUM_VALUE11621 = 78;
+ ENUM_VALUE11622 = 79;
+ ENUM_VALUE11623 = 80;
+ ENUM_VALUE11624 = 81;
+ ENUM_VALUE11625 = 82;
+ ENUM_VALUE11626 = 83;
+ ENUM_VALUE11627 = 84;
+ ENUM_VALUE11628 = 85;
+ ENUM_VALUE11629 = 86;
+ ENUM_VALUE11630 = 87;
+ ENUM_VALUE11631 = 88;
+ ENUM_VALUE11632 = 89;
+ ENUM_VALUE11633 = 90;
+ ENUM_VALUE11634 = 91;
+ ENUM_VALUE11635 = 92;
+ ENUM_VALUE11636 = 93;
+ ENUM_VALUE11637 = 94;
+ ENUM_VALUE11638 = 95;
+ ENUM_VALUE11639 = 96;
+ ENUM_VALUE11640 = 97;
+ ENUM_VALUE11641 = 98;
+ ENUM_VALUE11642 = 99;
+ ENUM_VALUE11643 = 100;
+ ENUM_VALUE11644 = 101;
+ ENUM_VALUE11645 = 102;
+ ENUM_VALUE11646 = 103;
+ ENUM_VALUE11647 = 104;
+ ENUM_VALUE11648 = 105;
+ ENUM_VALUE11649 = 106;
+ ENUM_VALUE11650 = 107;
+ ENUM_VALUE11651 = 108;
+ ENUM_VALUE11652 = 109;
+ ENUM_VALUE11653 = 110;
+ ENUM_VALUE11654 = 111;
+ ENUM_VALUE11655 = 112;
+ ENUM_VALUE11656 = 113;
+ ENUM_VALUE11657 = 114;
+ ENUM_VALUE11658 = 115;
+ ENUM_VALUE11659 = 116;
+ ENUM_VALUE11660 = 117;
+ ENUM_VALUE11661 = 118;
+ ENUM_VALUE11662 = 119;
+ ENUM_VALUE11663 = 120;
+ ENUM_VALUE11664 = 121;
+ ENUM_VALUE11665 = 122;
+ ENUM_VALUE11666 = 123;
+ ENUM_VALUE11667 = 124;
+ ENUM_VALUE11668 = 125;
+ ENUM_VALUE11669 = 126;
+ ENUM_VALUE11670 = 127;
+ ENUM_VALUE11671 = 128;
+ ENUM_VALUE11672 = 129;
+ ENUM_VALUE11673 = 130;
+ ENUM_VALUE11674 = 131;
+ ENUM_VALUE11675 = 132;
+ ENUM_VALUE11676 = 133;
+ ENUM_VALUE11677 = 134;
+ ENUM_VALUE11678 = 135;
+ ENUM_VALUE11679 = 136;
+ ENUM_VALUE11680 = 137;
+ ENUM_VALUE11681 = 138;
+ ENUM_VALUE11682 = 139;
+ ENUM_VALUE11683 = 140;
+ ENUM_VALUE11684 = 141;
+ ENUM_VALUE11685 = 142;
+ ENUM_VALUE11686 = 143;
+ ENUM_VALUE11687 = 144;
+ ENUM_VALUE11688 = 145;
+ ENUM_VALUE11689 = 146;
+ ENUM_VALUE11690 = 147;
+ ENUM_VALUE11691 = 148;
+ ENUM_VALUE11692 = 149;
+ ENUM_VALUE11693 = 150;
+ ENUM_VALUE11694 = 151;
+ ENUM_VALUE11695 = 152;
+ ENUM_VALUE11696 = 153;
+ ENUM_VALUE11697 = 154;
+ ENUM_VALUE11698 = 155;
+ ENUM_VALUE11699 = 156;
+ ENUM_VALUE11700 = 157;
+ ENUM_VALUE11701 = 158;
+ ENUM_VALUE11702 = 159;
+ ENUM_VALUE11703 = 160;
+ ENUM_VALUE11704 = 161;
+ ENUM_VALUE11705 = 162;
+ ENUM_VALUE11706 = 163;
+ ENUM_VALUE11707 = 164;
+ ENUM_VALUE11708 = 165;
+ ENUM_VALUE11709 = 166;
+ ENUM_VALUE11710 = 167;
+ ENUM_VALUE11711 = 168;
+ ENUM_VALUE11712 = 169;
+ ENUM_VALUE11713 = 170;
+ ENUM_VALUE11714 = 171;
+ ENUM_VALUE11715 = 172;
+ ENUM_VALUE11716 = 173;
+ ENUM_VALUE11717 = 174;
+ ENUM_VALUE11718 = 175;
+ ENUM_VALUE11719 = 176;
+ ENUM_VALUE11720 = 177;
+ ENUM_VALUE11721 = 178;
+ ENUM_VALUE11722 = 179;
+ ENUM_VALUE11723 = 180;
+ ENUM_VALUE11724 = 181;
+ ENUM_VALUE11725 = 182;
+ ENUM_VALUE11726 = 183;
+ ENUM_VALUE11727 = 184;
+ ENUM_VALUE11728 = 185;
+ ENUM_VALUE11729 = 186;
+ ENUM_VALUE11730 = 187;
+ ENUM_VALUE11731 = 188;
+ ENUM_VALUE11732 = 16777215;
+}
+
+enum Enum11468 {
+ ENUM_VALUE11469 = -99;
+ ENUM_VALUE11470 = 0;
+ ENUM_VALUE11471 = 1;
+ ENUM_VALUE11472 = 2;
+ ENUM_VALUE11473 = 3;
+ ENUM_VALUE11474 = 4;
+ ENUM_VALUE11475 = 28;
+ ENUM_VALUE11476 = 22;
+ ENUM_VALUE11477 = 38;
+ ENUM_VALUE11478 = 512;
+ ENUM_VALUE11479 = 2048;
+ ENUM_VALUE11480 = 66;
+ ENUM_VALUE11481 = 578;
+ ENUM_VALUE11482 = 77;
+ ENUM_VALUE11483 = 88;
+ ENUM_VALUE11484 = 100;
+ ENUM_VALUE11485 = 110;
+ ENUM_VALUE11486 = 2158;
+ ENUM_VALUE11487 = 122;
+ ENUM_VALUE11488 = 2170;
+ ENUM_VALUE11489 = 144;
+ ENUM_VALUE11490 = 244;
+ ENUM_VALUE11491 = 2292;
+ ENUM_VALUE11492 = 44;
+}
+
+enum Enum11022 {
+ ENUM_VALUE11023 = 0;
+ ENUM_VALUE11024 = 1;
+ ENUM_VALUE11025 = 2;
+ ENUM_VALUE11026 = 3;
+ ENUM_VALUE11027 = 4;
+ ENUM_VALUE11028 = 5;
+ ENUM_VALUE11029 = 6;
+ ENUM_VALUE11030 = 7;
+ ENUM_VALUE11031 = 8;
+ ENUM_VALUE11032 = 9;
+ ENUM_VALUE11033 = 10;
+ ENUM_VALUE11034 = 11;
+ ENUM_VALUE11035 = 12;
+ ENUM_VALUE11036 = 13;
+ ENUM_VALUE11037 = 14;
+ ENUM_VALUE11038 = 15;
+ ENUM_VALUE11039 = 16;
+ ENUM_VALUE11040 = 17;
+ ENUM_VALUE11041 = 18;
+ ENUM_VALUE11042 = 19;
+ ENUM_VALUE11043 = 20;
+ ENUM_VALUE11044 = 21;
+ ENUM_VALUE11045 = 22;
+ ENUM_VALUE11046 = 23;
+ ENUM_VALUE11047 = 24;
+ ENUM_VALUE11048 = 25;
+ ENUM_VALUE11049 = 26;
+ ENUM_VALUE11050 = 27;
+ ENUM_VALUE11051 = 28;
+ ENUM_VALUE11052 = 29;
+ ENUM_VALUE11053 = 30;
+ ENUM_VALUE11054 = 31;
+ ENUM_VALUE11055 = 32;
+ ENUM_VALUE11056 = 33;
+ ENUM_VALUE11057 = 34;
+ ENUM_VALUE11058 = 35;
+ ENUM_VALUE11059 = 36;
+ ENUM_VALUE11060 = 37;
+ ENUM_VALUE11061 = 38;
+ ENUM_VALUE11062 = 39;
+ ENUM_VALUE11063 = 40;
+ ENUM_VALUE11064 = 41;
+ ENUM_VALUE11065 = 42;
+ ENUM_VALUE11066 = 43;
+ ENUM_VALUE11067 = 44;
+ ENUM_VALUE11068 = 45;
+ ENUM_VALUE11069 = 46;
+ ENUM_VALUE11070 = 47;
+ ENUM_VALUE11071 = 48;
+ ENUM_VALUE11072 = 49;
+ ENUM_VALUE11073 = 50;
+ ENUM_VALUE11074 = 51;
+ ENUM_VALUE11075 = 52;
+ ENUM_VALUE11076 = 53;
+ ENUM_VALUE11077 = 54;
+ ENUM_VALUE11078 = 55;
+ ENUM_VALUE11079 = 56;
+ ENUM_VALUE11080 = 57;
+ ENUM_VALUE11081 = 58;
+ ENUM_VALUE11082 = 59;
+ ENUM_VALUE11083 = 60;
+ ENUM_VALUE11084 = 61;
+ ENUM_VALUE11085 = 62;
+ ENUM_VALUE11086 = 63;
+ ENUM_VALUE11087 = 64;
+ ENUM_VALUE11088 = 65;
+ ENUM_VALUE11089 = 66;
+ ENUM_VALUE11090 = 67;
+ ENUM_VALUE11091 = 68;
+ ENUM_VALUE11092 = 69;
+ ENUM_VALUE11093 = 70;
+ ENUM_VALUE11094 = 71;
+ ENUM_VALUE11095 = 72;
+ ENUM_VALUE11096 = 73;
+ ENUM_VALUE11097 = 74;
+ ENUM_VALUE11098 = 75;
+ ENUM_VALUE11099 = 76;
+ ENUM_VALUE11100 = 77;
+ ENUM_VALUE11101 = 78;
+ ENUM_VALUE11102 = 79;
+ ENUM_VALUE11103 = 80;
+ ENUM_VALUE11104 = 81;
+ ENUM_VALUE11105 = 82;
+ ENUM_VALUE11106 = 83;
+}
+
+enum Enum12670 {
+ ENUM_VALUE12671 = 0;
+ ENUM_VALUE12672 = 1;
+ ENUM_VALUE12673 = 2;
+}
+
+enum Enum12871 {
+ ENUM_VALUE12872 = 1;
+ ENUM_VALUE12873 = 2;
+ ENUM_VALUE12874 = 3;
+ ENUM_VALUE12875 = 4;
+ ENUM_VALUE12876 = 5;
+ ENUM_VALUE12877 = 6;
+}
+
+enum Enum13092 {
+ ENUM_VALUE13093 = 1;
+ ENUM_VALUE13094 = 2;
+ ENUM_VALUE13095 = 3;
+}
+
+enum Enum13146 {
+ ENUM_VALUE13147 = 0;
+ ENUM_VALUE13148 = 1;
+ ENUM_VALUE13149 = 2;
+ ENUM_VALUE13150 = 3;
+}
+
+enum Enum16042 {
+ ENUM_VALUE16043 = 0;
+ ENUM_VALUE16044 = 1;
+ ENUM_VALUE16045 = 17;
+ ENUM_VALUE16046 = 273;
+ ENUM_VALUE16047 = 274;
+ ENUM_VALUE16048 = 4385;
+ ENUM_VALUE16049 = 4386;
+ ENUM_VALUE16050 = 4387;
+ ENUM_VALUE16051 = 4388;
+ ENUM_VALUE16052 = 4389;
+ ENUM_VALUE16053 = 4390;
+ ENUM_VALUE16054 = 4391;
+ ENUM_VALUE16055 = 4392;
+ ENUM_VALUE16056 = 4393;
+ ENUM_VALUE16057 = 276;
+ ENUM_VALUE16058 = 277;
+ ENUM_VALUE16059 = 18;
+ ENUM_VALUE16060 = 289;
+ ENUM_VALUE16061 = 291;
+ ENUM_VALUE16062 = 4657;
+ ENUM_VALUE16063 = 74513;
+ ENUM_VALUE16064 = 4658;
+ ENUM_VALUE16065 = 4659;
+ ENUM_VALUE16066 = 4660;
+ ENUM_VALUE16067 = 4661;
+ ENUM_VALUE16068 = 4662;
+ ENUM_VALUE16069 = 4663;
+ ENUM_VALUE16070 = 4664;
+ ENUM_VALUE16071 = 292;
+ ENUM_VALUE16072 = 4673;
+ ENUM_VALUE16073 = 4674;
+ ENUM_VALUE16074 = 293;
+ ENUM_VALUE16075 = 19;
+ ENUM_VALUE16076 = 20;
+ ENUM_VALUE16077 = 321;
+ ENUM_VALUE16078 = 5137;
+ ENUM_VALUE16079 = 5138;
+ ENUM_VALUE16080 = 5139;
+ ENUM_VALUE16081 = 5140;
+ ENUM_VALUE16082 = 5141;
+ ENUM_VALUE16083 = 5142;
+ ENUM_VALUE16084 = 82273;
+ ENUM_VALUE16085 = 82274;
+ ENUM_VALUE16086 = 82275;
+ ENUM_VALUE16087 = 82276;
+ ENUM_VALUE16088 = 82277;
+ ENUM_VALUE16089 = 82278;
+ ENUM_VALUE16090 = 5143;
+ ENUM_VALUE16091 = 5144;
+ ENUM_VALUE16092 = 5145;
+ ENUM_VALUE16093 = 5146;
+ ENUM_VALUE16094 = 82337;
+ ENUM_VALUE16095 = 5147;
+ ENUM_VALUE16096 = 5148;
+ ENUM_VALUE16097 = 322;
+ ENUM_VALUE16098 = 323;
+ ENUM_VALUE16099 = 324;
+ ENUM_VALUE16100 = 325;
+ ENUM_VALUE16101 = 326;
+ ENUM_VALUE16102 = 327;
+ ENUM_VALUE16103 = 328;
+ ENUM_VALUE16104 = 21;
+ ENUM_VALUE16105 = 337;
+ ENUM_VALUE16106 = 22;
+ ENUM_VALUE16107 = 23;
+ ENUM_VALUE16108 = 24;
+ ENUM_VALUE16109 = 2;
+ ENUM_VALUE16110 = 33;
+ ENUM_VALUE16111 = 34;
+ ENUM_VALUE16112 = 545;
+ ENUM_VALUE16113 = 8721;
+ ENUM_VALUE16114 = 8723;
+ ENUM_VALUE16115 = 8724;
+ ENUM_VALUE16116 = 546;
+ ENUM_VALUE16117 = 8739;
+ ENUM_VALUE16118 = 8740;
+ ENUM_VALUE16119 = 547;
+ ENUM_VALUE16120 = 548;
+ ENUM_VALUE16121 = 549;
+ ENUM_VALUE16122 = 550;
+ ENUM_VALUE16123 = 551;
+ ENUM_VALUE16124 = 552;
+ ENUM_VALUE16125 = 553;
+ ENUM_VALUE16126 = 35;
+ ENUM_VALUE16127 = 36;
+ ENUM_VALUE16128 = 37;
+ ENUM_VALUE16129 = 593;
+ ENUM_VALUE16130 = 594;
+ ENUM_VALUE16131 = 595;
+ ENUM_VALUE16132 = 596;
+ ENUM_VALUE16133 = 597;
+ ENUM_VALUE16134 = 38;
+ ENUM_VALUE16135 = 609;
+ ENUM_VALUE16136 = 610;
+ ENUM_VALUE16137 = 617;
+ ENUM_VALUE16138 = 614;
+ ENUM_VALUE16139 = 615;
+ ENUM_VALUE16140 = 616;
+ ENUM_VALUE16141 = 618;
+ ENUM_VALUE16142 = 620;
+ ENUM_VALUE16143 = 9937;
+ ENUM_VALUE16144 = 9938;
+ ENUM_VALUE16145 = 9939;
+ ENUM_VALUE16146 = 9940;
+ ENUM_VALUE16147 = 9941;
+ ENUM_VALUE16148 = 39;
+ ENUM_VALUE16149 = 40;
+ ENUM_VALUE16150 = 41;
+ ENUM_VALUE16151 = 42;
+ ENUM_VALUE16152 = 43;
+ ENUM_VALUE16153 = 44;
+ ENUM_VALUE16154 = 45;
+ ENUM_VALUE16155 = 11793;
+ ENUM_VALUE16156 = 3;
+ ENUM_VALUE16157 = 49;
+ ENUM_VALUE16158 = 50;
+ ENUM_VALUE16159 = 51;
+ ENUM_VALUE16160 = 817;
+ ENUM_VALUE16161 = 818;
+ ENUM_VALUE16162 = 819;
+ ENUM_VALUE16163 = 52;
+ ENUM_VALUE16164 = 833;
+ ENUM_VALUE16165 = 53;
+ ENUM_VALUE16166 = 54;
+ ENUM_VALUE16167 = 4;
+ ENUM_VALUE16168 = 1041;
+ ENUM_VALUE16169 = 16657;
+ ENUM_VALUE16170 = 16658;
+ ENUM_VALUE16171 = 16659;
+ ENUM_VALUE16172 = 16660;
+ ENUM_VALUE16173 = 16661;
+ ENUM_VALUE16174 = 1042;
+ ENUM_VALUE16175 = 16673;
+ ENUM_VALUE16176 = 1043;
+ ENUM_VALUE16177 = 16689;
+ ENUM_VALUE16178 = 16690;
+ ENUM_VALUE16179 = 16691;
+ ENUM_VALUE16180 = 16692;
+ ENUM_VALUE16181 = 16693;
+ ENUM_VALUE16182 = 16694;
+ ENUM_VALUE16183 = 16695;
+ ENUM_VALUE16184 = 1044;
+ ENUM_VALUE16185 = 16705;
+ ENUM_VALUE16186 = 16706;
+ ENUM_VALUE16187 = 16707;
+ ENUM_VALUE16188 = 16708;
+ ENUM_VALUE16189 = 16709;
+ ENUM_VALUE16190 = 16710;
+ ENUM_VALUE16191 = 16711;
+ ENUM_VALUE16192 = 16712;
+ ENUM_VALUE16193 = 16713;
+ ENUM_VALUE16194 = 1046;
+ ENUM_VALUE16195 = 16737;
+ ENUM_VALUE16196 = 1047;
+ ENUM_VALUE16197 = 16753;
+ ENUM_VALUE16198 = 268049;
+ ENUM_VALUE16199 = 268050;
+ ENUM_VALUE16200 = 268051;
+ ENUM_VALUE16201 = 268052;
+ ENUM_VALUE16202 = 1048;
+ ENUM_VALUE16203 = 16769;
+ ENUM_VALUE16204 = 16770;
+ ENUM_VALUE16205 = 16771;
+ ENUM_VALUE16206 = 16772;
+ ENUM_VALUE16207 = 16773;
+ ENUM_VALUE16208 = 1049;
+ ENUM_VALUE16209 = 1056;
+ ENUM_VALUE16210 = 1058;
+ ENUM_VALUE16211 = 1059;
+ ENUM_VALUE16212 = 1060;
+ ENUM_VALUE16213 = 1061;
+ ENUM_VALUE16214 = 5;
+ ENUM_VALUE16215 = 6;
+ ENUM_VALUE16216 = 97;
+ ENUM_VALUE16217 = 98;
+ ENUM_VALUE16218 = 99;
+ ENUM_VALUE16219 = 100;
+ ENUM_VALUE16220 = 101;
+ ENUM_VALUE16221 = 102;
+ ENUM_VALUE16222 = 103;
+ ENUM_VALUE16223 = 104;
+ ENUM_VALUE16224 = 105;
+ ENUM_VALUE16225 = 106;
+ ENUM_VALUE16226 = 108;
+ ENUM_VALUE16227 = 1729;
+ ENUM_VALUE16228 = 1730;
+ ENUM_VALUE16229 = 1731;
+ ENUM_VALUE16230 = 7;
+ ENUM_VALUE16231 = 8;
+ ENUM_VALUE16232 = 9;
+ ENUM_VALUE16233 = 10;
+ ENUM_VALUE16234 = 161;
+ ENUM_VALUE16235 = 2577;
+ ENUM_VALUE16236 = 41233;
+ ENUM_VALUE16237 = 41234;
+ ENUM_VALUE16238 = 2578;
+ ENUM_VALUE16239 = 2579;
+ ENUM_VALUE16240 = 41265;
+ ENUM_VALUE16241 = 2580;
+ ENUM_VALUE16242 = 2581;
+ ENUM_VALUE16243 = 41297;
+ ENUM_VALUE16244 = 41298;
+ ENUM_VALUE16245 = 41299;
+ ENUM_VALUE16246 = 41300;
+ ENUM_VALUE16247 = 2582;
+ ENUM_VALUE16248 = 2583;
+ ENUM_VALUE16249 = 2584;
+ ENUM_VALUE16250 = 162;
+ ENUM_VALUE16251 = 2593;
+ ENUM_VALUE16252 = 41489;
+ ENUM_VALUE16253 = 663825;
+ ENUM_VALUE16254 = 663826;
+ ENUM_VALUE16255 = 41490;
+ ENUM_VALUE16256 = 41491;
+ ENUM_VALUE16257 = 41492;
+ ENUM_VALUE16258 = 663873;
+ ENUM_VALUE16259 = 2594;
+ ENUM_VALUE16260 = 41505;
+ ENUM_VALUE16261 = 41506;
+ ENUM_VALUE16262 = 41507;
+ ENUM_VALUE16263 = 2595;
+ ENUM_VALUE16264 = 41521;
+ ENUM_VALUE16265 = 41522;
+ ENUM_VALUE16266 = 41523;
+ ENUM_VALUE16267 = 41524;
+ ENUM_VALUE16268 = 41525;
+ ENUM_VALUE16269 = 664401;
+ ENUM_VALUE16270 = 664402;
+ ENUM_VALUE16271 = 41526;
+ ENUM_VALUE16272 = 41527;
+ ENUM_VALUE16273 = 2596;
+ ENUM_VALUE16274 = 2597;
+ ENUM_VALUE16275 = 2598;
+ ENUM_VALUE16276 = 41569;
+ ENUM_VALUE16277 = 41570;
+ ENUM_VALUE16278 = 41571;
+ ENUM_VALUE16279 = 41572;
+ ENUM_VALUE16280 = 41573;
+ ENUM_VALUE16281 = 665169;
+ ENUM_VALUE16282 = 665170;
+ ENUM_VALUE16283 = 665171;
+ ENUM_VALUE16284 = 665172;
+ ENUM_VALUE16285 = 2599;
+ ENUM_VALUE16286 = 2600;
+ ENUM_VALUE16287 = 2601;
+ ENUM_VALUE16288 = 2603;
+ ENUM_VALUE16289 = 2604;
+ ENUM_VALUE16290 = 163;
+ ENUM_VALUE16291 = 2608;
+ ENUM_VALUE16292 = 2609;
+ ENUM_VALUE16293 = 2610;
+ ENUM_VALUE16294 = 2611;
+ ENUM_VALUE16295 = 2612;
+ ENUM_VALUE16296 = 164;
+ ENUM_VALUE16297 = 2625;
+ ENUM_VALUE16298 = 2626;
+ ENUM_VALUE16299 = 42017;
+ ENUM_VALUE16300 = 42018;
+ ENUM_VALUE16301 = 42019;
+ ENUM_VALUE16302 = 2627;
+ ENUM_VALUE16303 = 2628;
+ ENUM_VALUE16304 = 165;
+ ENUM_VALUE16305 = 2641;
+ ENUM_VALUE16306 = 42257;
+ ENUM_VALUE16307 = 42258;
+ ENUM_VALUE16308 = 2642;
+ ENUM_VALUE16309 = 2643;
+ ENUM_VALUE16310 = 2644;
+ ENUM_VALUE16311 = 2646;
+ ENUM_VALUE16312 = 2647;
+ ENUM_VALUE16313 = 42353;
+ ENUM_VALUE16314 = 2648;
+ ENUM_VALUE16315 = 2649;
+ ENUM_VALUE16316 = 2650;
+ ENUM_VALUE16317 = 2651;
+ ENUM_VALUE16318 = 2652;
+ ENUM_VALUE16319 = 2653;
+ ENUM_VALUE16320 = 2654;
+ ENUM_VALUE16321 = 42481;
+ ENUM_VALUE16322 = 42482;
+ ENUM_VALUE16323 = 42483;
+ ENUM_VALUE16324 = 166;
+ ENUM_VALUE16325 = 2657;
+ ENUM_VALUE16326 = 2658;
+ ENUM_VALUE16327 = 42529;
+ ENUM_VALUE16328 = 2659;
+ ENUM_VALUE16329 = 2660;
+ ENUM_VALUE16330 = 2661;
+ ENUM_VALUE16331 = 2662;
+ ENUM_VALUE16332 = 2663;
+ ENUM_VALUE16333 = 42609;
+ ENUM_VALUE16334 = 2664;
+ ENUM_VALUE16335 = 2665;
+ ENUM_VALUE16336 = 42753;
+ ENUM_VALUE16337 = 42754;
+ ENUM_VALUE16338 = 42755;
+ ENUM_VALUE16339 = 11;
+ ENUM_VALUE16340 = 177;
+ ENUM_VALUE16341 = 2833;
+ ENUM_VALUE16342 = 179;
+ ENUM_VALUE16343 = 180;
+ ENUM_VALUE16344 = 2881;
+ ENUM_VALUE16345 = 182;
+ ENUM_VALUE16346 = 183;
+ ENUM_VALUE16347 = 12;
+ ENUM_VALUE16348 = 3089;
+ ENUM_VALUE16349 = 194;
+ ENUM_VALUE16350 = 195;
+ ENUM_VALUE16351 = 196;
+ ENUM_VALUE16352 = 198;
+ ENUM_VALUE16353 = 3169;
+ ENUM_VALUE16354 = 199;
+ ENUM_VALUE16355 = 200;
+ ENUM_VALUE16356 = 208;
+ ENUM_VALUE16357 = 3329;
+ ENUM_VALUE16358 = 3330;
+ ENUM_VALUE16359 = 3331;
+ ENUM_VALUE16360 = 209;
+ ENUM_VALUE16361 = 210;
+ ENUM_VALUE16362 = 211;
+ ENUM_VALUE16363 = 3377;
+ ENUM_VALUE16364 = 3378;
+ ENUM_VALUE16365 = 3379;
+ ENUM_VALUE16366 = 3380;
+ ENUM_VALUE16367 = 3381;
+ ENUM_VALUE16368 = 865809;
+ ENUM_VALUE16369 = 865810;
+ ENUM_VALUE16370 = 865811;
+ ENUM_VALUE16371 = 865812;
+ ENUM_VALUE16372 = 865813;
+ ENUM_VALUE16373 = 865814;
+ ENUM_VALUE16374 = 865815;
+ ENUM_VALUE16375 = 865816;
+ ENUM_VALUE16376 = 865817;
+ ENUM_VALUE16377 = 865818;
+ ENUM_VALUE16378 = 865819;
+ ENUM_VALUE16379 = 865820;
+ ENUM_VALUE16380 = 865821;
+ ENUM_VALUE16381 = 865822;
+ ENUM_VALUE16382 = 865823;
+ ENUM_VALUE16383 = 865824;
+ ENUM_VALUE16384 = 865825;
+ ENUM_VALUE16385 = 865826;
+ ENUM_VALUE16386 = 865827;
+ ENUM_VALUE16387 = 865828;
+ ENUM_VALUE16388 = 865829;
+ ENUM_VALUE16389 = 212;
+ ENUM_VALUE16390 = 3393;
+ ENUM_VALUE16391 = 3394;
+ ENUM_VALUE16392 = 3395;
+ ENUM_VALUE16393 = 213;
+ ENUM_VALUE16394 = 214;
+ ENUM_VALUE16395 = 215;
+ ENUM_VALUE16396 = 3441;
+ ENUM_VALUE16397 = 3442;
+ ENUM_VALUE16398 = 216;
+ ENUM_VALUE16399 = 217;
+ ENUM_VALUE16400 = 3473;
+ ENUM_VALUE16401 = 3474;
+ ENUM_VALUE16402 = 3475;
+ ENUM_VALUE16403 = 254;
+ ENUM_VALUE16404 = 255;
+}
+
+enum Enum16553 {
+ ENUM_VALUE16554 = 0;
+ ENUM_VALUE16555 = 1;
+ ENUM_VALUE16556 = 2;
+ ENUM_VALUE16557 = 3;
+ ENUM_VALUE16558 = 4;
+ ENUM_VALUE16559 = 5;
+ ENUM_VALUE16560 = 6;
+ ENUM_VALUE16561 = 7;
+ ENUM_VALUE16562 = 8;
+ ENUM_VALUE16563 = 9;
+}
+
+enum Enum16728 {
+ ENUM_VALUE16729 = 1;
+ ENUM_VALUE16730 = 2;
+ ENUM_VALUE16731 = 3;
+}
+
+enum Enum16732 {
+ ENUM_VALUE16733 = 1;
+ ENUM_VALUE16734 = 2;
+ ENUM_VALUE16735 = 3;
+ ENUM_VALUE16736 = 4;
+ ENUM_VALUE16737 = 5;
+}
+
+enum Enum16738 {
+ ENUM_VALUE16739 = 1;
+ ENUM_VALUE16740 = 2;
+ ENUM_VALUE16741 = 3;
+ ENUM_VALUE16742 = 4;
+ ENUM_VALUE16743 = 5;
+ ENUM_VALUE16744 = 6;
+ ENUM_VALUE16745 = 7;
+}
+
+enum Enum16698 {
+ ENUM_VALUE16699 = -1;
+ ENUM_VALUE16700 = 100;
+ ENUM_VALUE16701 = 2;
+ ENUM_VALUE16702 = 0;
+ ENUM_VALUE16703 = 1;
+ ENUM_VALUE16704 = 4;
+ ENUM_VALUE16705 = 11;
+ ENUM_VALUE16706 = 12;
+ ENUM_VALUE16707 = 3;
+ ENUM_VALUE16708 = 5;
+ ENUM_VALUE16709 = 6;
+ ENUM_VALUE16710 = 7;
+ ENUM_VALUE16711 = 8;
+ ENUM_VALUE16712 = 9;
+ ENUM_VALUE16713 = 10;
+ ENUM_VALUE16714 = 13;
+ ENUM_VALUE16715 = 14;
+ ENUM_VALUE16716 = 15;
+ ENUM_VALUE16717 = 16;
+ ENUM_VALUE16718 = 18;
+ ENUM_VALUE16719 = 17;
+ ENUM_VALUE16720 = 19;
+ ENUM_VALUE16721 = 20;
+}
+
+enum Enum16819 {
+ ENUM_VALUE16820 = 0;
+ ENUM_VALUE16821 = 1;
+ ENUM_VALUE16822 = 2;
+ ENUM_VALUE16823 = 3;
+ ENUM_VALUE16824 = 4;
+ ENUM_VALUE16825 = 5;
+}
+
+enum Enum16925 {
+ ENUM_VALUE16926 = 0;
+ ENUM_VALUE16927 = 1;
+ ENUM_VALUE16928 = 2;
+ ENUM_VALUE16929 = 3;
+ ENUM_VALUE16930 = 4;
+ ENUM_VALUE16931 = 5;
+ ENUM_VALUE16932 = 6;
+ ENUM_VALUE16933 = 7;
+ ENUM_VALUE16934 = 8;
+ ENUM_VALUE16935 = 9;
+ ENUM_VALUE16936 = 10;
+ ENUM_VALUE16937 = 11;
+ ENUM_VALUE16938 = 12;
+ ENUM_VALUE16939 = 13;
+}
+
+enum Enum22854 {
+ ENUM_VALUE22855 = 0;
+ ENUM_VALUE22856 = 1;
+}
+
+enum Enum24361 {
+ ENUM_VALUE24362 = 0;
+ ENUM_VALUE24363 = 1;
+ ENUM_VALUE24364 = 2;
+ ENUM_VALUE24365 = 3;
+}
+
+enum Enum16891 {
+ ENUM_VALUE16892 = 0;
+ ENUM_VALUE16893 = 1;
+ ENUM_VALUE16894 = 2;
+ ENUM_VALUE16895 = 3;
+ ENUM_VALUE16896 = 4;
+ ENUM_VALUE16897 = 5;
+ ENUM_VALUE16898 = 6;
+ ENUM_VALUE16899 = 7;
+ ENUM_VALUE16900 = 8;
+ ENUM_VALUE16901 = 9;
+ ENUM_VALUE16902 = 10;
+ ENUM_VALUE16903 = 11;
+ ENUM_VALUE16904 = 12;
+ ENUM_VALUE16905 = 13;
+ ENUM_VALUE16906 = 14;
+ ENUM_VALUE16907 = 15;
+ ENUM_VALUE16908 = 16;
+ ENUM_VALUE16909 = 17;
+ ENUM_VALUE16910 = 18;
+ ENUM_VALUE16911 = 19;
+ ENUM_VALUE16912 = 20;
+ ENUM_VALUE16913 = 21;
+ ENUM_VALUE16914 = 22;
+ ENUM_VALUE16915 = 23;
+ ENUM_VALUE16916 = 24;
+ ENUM_VALUE16917 = 25;
+ ENUM_VALUE16918 = 26;
+ ENUM_VALUE16919 = 27;
+ ENUM_VALUE16920 = 28;
+ ENUM_VALUE16921 = 29;
+ ENUM_VALUE16922 = 30;
+ ENUM_VALUE16923 = 31;
+}
+
+enum Enum27361 {
+ ENUM_VALUE27362 = 0;
+ ENUM_VALUE27363 = 1;
+ ENUM_VALUE27364 = 2;
+ ENUM_VALUE27365 = 3;
+ ENUM_VALUE27366 = 4;
+}
+
+enum Enum33960 {
+ ENUM_VALUE33961 = 0;
+ ENUM_VALUE33962 = 1;
+ ENUM_VALUE33963 = 2;
+ ENUM_VALUE33964 = 3;
+ ENUM_VALUE33965 = 4;
+ ENUM_VALUE33966 = 5;
+ ENUM_VALUE33967 = 6;
+}
+
+enum Enum34388 {
+ ENUM_VALUE34389 = 1;
+}
+
+enum Enum35477 {
+ ENUM_VALUE35478 = 4;
+ ENUM_VALUE35479 = 3;
+ ENUM_VALUE35480 = 2;
+ ENUM_VALUE35481 = 1;
+ ENUM_VALUE35482 = 0;
+}
+
+enum Enum35507 {
+ ENUM_VALUE35508 = 0;
+ ENUM_VALUE35509 = 1;
+ ENUM_VALUE35510 = 2;
+ ENUM_VALUE35511 = 3;
+ ENUM_VALUE35512 = 4;
+ ENUM_VALUE35513 = 5;
+ ENUM_VALUE35514 = 6;
+ ENUM_VALUE35515 = 7;
+ ENUM_VALUE35516 = 8;
+ ENUM_VALUE35517 = 9;
+}
+
+enum Enum36860 {
+ ENUM_VALUE36861 = 0;
+ ENUM_VALUE36862 = 1;
+ ENUM_VALUE36863 = 2;
+ ENUM_VALUE36864 = 3;
+ ENUM_VALUE36865 = 4;
+ ENUM_VALUE36866 = 5;
+ ENUM_VALUE36867 = 6;
+ ENUM_VALUE36868 = 7;
+}
+
+enum Enum36890 {
+ ENUM_VALUE36891 = 0;
+ ENUM_VALUE36892 = 1;
+}
+
diff --git a/benchmarks/datasets/google_message4/benchmark_message4.proto b/benchmarks/datasets/google_message4/benchmark_message4.proto
new file mode 100644
index 00000000..21613939
--- /dev/null
+++ b/benchmarks/datasets/google_message4/benchmark_message4.proto
@@ -0,0 +1,454 @@
+syntax = "proto2";
+
+import "datasets/google_message4/benchmark_message4_1.proto";
+import "datasets/google_message4/benchmark_message4_2.proto";
+import "datasets/google_message4/benchmark_message4_3.proto";
+package benchmarks.google_message4;
+
+option cc_enable_arenas = true;
+option java_package = "com.google.protobuf.benchmarks";
+
+message GoogleMessage4 {
+ optional int32 field37503 = 1;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37504 = 2;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37505 = 3;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37506 = 4;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37507 = 5;
+ optional .benchmarks.google_message4.Message37489 field37508 = 6;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37509 = 7;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37510 = 8;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37511 = 9;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37512 = 10;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37513 = 11;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37514 = 12;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37515 = 13;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37516 = 14;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37517 = 15;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37518 = 16;
+}
+
+message Message37489 {
+ optional .benchmarks.google_message4.Message2517 field37534 = 3;
+ optional .benchmarks.google_message4.Message7330 field37535 = 4;
+ optional .benchmarks.google_message4.Message8815 field37536 = 6;
+ optional .benchmarks.google_message4.Message8817 field37537 = 7;
+ optional .benchmarks.google_message4.Message8835 field37538 = 8;
+ optional .benchmarks.google_message4.Message8848 field37539 = 9;
+ optional .benchmarks.google_message4.Message8856 field37540 = 11;
+ optional .benchmarks.google_message4.Message12717 field37541 = 15;
+ optional .benchmarks.google_message4.Message12748 field37542 = 20;
+ optional .benchmarks.google_message4.Message7319 field37543 = 22;
+ optional .benchmarks.google_message4.Message12908 field37544 = 24;
+ optional .benchmarks.google_message4.Message12910 field37545 = 25;
+ optional .benchmarks.google_message4.Message12960 field37546 = 30;
+ optional .benchmarks.google_message4.Message176 field37547 = 33;
+ optional .benchmarks.google_message4.Message13000 field37548 = 34;
+ optional .benchmarks.google_message4.Message13035 field37549 = 35;
+ optional .benchmarks.google_message4.Message37331 field37550 = 36;
+ optional .benchmarks.google_message4.Message37329 field37551 = 37;
+ optional .benchmarks.google_message4.Message37327 field37552 = 38;
+ optional .benchmarks.google_message4.Message37333 field37553 = 39;
+ optional .benchmarks.google_message4.Message37335 field37554 = 40;
+}
+
+message Message7319 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7321 = 1;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7322 = 7;
+}
+
+message Message12717 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field12719 = 1;
+ optional string field12720 = 2;
+ optional uint32 field12721 = 3;
+ optional .benchmarks.google_message4.Message11976 field12722 = 4;
+ repeated .benchmarks.google_message4.Message11948 field12723 = 5;
+ optional .benchmarks.google_message4.Message11947 field12724 = 6;
+ optional .benchmarks.google_message4.Message12687 field12725 = 7;
+ repeated .benchmarks.google_message4.Message11948 field12726 = 8;
+ optional int64 field12727 = 9;
+}
+
+message Message37331 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37367 = 4;
+ required .benchmarks.google_message4.Message37326 field37368 = 1;
+ required int64 field37369 = 2;
+ required bytes field37370 = 3;
+}
+
+message Message8815 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field8819 = 1;
+ repeated .benchmarks.google_message4.Message8768 field8820 = 2;
+ optional bool field8821 = 3;
+}
+
+message Message7330 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7332 = 1;
+ optional .benchmarks.google_message4.Message3069 field7333 = 2;
+ optional .benchmarks.google_message4.Message7320 field7334 = 3;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7335 = 4;
+ optional bool field7336 = 5;
+ optional int64 field7337 = 6;
+}
+
+message Message12960 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field12962 = 1;
+ optional .benchmarks.google_message4.Message12948 field12963 = 2;
+}
+
+message Message176 {
+ required string field408 = 1;
+ optional int32 field409 = 4;
+ optional string field410 = 50;
+ optional int32 field411 = 2;
+ optional uint64 field412 = 47;
+ optional string field413 = 56;
+ optional int32 field414 = 24;
+ optional string field415 = 21;
+ optional bytes field416 = 3;
+ optional string field417 = 57;
+ optional int32 field418 = 51;
+ optional float field419 = 7;
+ optional bool field420 = 5;
+ optional bool field421 = 28;
+ optional int32 field422 = 6;
+ repeated int32 field423 = 40;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field424 = 41;
+ optional bool field425 = 25;
+ optional uint64 field426 = 26;
+ optional int32 field427 = 38;
+ optional bytes field428 = 15;
+ optional bytes field429 = 55;
+ optional bytes field430 = 16;
+ optional bytes field431 = 23;
+ optional bool field432 = 33;
+ optional bytes field433 = 31;
+ optional bytes field434 = 32;
+ optional int32 field435 = 36;
+ optional uint64 field436 = 17;
+ optional int32 field437 = 45;
+ optional uint64 field438 = 18;
+ optional string field439 = 46;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field440 = 64;
+ optional int32 field441 = 39;
+ optional uint64 field442 = 48;
+ optional bytes field443 = 19;
+ optional bytes field444 = 42;
+ optional bytes field445 = 43;
+ optional string field446 = 44;
+ optional string field447 = 49;
+ optional int64 field448 = 20;
+ optional bool field449 = 53;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field450 = 54;
+ repeated .benchmarks.google_message4.UnusedEmptyMessage field451 = 22;
+ optional .benchmarks.google_message4.UnusedEnum field452 = 27;
+ optional int32 field453 = 29;
+ optional int32 field454 = 30;
+ optional .benchmarks.google_message4.UnusedEnum field455 = 37;
+ optional .benchmarks.google_message4.UnusedEnum field456 = 34;
+ optional int32 field457 = 35;
+ repeated group Message178 = 101 {
+ }
+ optional bool field459 = 52;
+ optional uint64 field460 = 58;
+ optional uint64 field461 = 59;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field462 = 60;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field463 = 61;
+ optional .benchmarks.google_message4.UnusedEnum field464 = 62;
+ repeated string field465 = 63;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field466 = 65;
+}
+
+message Message8817 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field8825 = 1;
+ repeated .benchmarks.google_message4.Message8768 field8826 = 2;
+ optional string field8827 = 3;
+}
+
+message Message8835 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field8837 = 1;
+ repeated string field8838 = 2;
+ optional .benchmarks.google_message4.UnusedEnum field8839 = 3;
+}
+
+message Message37333 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37372 = 3;
+ required .benchmarks.google_message4.Message37326 field37373 = 1;
+ optional uint64 field37374 = 2;
+}
+
+message Message13000 {
+ optional int64 field13015 = 1;
+ repeated .benchmarks.google_message4.Message12979 field13016 = 2;
+}
+
+message Message37335 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37376 = 4;
+ required .benchmarks.google_message4.Message37326 field37377 = 1;
+ required .benchmarks.google_message4.Message37173 field37378 = 2;
+ optional uint64 field37379 = 3;
+}
+
+message Message8848 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field8850 = 1;
+ optional string field8851 = 2;
+ optional bytes field8852 = 3;
+}
+
+message Message13035 {
+ optional int64 field13058 = 1;
+ repeated int64 field13059 = 2;
+}
+
+message Message8856 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field8858 = 1;
+ optional string field8859 = 2;
+}
+
+message Message12908 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field12912 = 1;
+ optional string field12913 = 2;
+ optional .benchmarks.google_message4.Message12799 field12914 = 3;
+ optional int64 field12915 = 4;
+ optional .benchmarks.google_message4.Message3804 field12916 = 5;
+ optional .benchmarks.google_message4.Message12870 field12917 = 6;
+}
+
+message Message12910 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field12920 = 1;
+ optional .benchmarks.google_message4.Message12818 field12921 = 2;
+ repeated .benchmarks.google_message4.Message12903 field12922 = 3;
+}
+
+message Message37327 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37347 = 11;
+ required .benchmarks.google_message4.Message37326 field37348 = 1;
+ optional bool field37349 = 2;
+ optional bool field37350 = 3;
+ optional bool field37351 = 4;
+ optional bool field37352 = 5;
+ optional bool field37353 = 6;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37354 = 7;
+ optional uint64 field37355 = 8;
+ optional bool field37356 = 9;
+ optional bool field37357 = 10;
+}
+
+message Message37329 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37359 = 6;
+ required .benchmarks.google_message4.Message37326 field37360 = 1;
+ required int64 field37361 = 2;
+ required int64 field37362 = 3;
+ optional bool field37363 = 4;
+}
+
+message Message2517 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field2519 = 1;
+ optional .benchmarks.google_message4.Message2356 field2520 = 2;
+ optional .benchmarks.google_message4.Message0 field2521 = 3;
+ optional .benchmarks.google_message4.Message2463 field2522 = 4;
+ repeated .benchmarks.google_message4.Message971 field2523 = 5;
+}
+
+message Message12748 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field12754 = 1;
+ optional string field12755 = 2;
+ optional string field12756 = 3;
+ optional .benchmarks.google_message4.Enum12735 field12757 = 4;
+}
+
+message Message12687 {
+ repeated .benchmarks.google_message4.Message12686 field12701 = 1;
+}
+
+message Message11948 {
+ optional string field11954 = 1;
+ repeated .benchmarks.google_message4.Message11949 field11955 = 2;
+ optional bool field11956 = 3;
+}
+
+message Message11976 {
+ repeated .benchmarks.google_message4.Message11975 field12002 = 1;
+}
+
+message Message7320 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7323 = 1;
+ optional .benchmarks.google_message4.Message7287 field7324 = 8;
+}
+
+message Message3069 {
+ optional .benchmarks.google_message4.Message3061 field3374 = 1;
+ optional bytes field3375 = 2;
+ repeated group Message3070 = 3 {
+ required .benchmarks.google_message4.Enum3071 field3378 = 4;
+ required bytes field3379 = 5;
+ }
+ extensions 10000 to 536870911;
+}
+
+message Message12948 {
+ repeated .benchmarks.google_message4.Message12949 field12958 = 1;
+}
+
+message Message8768 {
+ optional string field8782 = 1;
+ optional .benchmarks.google_message4.Message8572 field8783 = 2;
+ optional bool field8784 = 3;
+ repeated .benchmarks.google_message4.Message8774 field8785 = 4;
+ optional int64 field8786 = 5;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field8787 = 6;
+ optional string field8788 = 7;
+}
+
+message Message12979 {
+ required bytes field12981 = 1;
+ repeated string field12982 = 2;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field12983 = 3;
+ optional int64 field12984 = 4;
+ optional string field12985 = 5;
+ optional int32 field12986 = 6;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field12987 = 7;
+}
+
+message Message37173 {
+ optional string field37252 = 1;
+ optional int64 field37253 = 2;
+ optional .benchmarks.google_message4.UnusedEnum field37254 = 4;
+ optional bool field37255 = 5;
+ optional bool field37256 = 6;
+ optional bool field37257 = 7;
+ optional string field37258 = 8;
+ optional string field37259 = 9;
+ optional uint32 field37260 = 10;
+ optional fixed32 field37261 = 11;
+ optional string field37262 = 12;
+ optional string field37263 = 13;
+ optional string field37264 = 14;
+ optional int32 field37265 = 15;
+ optional int64 field37266 = 16;
+ optional int64 field37267 = 17;
+ optional int32 field37268 = 18;
+ optional int32 field37269 = 19;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37270 = 20;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37271 = 21;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37272 = 22;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37273 = 23;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field37274 = 24;
+ optional string field37275 = 25;
+ optional bool field37276 = 26;
+}
+
+message Message12799 {
+ required string field12809 = 1;
+ repeated fixed64 field12810 = 2;
+ repeated .benchmarks.google_message4.Message12776 field12811 = 8;
+ repeated int32 field12812 = 4;
+ repeated .benchmarks.google_message4.Message12798 field12813 = 5;
+ required int32 field12814 = 3;
+ optional int32 field12815 = 6;
+ optional .benchmarks.google_message4.Message12797 field12816 = 7;
+}
+
+message Message12870 {
+ required int32 field12879 = 1;
+ optional int32 field12880 = 7;
+ required int32 field12881 = 2;
+ optional uint64 field12882 = 3;
+ optional string field12883 = 2001;
+ optional fixed64 field12884 = 4;
+ repeated fixed64 field12885 = 14;
+ optional int32 field12886 = 9;
+ optional int64 field12887 = 18;
+ repeated .benchmarks.google_message4.Message12870 field12888 = 8;
+ optional int32 field12889 = 5;
+ optional uint64 field12890 = 6;
+ optional int32 field12891 = 10;
+ optional int32 field12892 = 11;
+ optional double field12893 = 12;
+ optional .benchmarks.google_message4.Message12825 field12894 = 13;
+ optional double field12895 = 15;
+ optional string field12896 = 16;
+ optional .benchmarks.google_message4.Enum12871 field12897 = 17;
+ optional int32 field12898 = 19;
+}
+
+message Message3804 {
+ required int64 field3818 = 1;
+ required bool field3819 = 2;
+ repeated .benchmarks.google_message4.Enum3805 field3820 = 4;
+ optional int32 field3821 = 5;
+ optional bool field3822 = 6;
+ optional int64 field3823 = 7;
+ optional .benchmarks.google_message4.Enum3783 field3824 = 8;
+}
+
+message Message12903 {
+ optional string field12905 = 1;
+ optional .benchmarks.google_message4.Message8587 field12906 = 2;
+ repeated .benchmarks.google_message4.Message8590 field12907 = 3;
+}
+
+message Message37326 {
+ required string field37345 = 1;
+ optional string field37346 = 2;
+}
+
+message Message2356 {
+ optional .benchmarks.google_message4.Message1374 field2368 = 121;
+ optional uint64 field2369 = 1;
+ optional int32 field2370 = 2;
+ optional int32 field2371 = 17;
+ required string field2372 = 3;
+ optional int32 field2373 = 7;
+ optional bytes field2374 = 8;
+ optional string field2375 = 4;
+ optional string field2376 = 101;
+ optional int32 field2377 = 102;
+ optional int32 field2378 = 103;
+ optional int32 field2379 = 104;
+ optional int32 field2380 = 113;
+ optional int32 field2381 = 114;
+ optional int32 field2382 = 115;
+ optional int32 field2383 = 117;
+ optional int32 field2384 = 118;
+ optional int32 field2385 = 119;
+ optional int32 field2386 = 105;
+ optional bytes field2387 = 5;
+ optional group Message2357 = 6 {
+ optional int64 field2399 = 9;
+ optional int32 field2400 = 10;
+ optional int32 field2401 = 11;
+ optional int32 field2402 = 12;
+ optional int32 field2403 = 13;
+ optional int32 field2404 = 116;
+ optional int32 field2405 = 106;
+ required bytes field2406 = 14;
+ optional int32 field2407 = 45;
+ optional int32 field2408 = 112;
+ optional bool field2409 = 122;
+ optional bytes field2410 = 124;
+ }
+ optional string field2389 = 120;
+ optional group Message2358 = 107 {
+ }
+ repeated group Message2359 = 40 {
+ }
+ optional int32 field2392 = 50;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field2393 = 60;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field2394 = 70;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field2395 = 80;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field2396 = 90;
+ optional string field2397 = 100;
+ optional string field2398 = 123;
+}
+
+message Message0 {
+ option message_set_wire_format = true;
+ extensions 4 to 2147483646;
+}
+
+message Message971 {
+ optional string field972 = 1;
+ optional int32 field973 = 2;
+ optional bool field974 = 3;
+}
+
diff --git a/benchmarks/datasets/google_message4/benchmark_message4_1.proto b/benchmarks/datasets/google_message4/benchmark_message4_1.proto
new file mode 100644
index 00000000..e7697480
--- /dev/null
+++ b/benchmarks/datasets/google_message4/benchmark_message4_1.proto
@@ -0,0 +1,474 @@
+syntax = "proto2";
+
+import "datasets/google_message4/benchmark_message4_2.proto";
+import "datasets/google_message4/benchmark_message4_3.proto";
+package benchmarks.google_message4;
+
+option cc_enable_arenas = true;
+option java_package = "com.google.protobuf.benchmarks";
+
+message Message2463 {
+ repeated .benchmarks.google_message4.Message2462 field2498 = 1;
+}
+
+message Message12686 {
+ optional string field12699 = 1;
+ optional .benchmarks.google_message4.Message12685 field12700 = 2;
+}
+
+message Message11949 {
+}
+
+message Message11975 {
+ optional string field11992 = 1;
+ optional int32 field11993 = 2;
+ repeated .benchmarks.google_message4.Message10320 field11994 = 3;
+ optional .benchmarks.google_message4.Message11947 field11995 = 4;
+ optional .benchmarks.google_message4.Message11920 field11996 = 5;
+ optional bool field11997 = 6;
+ repeated string field11998 = 7;
+ optional float field11999 = 8;
+ repeated .benchmarks.google_message4.UnusedEnum field12000 = 9;
+ optional int32 field12001 = 11;
+}
+
+message Message7287 {
+ optional .benchmarks.google_message4.Message6133 field7311 = 1;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7312 = 8;
+ optional string field7313 = 3;
+ optional .benchmarks.google_message4.Message6643 field7314 = 4;
+ optional .benchmarks.google_message4.Enum7288 field7315 = 5;
+ optional bytes field7316 = 6;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7317 = 7;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7318 = 9;
+}
+
+message Message3061 {
+ optional string field3286 = 2;
+ optional int32 field3287 = 77;
+ optional string field3288 = 49;
+ required .benchmarks.google_message4.Message3046 field3289 = 3;
+ optional .benchmarks.google_message4.Message3046 field3290 = 58;
+ optional group Message3062 = 4 {
+ required int32 field3335 = 5;
+ optional int32 field3336 = 6;
+ optional int32 field3337 = 7;
+ }
+ optional .benchmarks.google_message4.Message3060 field3292 = 104;
+ optional int64 field3293 = 32;
+ optional int32 field3294 = 41;
+ optional group Message3063 = 13 {
+ required int32 field3338 = 14;
+ optional .benchmarks.google_message4.Enum2851 field3339 = 18;
+ optional int64 field3340 = 15;
+ optional int64 field3341 = 23;
+ }
+ optional .benchmarks.google_message4.Enum2834 field3296 = 94;
+ optional bool field3297 = 25;
+ optional bool field3298 = 50;
+ optional string field3299 = 89;
+ optional string field3300 = 91;
+ optional string field3301 = 105;
+ optional .benchmarks.google_message4.Message3050 field3302 = 53;
+ optional fixed64 field3303 = 51;
+ optional fixed64 field3304 = 106;
+ optional int32 field3305 = 60;
+ optional string field3306 = 44;
+ optional bytes field3307 = 81;
+ optional string field3308 = 70;
+ optional bytes field3309 = 45;
+ optional .benchmarks.google_message4.Enum2806 field3310 = 71;
+ optional int32 field3311 = 72;
+ optional bytes field3312 = 78;
+ optional int32 field3313 = 20;
+ repeated group Message3064 = 8 {
+ required .benchmarks.google_message4.Enum2602 field3342 = 9;
+ optional int32 field3343 = 92;
+ optional string field3344 = 10;
+ optional bytes field3345 = 11;
+ optional int32 field3346 = 12;
+ optional .benchmarks.google_message4.Message3060 field3347 = 98;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field3348 = 82;
+ optional .benchmarks.google_message4.Message3050 field3349 = 80;
+ optional fixed64 field3350 = 52;
+ optional int32 field3351 = 33;
+ optional string field3352 = 42;
+ optional string field3353 = 69;
+ optional bytes field3354 = 43;
+ optional .benchmarks.google_message4.Enum2806 field3355 = 73;
+ optional int32 field3356 = 74;
+ optional int32 field3357 = 90;
+ optional bytes field3358 = 79;
+ optional int32 field3359 = 19;
+ optional .benchmarks.google_message4.Enum2834 field3360 = 95;
+ }
+ optional .benchmarks.google_message4.UnusedEmptyMessage field3315 = 39;
+ optional int32 field3316 = 76;
+ optional group Message3065 = 63 {
+ }
+ optional .benchmarks.google_message4.Enum2806 field3318 = 54;
+ optional int32 field3319 = 46;
+ repeated string field3320 = 24;
+ optional fixed32 field3321 = 38;
+ optional bytes field3322 = 99;
+ optional fixed64 field3323 = 1;
+ optional fixed64 field3324 = 97;
+ repeated .benchmarks.google_message4.Message3040 field3325 = 16;
+ repeated .benchmarks.google_message4.Message3041 field3326 = 61;
+ optional group Message3066 = 21 {
+ optional int32 field3366 = 22;
+ optional int32 field3367 = 55;
+ optional int32 field3368 = 88;
+ optional int32 field3369 = 56;
+ optional int32 field3370 = 75;
+ optional int32 field3371 = 57;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field3372 = 85;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field3373 = 96;
+ }
+ optional .benchmarks.google_message4.UnusedEmptyMessage field3328 = 47;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field3329 = 48;
+ optional fixed64 field3330 = 40;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field3331 = 86;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field3332 = 59;
+ optional int32 field3333 = 17;
+}
+
+message Message12949 {
+}
+
+message Message8572 {
+ optional bytes field8647 = 1;
+ optional bytes field8648 = 3;
+ optional .benchmarks.google_message4.Message3886 field8649 = 4;
+ optional .benchmarks.google_message4.Message3919 field8650 = 57;
+ optional bool field8651 = 5;
+ optional int32 field8652 = 6;
+ optional int32 field8653 = 49;
+ optional .benchmarks.google_message4.Message7905 field8654 = 7;
+ optional int32 field8655 = 10;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field8656 = 11;
+ optional bool field8657 = 35;
+ optional bytes field8658 = 12;
+ optional string field8659 = 14;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field8660 = 13;
+ optional bytes field8661 = 15;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field8662 = 17;
+ optional int32 field8663 = 18;
+ optional int32 field8664 = 19;
+ optional bool field8665 = 20;
+ optional .benchmarks.google_message4.Enum3476 field8666 = 31;
+ optional bool field8667 = 36;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field8668 = 39;
+ optional bytes field8669 = 22;
+ optional int32 field8670 = 24;
+ optional .benchmarks.google_message4.Message3052 field8671 = 25;
+ optional bytes field8672 = 26;
+ optional bytes field8673 = 28;
+ optional int32 field8674 = 29;
+ optional bytes field8675 = 30;
+ optional bytes field8676 = 32;
+ optional string field8677 = 33;
+ optional int32 field8678 = 34;
+ optional int32 field8679 = 37;
+ optional double field8680 = 38;
+ optional double field8681 = 42;
+ optional .benchmarks.google_message4.Message3922 field8682 = 40;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field8683 = 43;
+ optional int64 field8684 = 44;
+ optional .benchmarks.google_message4.Message7929 field8685 = 45;
+ optional uint64 field8686 = 46;
+ optional uint32 field8687 = 48;
+ optional .benchmarks.google_message4.Message7843 field8688 = 47;
+ optional .benchmarks.google_message4.Message7864 field8689 = 50;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field8690 = 52;
+ optional bool field8691 = 58;
+ optional bool field8692 = 54;
+ optional string field8693 = 55;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field8694 = 41;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field8695 = 53;
+ optional .benchmarks.google_message4.Message8575 field8696 = 61;
+}
+
+message Message8774 {
+ optional string field8810 = 1;
+ optional string field8811 = 2;
+ optional string field8812 = 3;
+ optional string field8813 = 4;
+ optional string field8814 = 5;
+}
+
+message Message12776 {
+ optional string field12786 = 1;
+ optional fixed64 field12787 = 11;
+ optional int32 field12788 = 6;
+ optional int32 field12789 = 13;
+ optional int32 field12790 = 14;
+ optional int32 field12791 = 15;
+ optional int32 field12792 = 16;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field12793 = 8;
+ optional .benchmarks.google_message4.Message12774 field12794 = 10;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field12795 = 12;
+ extensions 2 to 2;
+ extensions 3 to 3;
+ extensions 4 to 4;
+ extensions 5 to 5;
+ extensions 7 to 7;
+ extensions 9 to 9;
+}
+
+message Message12798 {
+ optional int32 field12805 = 1;
+ optional int32 field12806 = 2;
+ optional .benchmarks.google_message4.Message12774 field12807 = 6;
+ optional bool field12808 = 7;
+}
+
+message Message12797 {
+ optional .benchmarks.google_message4.Message12796 field12802 = 1;
+ repeated .benchmarks.google_message4.Message12796 field12803 = 2;
+ optional string field12804 = 3;
+}
+
+message Message12825 {
+ repeated .benchmarks.google_message4.Message12818 field12862 = 1;
+ optional int32 field12863 = 2;
+ optional .benchmarks.google_message4.Message12819 field12864 = 3;
+ optional .benchmarks.google_message4.Message12820 field12865 = 4;
+ optional int32 field12866 = 5;
+ repeated .benchmarks.google_message4.Message12821 field12867 = 6;
+ repeated .benchmarks.google_message4.UnusedEmptyMessage field12868 = 7;
+}
+
+message Message8590 {
+}
+
+message Message8587 {
+}
+
+message Message1374 {
+ required string field1375 = 1;
+ optional string field1376 = 2;
+}
+
+message Message2462 {
+ required bytes field2496 = 1;
+ required double field2497 = 2;
+}
+
+message Message12685 {
+ repeated string field12692 = 1;
+ repeated string field12693 = 2;
+ optional int64 field12694 = 3;
+ optional uint32 field12695 = 4;
+ repeated string field12696 = 5;
+ optional string field12697 = 6;
+ optional string field12698 = 7;
+}
+
+message Message10320 {
+ optional .benchmarks.google_message4.Enum10335 field10347 = 1;
+ repeated .benchmarks.google_message4.Message10319 field10348 = 2;
+ optional int32 field10349 = 3;
+ optional int32 field10350 = 4;
+ optional int32 field10351 = 5;
+ optional int32 field10352 = 6;
+ optional .benchmarks.google_message4.Enum10337 field10353 = 7;
+}
+
+message Message11947 {
+ optional uint32 field11951 = 1;
+ optional bool field11952 = 2;
+ optional int32 field11953 = 3;
+}
+
+message Message11920 {
+ optional .benchmarks.google_message4.Enum11901 field11945 = 1;
+ optional .benchmarks.google_message4.UnusedEnum field11946 = 2;
+}
+
+message Message6643 {
+ optional .benchmarks.google_message4.UnusedEmptyMessage field6683 = 3;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field6684 = 4;
+ optional double field6685 = 5;
+ optional double field6686 = 6;
+ optional int32 field6687 = 1;
+ optional int32 field6688 = 2;
+ optional double field6689 = 9;
+ optional bytes field6690 = 10;
+ optional int32 field6691 = 11;
+ optional bool field6692 = 12;
+ optional bool field6693 = 13;
+ optional .benchmarks.google_message4.Message6578 field6694 = 15;
+ optional .benchmarks.google_message4.UnusedEnum field6695 = 16;
+ optional int64 field6696 = 17;
+ repeated .benchmarks.google_message4.UnusedEmptyMessage field6697 = 22;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field6698 = 19;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field6699 = 20;
+ optional int32 field6700 = 21;
+}
+
+message Message6133 {
+ optional .benchmarks.google_message4.Message4016 field6173 = 12;
+ optional double field6174 = 16;
+ required string field6175 = 1;
+ required string field6176 = 2;
+ required string field6177 = 3;
+ optional string field6178 = 4;
+ optional string field6179 = 8;
+ repeated .benchmarks.google_message4.Message6109 field6180 = 5;
+ repeated .benchmarks.google_message4.Message5908 field6181 = 13;
+ repeated .benchmarks.google_message4.Message6107 field6182 = 7;
+ repeated .benchmarks.google_message4.Message6126 field6183 = 9;
+ repeated .benchmarks.google_message4.Message6129 field6184 = 15;
+ optional int32 field6185 = 10;
+ optional int32 field6186 = 11;
+ optional .benchmarks.google_message4.Message4016 field6187 = 17;
+ optional double field6188 = 14;
+ optional double field6189 = 18;
+ optional string field6190 = 19;
+ optional string field6191 = 20;
+ repeated .benchmarks.google_message4.Message5881 field6192 = 21;
+}
+
+message Message6109 {
+ optional string field6140 = 1;
+ required .benchmarks.google_message4.Enum6111 field6141 = 2;
+ optional int32 field6142 = 9;
+ optional string field6143 = 3;
+ repeated .benchmarks.google_message4.Message6110 field6144 = 4;
+ repeated int32 field6145 = 7;
+ repeated int32 field6146 = 8;
+ optional .benchmarks.google_message4.Message6133 field6147 = 10;
+ repeated int32 field6148 = 11;
+ optional string field6149 = 12;
+ optional string field6150 = 13;
+ optional bool field6151 = 14;
+ extensions 1000 to 536870911;
+}
+
+message Message3046 {
+ required .benchmarks.google_message4.Enum2593 field3222 = 1;
+ optional int32 field3223 = 4;
+}
+
+message Message3060 {
+ optional int64 field3283 = 1;
+ optional int64 field3284 = 2;
+ optional int64 field3285 = 3;
+}
+
+message Message3041 {
+ optional string field3214 = 1;
+ optional int32 field3215 = 2;
+}
+
+message Message3040 {
+ required fixed64 field3209 = 1;
+ repeated fixed64 field3210 = 4;
+ optional int32 field3211 = 5;
+ optional fixed64 field3212 = 2;
+ required string field3213 = 3;
+}
+
+message Message3050 {
+ optional bytes field3245 = 5;
+ optional int32 field3246 = 2;
+ optional bytes field3247 = 6;
+ optional int32 field3248 = 4;
+ optional fixed32 field3249 = 1;
+ optional fixed32 field3250 = 3;
+}
+
+message Message7905 {
+ optional int32 field7911 = 1;
+ optional bool field7912 = 2;
+ optional bytes field7913 = 3;
+ optional int32 field7914 = 4;
+ optional int32 field7915 = 5;
+ optional bytes field7916 = 6;
+ optional int32 field7917 = 7;
+}
+
+message Message3886 {
+ repeated group Message3887 = 1 {
+ required string field3932 = 2;
+ optional string field3933 = 9;
+ optional .benchmarks.google_message4.Message3850 field3934 = 3;
+ optional bytes field3935 = 8;
+ }
+}
+
+message Message7864 {
+ optional string field7866 = 1;
+ optional string field7867 = 2;
+ repeated .benchmarks.google_message4.Message7865 field7868 = 5;
+ repeated .benchmarks.google_message4.Message7865 field7869 = 6;
+ repeated .benchmarks.google_message4.Message7865 field7870 = 7;
+ repeated .benchmarks.google_message4.UnusedEmptyMessage field7871 = 8;
+}
+
+message Message3922 {
+ optional uint64 field4012 = 1;
+}
+
+message Message3052 {
+ repeated string field3254 = 1;
+ repeated string field3255 = 2;
+ repeated bytes field3256 = 3;
+ repeated string field3257 = 4;
+ optional bool field3258 = 5;
+ optional int32 field3259 = 6;
+ optional int32 field3260 = 7;
+ optional string field3261 = 8;
+ optional string field3262 = 9;
+}
+
+message Message8575 {
+}
+
+message Message7843 {
+ optional bool field7844 = 5;
+ optional int32 field7845 = 1;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7846 = 22;
+ repeated int32 field7847 = 3;
+ repeated string field7848 = 11;
+ optional .benchmarks.google_message4.UnusedEnum field7849 = 15;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7850 = 6;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7851 = 14;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7852 = 10;
+ optional .benchmarks.google_message4.Message7511 field7853 = 13;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7854 = 16;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7855 = 17;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7856 = 19;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field7857 = 18;
+ optional .benchmarks.google_message4.UnusedEnum field7858 = 20;
+ optional int32 field7859 = 2;
+}
+
+message Message3919 {
+ repeated .benchmarks.google_message4.Message3920 field4009 = 1;
+}
+
+message Message7929 {
+ optional int64 field7942 = 1;
+ optional int64 field7943 = 4;
+ optional int64 field7944 = 5;
+ optional int64 field7945 = 12;
+ optional int64 field7946 = 13;
+ optional int64 field7947 = 18;
+ optional int64 field7948 = 6;
+ optional int64 field7949 = 7;
+ repeated .benchmarks.google_message4.Message7919 field7950 = 8;
+ repeated .benchmarks.google_message4.UnusedEmptyMessage field7951 = 20;
+ repeated .benchmarks.google_message4.Message7920 field7952 = 14;
+ repeated .benchmarks.google_message4.Message7921 field7953 = 15;
+ repeated .benchmarks.google_message4.Message7928 field7954 = 17;
+ optional int64 field7955 = 19;
+ optional bool field7956 = 2;
+ optional int64 field7957 = 3;
+ optional int64 field7958 = 9;
+ repeated .benchmarks.google_message4.UnusedEmptyMessage field7959 = 10;
+ repeated bytes field7960 = 11;
+ optional int64 field7961 = 16;
+}
+
diff --git a/benchmarks/datasets/google_message4/benchmark_message4_2.proto b/benchmarks/datasets/google_message4/benchmark_message4_2.proto
new file mode 100644
index 00000000..d5e9da5a
--- /dev/null
+++ b/benchmarks/datasets/google_message4/benchmark_message4_2.proto
@@ -0,0 +1,292 @@
+syntax = "proto2";
+
+import "datasets/google_message4/benchmark_message4_3.proto";
+package benchmarks.google_message4;
+
+option cc_enable_arenas = true;
+option java_package = "com.google.protobuf.benchmarks";
+
+message Message12774 {
+ optional uint32 field12777 = 1;
+ optional uint32 field12778 = 2;
+ optional uint32 field12779 = 3;
+ optional uint32 field12780 = 4;
+ optional uint32 field12781 = 5;
+ optional bool field12782 = 6;
+}
+
+message Message12796 {
+ repeated fixed64 field12800 = 1;
+ optional uint64 field12801 = 2;
+}
+
+message Message12821 {
+ optional int32 field12848 = 1;
+ optional int32 field12849 = 2;
+ optional int32 field12850 = 3;
+ optional int32 field12851 = 4;
+ optional int32 field12852 = 5;
+}
+
+message Message12820 {
+ optional int32 field12840 = 1;
+ optional int32 field12841 = 2;
+ optional int32 field12842 = 3;
+ optional int32 field12843 = 8;
+ optional int32 field12844 = 4;
+ optional int32 field12845 = 5;
+ optional int32 field12846 = 6;
+ optional int32 field12847 = 7;
+}
+
+message Message12819 {
+ optional double field12834 = 1;
+ optional double field12835 = 2;
+ optional double field12836 = 3;
+ optional double field12837 = 4;
+ optional double field12838 = 5;
+ optional double field12839 = 6;
+}
+
+message Message12818 {
+ optional uint64 field12829 = 1;
+ optional int32 field12830 = 2;
+ optional int32 field12831 = 3;
+ optional int32 field12832 = 5;
+ repeated .benchmarks.google_message4.Message12817 field12833 = 4;
+}
+
+message Message10319 {
+ optional .benchmarks.google_message4.Enum10325 field10340 = 1;
+ optional int32 field10341 = 4;
+ optional int32 field10342 = 5;
+ optional bytes field10343 = 3;
+ optional string field10344 = 2;
+ optional string field10345 = 6;
+ optional string field10346 = 7;
+}
+
+message Message6578 {
+ optional .benchmarks.google_message4.Enum6579 field6632 = 1;
+ optional .benchmarks.google_message4.Enum6588 field6633 = 2;
+}
+
+message Message6126 {
+ required string field6152 = 1;
+ repeated .benchmarks.google_message4.Message6127 field6153 = 9;
+ optional int32 field6154 = 14;
+ optional bytes field6155 = 10;
+ optional .benchmarks.google_message4.Message6024 field6156 = 12;
+ optional int32 field6157 = 4;
+ optional string field6158 = 5;
+ optional int32 field6159 = 6;
+ repeated int32 field6160 = 2;
+ repeated int32 field6161 = 3;
+ repeated .benchmarks.google_message4.Message6052 field6162 = 7;
+ repeated .benchmarks.google_message4.UnusedEmptyMessage field6163 = 11;
+ optional .benchmarks.google_message4.Enum6065 field6164 = 15;
+ repeated .benchmarks.google_message4.Message6127 field6165 = 8;
+ optional bool field6166 = 13;
+ optional bool field6167 = 16;
+ optional bool field6168 = 18;
+ repeated .benchmarks.google_message4.Message6054 field6169 = 17;
+ optional int32 field6170 = 19;
+}
+
+message Message5881 {
+ required double field5897 = 1;
+ optional string field5898 = 5;
+ optional .benchmarks.google_message4.Message5861 field5899 = 2;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field5900 = 3;
+ optional .benchmarks.google_message4.Message5867 field5901 = 4;
+ optional .benchmarks.google_message4.Message5880 field5902 = 6;
+}
+
+message Message6110 {
+}
+
+message Message6107 {
+ optional .benchmarks.google_message4.Message4016 field6134 = 1;
+ optional int32 field6135 = 2;
+ optional string field6136 = 3;
+ repeated int32 field6137 = 4;
+ optional int32 field6138 = 5;
+ repeated .benchmarks.google_message4.Message6108 field6139 = 6;
+}
+
+message Message6129 {
+ required .benchmarks.google_message4.Enum6130 field6171 = 1;
+ required string field6172 = 2;
+}
+
+message Message5908 {
+ optional string field5971 = 1;
+ optional int32 field5972 = 2;
+ optional int32 field5973 = 3;
+ optional .benchmarks.google_message4.Enum5909 field5974 = 45;
+ optional .benchmarks.google_message4.Enum5912 field5975 = 4;
+ optional fixed32 field5976 = 50;
+ optional fixed32 field5977 = 5;
+ optional fixed32 field5978 = 6;
+ optional string field5979 = 7;
+ optional .benchmarks.google_message4.Enum5915 field5980 = 8;
+ optional .benchmarks.google_message4.Message5903 field5981 = 9;
+ optional .benchmarks.google_message4.Message5903 field5982 = 10;
+ optional .benchmarks.google_message4.Enum5920 field5983 = 11;
+ optional .benchmarks.google_message4.Enum5923 field5984 = 40;
+ optional .benchmarks.google_message4.Message5903 field5985 = 41;
+ optional .benchmarks.google_message4.Message5903 field5986 = 42;
+ optional .benchmarks.google_message4.Enum5928 field5987 = 47;
+ optional bool field5988 = 48;
+ repeated fixed32 field5989 = 49;
+ optional string field5990 = 12;
+ optional .benchmarks.google_message4.Message5903 field5991 = 13;
+ optional .benchmarks.google_message4.Message5903 field5992 = 14;
+ optional .benchmarks.google_message4.Message5903 field5993 = 15;
+ optional .benchmarks.google_message4.Message5903 field5994 = 16;
+ optional .benchmarks.google_message4.Message5903 field5995 = 32;
+ optional .benchmarks.google_message4.Message5903 field5996 = 33;
+ optional .benchmarks.google_message4.Message5903 field5997 = 34;
+ optional .benchmarks.google_message4.Message5903 field5998 = 35;
+ optional .benchmarks.google_message4.Enum5931 field5999 = 17;
+ optional .benchmarks.google_message4.Enum5935 field6000 = 18;
+ optional .benchmarks.google_message4.Enum5939 field6001 = 36;
+ optional .benchmarks.google_message4.Enum5939 field6002 = 37;
+ repeated int32 field6003 = 19;
+ optional uint32 field6004 = 20;
+ optional uint32 field6005 = 21;
+ optional uint32 field6006 = 22;
+ optional uint32 field6007 = 23;
+ optional .benchmarks.google_message4.Enum5946 field6008 = 24;
+ optional .benchmarks.google_message4.Enum5946 field6009 = 25;
+ optional .benchmarks.google_message4.Enum5946 field6010 = 26;
+ optional .benchmarks.google_message4.Enum5946 field6011 = 27;
+ optional fixed32 field6012 = 28;
+ optional fixed32 field6013 = 29;
+ optional fixed32 field6014 = 30;
+ optional fixed32 field6015 = 31;
+ optional int32 field6016 = 38;
+ optional float field6017 = 39;
+ optional .benchmarks.google_message4.Enum5957 field6018 = 43;
+ optional .benchmarks.google_message4.Message5907 field6019 = 44;
+ optional .benchmarks.google_message4.Enum5962 field6020 = 46;
+}
+
+message Message3850 {
+ optional .benchmarks.google_message4.Enum3851 field3924 = 2;
+ optional bool field3925 = 12;
+ optional int32 field3926 = 4;
+ optional bool field3927 = 10;
+ optional bool field3928 = 13;
+ optional bool field3929 = 14;
+}
+
+message Message7865 {
+}
+
+message Message7511 {
+ optional bool field7523 = 1;
+ optional .benchmarks.google_message4.Enum7512 field7524 = 2;
+ optional int32 field7525 = 3;
+ optional int32 field7526 = 4;
+ optional bool field7527 = 5;
+ optional int32 field7528 = 6;
+ optional int32 field7529 = 7;
+}
+
+message Message3920 {
+}
+
+message Message7928 {
+ optional string field7940 = 1;
+ optional int64 field7941 = 2;
+}
+
+message Message7921 {
+ optional int32 field7936 = 1;
+ optional int64 field7937 = 2;
+ optional float field7938 = 3;
+ optional .benchmarks.google_message4.Enum7922 field7939 = 4;
+}
+
+message Message7920 {
+ optional int64 field7934 = 1;
+ optional int64 field7935 = 2;
+}
+
+message Message7919 {
+ optional fixed64 field7931 = 1;
+ optional int64 field7932 = 2;
+ optional bytes field7933 = 3;
+}
+
+message Message12817 {
+ optional int32 field12826 = 1;
+ optional int32 field12827 = 2;
+ optional int32 field12828 = 3;
+}
+
+message Message6054 {
+ required string field6089 = 1;
+ optional string field6090 = 2;
+}
+
+message Message6127 {
+}
+
+message Message6052 {
+ required string field6084 = 1;
+ required bytes field6085 = 2;
+}
+
+message Message6024 {
+ optional .benchmarks.google_message4.Enum6025 field6048 = 1;
+ optional string field6049 = 2;
+ optional .benchmarks.google_message4.UnusedEmptyMessage field6050 = 3;
+}
+
+message Message5861 {
+ required .benchmarks.google_message4.Enum5862 field5882 = 1;
+ required string field5883 = 2;
+ optional bool field5884 = 3;
+ optional string field5885 = 4;
+}
+
+message Message5880 {
+ optional string field5896 = 1;
+}
+
+message Message5867 {
+ optional .benchmarks.google_message4.Enum5868 field5890 = 1;
+ optional string field5891 = 2;
+ optional .benchmarks.google_message4.Enum5873 field5892 = 3;
+ optional int32 field5893 = 4;
+ optional .benchmarks.google_message4.UnusedEnum field5894 = 5;
+ optional bool field5895 = 6;
+}
+
+message Message4016 {
+ required int32 field4017 = 1;
+ required int32 field4018 = 2;
+ required int32 field4019 = 3;
+ required int32 field4020 = 4;
+}
+
+message Message6108 {
+}
+
+message Message5907 {
+ optional .benchmarks.google_message4.Message5903 field5967 = 1;
+ optional .benchmarks.google_message4.Message5903 field5968 = 2;
+ optional .benchmarks.google_message4.Message5903 field5969 = 3;
+ optional .benchmarks.google_message4.Message5903 field5970 = 4;
+}
+
+message UnusedEmptyMessage {
+}
+
+message Message5903 {
+ required int32 field5965 = 1;
+ optional .benchmarks.google_message4.Enum5904 field5966 = 2;
+}
+
diff --git a/benchmarks/datasets/google_message4/benchmark_message4_3.proto b/benchmarks/datasets/google_message4/benchmark_message4_3.proto
new file mode 100644
index 00000000..544fad20
--- /dev/null
+++ b/benchmarks/datasets/google_message4/benchmark_message4_3.proto
@@ -0,0 +1,751 @@
+syntax = "proto2";
+
+package benchmarks.google_message4;
+
+option cc_enable_arenas = true;
+option java_package = "com.google.protobuf.benchmarks";
+
+enum UnusedEnum {
+ UNUSED_ENUM_VALUE1 = 0;
+ UNUSED_ENUM_VALUE2 = 1;
+}
+
+enum Enum2593 {
+ ENUM_VALUE2594 = 0;
+ ENUM_VALUE2595 = 1;
+ ENUM_VALUE2596 = 2;
+ ENUM_VALUE2597 = 3;
+ ENUM_VALUE2598 = 4;
+ ENUM_VALUE2599 = 5;
+ ENUM_VALUE2600 = 6;
+ ENUM_VALUE2601 = 7;
+}
+
+enum Enum2834 {
+ ENUM_VALUE2835 = 0;
+ ENUM_VALUE2836 = 1;
+ ENUM_VALUE2837 = 2;
+}
+
+enum Enum2806 {
+ ENUM_VALUE2807 = 0;
+ ENUM_VALUE2808 = 1;
+ ENUM_VALUE2809 = 2;
+ ENUM_VALUE2810 = 3;
+ ENUM_VALUE2811 = 4;
+ ENUM_VALUE2812 = 5;
+ ENUM_VALUE2813 = 6;
+ ENUM_VALUE2814 = 7;
+ ENUM_VALUE2815 = 8;
+ ENUM_VALUE2816 = 9;
+ ENUM_VALUE2817 = 10;
+ ENUM_VALUE2818 = 11;
+ ENUM_VALUE2819 = 12;
+ ENUM_VALUE2820 = 13;
+ ENUM_VALUE2821 = 14;
+}
+
+enum Enum2851 {
+ option allow_alias = true;
+ ENUM_VALUE2852 = 0;
+ ENUM_VALUE2853 = 0;
+ ENUM_VALUE2854 = 1;
+ ENUM_VALUE2855 = 2;
+ ENUM_VALUE2856 = 3;
+ ENUM_VALUE2857 = 4;
+ ENUM_VALUE2858 = 5;
+ ENUM_VALUE2859 = 6;
+ ENUM_VALUE2860 = 7;
+ ENUM_VALUE2861 = 8;
+ ENUM_VALUE2862 = 9;
+ ENUM_VALUE2863 = 10;
+ ENUM_VALUE2864 = 11;
+ ENUM_VALUE2865 = 12;
+ ENUM_VALUE2866 = 13;
+ ENUM_VALUE2867 = 14;
+ ENUM_VALUE2868 = 15;
+ ENUM_VALUE2869 = 16;
+ ENUM_VALUE2870 = 17;
+ ENUM_VALUE2871 = 18;
+ ENUM_VALUE2872 = 19;
+ ENUM_VALUE2873 = 20;
+ ENUM_VALUE2874 = 21;
+ ENUM_VALUE2875 = 22;
+ ENUM_VALUE2876 = 23;
+ ENUM_VALUE2877 = 24;
+ ENUM_VALUE2878 = 25;
+ ENUM_VALUE2879 = 26;
+ ENUM_VALUE2880 = 27;
+ ENUM_VALUE2881 = 28;
+ ENUM_VALUE2882 = 29;
+ ENUM_VALUE2883 = 30;
+ ENUM_VALUE2884 = 31;
+ ENUM_VALUE2885 = 32;
+ ENUM_VALUE2886 = 33;
+ ENUM_VALUE2887 = 34;
+ ENUM_VALUE2888 = 35;
+ ENUM_VALUE2889 = 36;
+ ENUM_VALUE2890 = 37;
+ ENUM_VALUE2891 = 38;
+ ENUM_VALUE2892 = 39;
+ ENUM_VALUE2893 = 40;
+ ENUM_VALUE2894 = 41;
+ ENUM_VALUE2895 = 42;
+ ENUM_VALUE2896 = 43;
+ ENUM_VALUE2897 = 44;
+ ENUM_VALUE2898 = 45;
+ ENUM_VALUE2899 = 46;
+ ENUM_VALUE2900 = 47;
+ ENUM_VALUE2901 = 48;
+ ENUM_VALUE2902 = 49;
+ ENUM_VALUE2903 = 50;
+ ENUM_VALUE2904 = 51;
+ ENUM_VALUE2905 = 52;
+ ENUM_VALUE2906 = 53;
+ ENUM_VALUE2907 = 54;
+ ENUM_VALUE2908 = 55;
+ ENUM_VALUE2909 = 56;
+ ENUM_VALUE2910 = 57;
+ ENUM_VALUE2911 = 58;
+ ENUM_VALUE2912 = 59;
+ ENUM_VALUE2913 = 60;
+ ENUM_VALUE2914 = 61;
+ ENUM_VALUE2915 = 62;
+ ENUM_VALUE2916 = 63;
+ ENUM_VALUE2917 = 64;
+ ENUM_VALUE2918 = 65;
+ ENUM_VALUE2919 = 66;
+ ENUM_VALUE2920 = 67;
+ ENUM_VALUE2921 = 68;
+ ENUM_VALUE2922 = 69;
+ ENUM_VALUE2923 = 70;
+ ENUM_VALUE2924 = 71;
+ ENUM_VALUE2925 = 72;
+ ENUM_VALUE2926 = 73;
+ ENUM_VALUE2927 = 74;
+ ENUM_VALUE2928 = 75;
+ ENUM_VALUE2929 = 76;
+ ENUM_VALUE2930 = 77;
+ ENUM_VALUE2931 = 78;
+ ENUM_VALUE2932 = 79;
+ ENUM_VALUE2933 = 80;
+ ENUM_VALUE2934 = 81;
+ ENUM_VALUE2935 = 82;
+ ENUM_VALUE2936 = 83;
+ ENUM_VALUE2937 = 84;
+ ENUM_VALUE2938 = 85;
+ ENUM_VALUE2939 = 86;
+ ENUM_VALUE2940 = 87;
+ ENUM_VALUE2941 = 88;
+ ENUM_VALUE2942 = 89;
+ ENUM_VALUE2943 = 90;
+ ENUM_VALUE2944 = 91;
+ ENUM_VALUE2945 = 92;
+ ENUM_VALUE2946 = 93;
+ ENUM_VALUE2947 = 94;
+ ENUM_VALUE2948 = 95;
+ ENUM_VALUE2949 = 96;
+ ENUM_VALUE2950 = 97;
+ ENUM_VALUE2951 = 98;
+ ENUM_VALUE2952 = 99;
+ ENUM_VALUE2953 = 100;
+ ENUM_VALUE2954 = 101;
+ ENUM_VALUE2955 = 102;
+ ENUM_VALUE2956 = 103;
+ ENUM_VALUE2957 = 104;
+ ENUM_VALUE2958 = 105;
+ ENUM_VALUE2959 = 106;
+ ENUM_VALUE2960 = 107;
+ ENUM_VALUE2961 = 108;
+ ENUM_VALUE2962 = 109;
+ ENUM_VALUE2963 = 110;
+ ENUM_VALUE2964 = 111;
+ ENUM_VALUE2965 = 112;
+ ENUM_VALUE2966 = 113;
+ ENUM_VALUE2967 = 114;
+ ENUM_VALUE2968 = 115;
+ ENUM_VALUE2969 = 116;
+ ENUM_VALUE2970 = 117;
+ ENUM_VALUE2971 = 118;
+ ENUM_VALUE2972 = 119;
+}
+
+enum Enum2602 {
+ ENUM_VALUE2603 = 0;
+ ENUM_VALUE2604 = 1;
+ ENUM_VALUE2605 = 2;
+ ENUM_VALUE2606 = 3;
+ ENUM_VALUE2607 = 4;
+ ENUM_VALUE2608 = 5;
+ ENUM_VALUE2609 = 6;
+ ENUM_VALUE2610 = 7;
+ ENUM_VALUE2611 = 8;
+ ENUM_VALUE2612 = 9;
+ ENUM_VALUE2613 = 10;
+ ENUM_VALUE2614 = 11;
+}
+
+enum Enum3071 {
+ ENUM_VALUE3072 = 1;
+ ENUM_VALUE3073 = 2;
+ ENUM_VALUE3074 = 3;
+ ENUM_VALUE3075 = 4;
+ ENUM_VALUE3076 = 5;
+ ENUM_VALUE3077 = 6;
+ ENUM_VALUE3078 = 7;
+ ENUM_VALUE3079 = 8;
+ ENUM_VALUE3080 = 9;
+ ENUM_VALUE3081 = 10;
+ ENUM_VALUE3082 = 11;
+ ENUM_VALUE3083 = 12;
+ ENUM_VALUE3084 = 13;
+ ENUM_VALUE3085 = 14;
+ ENUM_VALUE3086 = 15;
+ ENUM_VALUE3087 = 16;
+ ENUM_VALUE3088 = 17;
+ ENUM_VALUE3089 = 18;
+ ENUM_VALUE3090 = 19;
+ ENUM_VALUE3091 = 20;
+ ENUM_VALUE3092 = 21;
+ ENUM_VALUE3093 = 22;
+ ENUM_VALUE3094 = 23;
+ ENUM_VALUE3095 = 24;
+ ENUM_VALUE3096 = 25;
+ ENUM_VALUE3097 = 26;
+ ENUM_VALUE3098 = 27;
+ ENUM_VALUE3099 = 28;
+}
+
+enum Enum3805 {
+ ENUM_VALUE3806 = 0;
+ ENUM_VALUE3807 = 1;
+ ENUM_VALUE3808 = 2;
+ ENUM_VALUE3809 = 3;
+ ENUM_VALUE3810 = 4;
+ ENUM_VALUE3811 = 5;
+ ENUM_VALUE3812 = 6;
+ ENUM_VALUE3813 = 7;
+ ENUM_VALUE3814 = 8;
+ ENUM_VALUE3815 = 9;
+ ENUM_VALUE3816 = 11;
+ ENUM_VALUE3817 = 10;
+}
+
+enum Enum3783 {
+ ENUM_VALUE3784 = 0;
+ ENUM_VALUE3785 = 1;
+ ENUM_VALUE3786 = 2;
+ ENUM_VALUE3787 = 3;
+ ENUM_VALUE3788 = 4;
+ ENUM_VALUE3789 = 5;
+ ENUM_VALUE3790 = 6;
+ ENUM_VALUE3791 = 7;
+ ENUM_VALUE3792 = 8;
+ ENUM_VALUE3793 = 9;
+ ENUM_VALUE3794 = 10;
+ ENUM_VALUE3795 = 11;
+ ENUM_VALUE3796 = 12;
+ ENUM_VALUE3797 = 13;
+ ENUM_VALUE3798 = 14;
+ ENUM_VALUE3799 = 15;
+ ENUM_VALUE3800 = 16;
+ ENUM_VALUE3801 = 20;
+ ENUM_VALUE3802 = 21;
+ ENUM_VALUE3803 = 50;
+}
+
+enum Enum3851 {
+ ENUM_VALUE3852 = 0;
+ ENUM_VALUE3853 = 1;
+ ENUM_VALUE3854 = 2;
+ ENUM_VALUE3855 = 3;
+ ENUM_VALUE3856 = 4;
+ ENUM_VALUE3857 = 5;
+ ENUM_VALUE3858 = 6;
+ ENUM_VALUE3859 = 7;
+ ENUM_VALUE3860 = 8;
+ ENUM_VALUE3861 = 9;
+ ENUM_VALUE3862 = 10;
+ ENUM_VALUE3863 = 11;
+ ENUM_VALUE3864 = 12;
+ ENUM_VALUE3865 = 13;
+ ENUM_VALUE3866 = 14;
+ ENUM_VALUE3867 = 15;
+ ENUM_VALUE3868 = 16;
+ ENUM_VALUE3869 = 17;
+}
+
+enum Enum5862 {
+ ENUM_VALUE5863 = 1;
+ ENUM_VALUE5864 = 2;
+ ENUM_VALUE5865 = 3;
+}
+
+enum Enum5868 {
+ ENUM_VALUE5869 = 0;
+ ENUM_VALUE5870 = 1;
+ ENUM_VALUE5871 = 2;
+ ENUM_VALUE5872 = 3;
+}
+
+enum Enum5873 {
+ ENUM_VALUE5874 = 0;
+ ENUM_VALUE5875 = 1;
+ ENUM_VALUE5876 = 2;
+}
+
+enum Enum5904 {
+ ENUM_VALUE5905 = 0;
+ ENUM_VALUE5906 = 1;
+}
+
+enum Enum5909 {
+ ENUM_VALUE5910 = 0;
+ ENUM_VALUE5911 = 1;
+}
+
+enum Enum5912 {
+ ENUM_VALUE5913 = 0;
+ ENUM_VALUE5914 = 1;
+}
+
+enum Enum5915 {
+ ENUM_VALUE5916 = 0;
+ ENUM_VALUE5917 = 1;
+ ENUM_VALUE5918 = 2;
+ ENUM_VALUE5919 = 3;
+}
+
+enum Enum5920 {
+ ENUM_VALUE5921 = 0;
+ ENUM_VALUE5922 = 1;
+}
+
+enum Enum5923 {
+ ENUM_VALUE5924 = 0;
+ ENUM_VALUE5925 = 1;
+ ENUM_VALUE5926 = 2;
+ ENUM_VALUE5927 = 3;
+}
+
+enum Enum5928 {
+ ENUM_VALUE5929 = 0;
+ ENUM_VALUE5930 = 1;
+}
+
+enum Enum5931 {
+ ENUM_VALUE5932 = 0;
+ ENUM_VALUE5933 = 1;
+ ENUM_VALUE5934 = 2;
+}
+
+enum Enum5935 {
+ ENUM_VALUE5936 = 0;
+ ENUM_VALUE5937 = 1;
+ ENUM_VALUE5938 = 2;
+}
+
+enum Enum5939 {
+ ENUM_VALUE5940 = 0;
+ ENUM_VALUE5941 = 1;
+ ENUM_VALUE5942 = 2;
+ ENUM_VALUE5943 = 3;
+ ENUM_VALUE5944 = 4;
+ ENUM_VALUE5945 = 5;
+}
+
+enum Enum5946 {
+ ENUM_VALUE5947 = 0;
+ ENUM_VALUE5948 = 1;
+ ENUM_VALUE5949 = 2;
+ ENUM_VALUE5950 = 3;
+ ENUM_VALUE5951 = 4;
+ ENUM_VALUE5952 = 5;
+ ENUM_VALUE5953 = 6;
+ ENUM_VALUE5954 = 7;
+ ENUM_VALUE5955 = 8;
+ ENUM_VALUE5956 = 9;
+}
+
+enum Enum5957 {
+ ENUM_VALUE5958 = 0;
+ ENUM_VALUE5959 = 1;
+ ENUM_VALUE5960 = 2;
+ ENUM_VALUE5961 = 3;
+}
+
+enum Enum5962 {
+ ENUM_VALUE5963 = 0;
+ ENUM_VALUE5964 = 1;
+}
+
+enum Enum6025 {
+ ENUM_VALUE6026 = 0;
+ ENUM_VALUE6027 = 1;
+ ENUM_VALUE6028 = 2;
+ ENUM_VALUE6029 = 3;
+ ENUM_VALUE6030 = 4;
+ ENUM_VALUE6031 = 5;
+ ENUM_VALUE6032 = 6;
+ ENUM_VALUE6033 = 7;
+ ENUM_VALUE6034 = 8;
+ ENUM_VALUE6035 = 9;
+ ENUM_VALUE6036 = 10;
+ ENUM_VALUE6037 = 11;
+ ENUM_VALUE6038 = 12;
+ ENUM_VALUE6039 = 13;
+ ENUM_VALUE6040 = 14;
+ ENUM_VALUE6041 = 15;
+ ENUM_VALUE6042 = 16;
+ ENUM_VALUE6043 = 17;
+ ENUM_VALUE6044 = 18;
+ ENUM_VALUE6045 = 19;
+ ENUM_VALUE6046 = 20;
+ ENUM_VALUE6047 = 21;
+}
+
+enum Enum6111 {
+ ENUM_VALUE6112 = 1;
+ ENUM_VALUE6113 = 2;
+ ENUM_VALUE6114 = 3;
+ ENUM_VALUE6115 = 4;
+ ENUM_VALUE6116 = 5;
+ ENUM_VALUE6117 = 6;
+ ENUM_VALUE6118 = 7;
+ ENUM_VALUE6119 = 8;
+ ENUM_VALUE6120 = 9;
+ ENUM_VALUE6121 = 10;
+ ENUM_VALUE6122 = 11;
+ ENUM_VALUE6123 = 12;
+ ENUM_VALUE6124 = 13;
+ ENUM_VALUE6125 = 14;
+}
+
+enum Enum6065 {
+ ENUM_VALUE6066 = 0;
+ ENUM_VALUE6067 = 1;
+ ENUM_VALUE6068 = 2;
+ ENUM_VALUE6069 = 3;
+ ENUM_VALUE6070 = 4;
+ ENUM_VALUE6071 = 5;
+ ENUM_VALUE6072 = 6;
+ ENUM_VALUE6073 = 7;
+ ENUM_VALUE6074 = 8;
+ ENUM_VALUE6075 = 9;
+ ENUM_VALUE6076 = 10;
+ ENUM_VALUE6077 = 11;
+ ENUM_VALUE6078 = 12;
+ ENUM_VALUE6079 = 13;
+ ENUM_VALUE6080 = 14;
+}
+
+enum Enum6130 {
+ ENUM_VALUE6131 = 0;
+ ENUM_VALUE6132 = 1;
+}
+
+enum Enum6579 {
+ ENUM_VALUE6580 = 0;
+ ENUM_VALUE6581 = 2;
+ ENUM_VALUE6582 = 3;
+ ENUM_VALUE6583 = 5;
+ ENUM_VALUE6584 = 10;
+ ENUM_VALUE6585 = 15;
+ ENUM_VALUE6586 = 25;
+ ENUM_VALUE6587 = 30;
+}
+
+enum Enum6588 {
+ ENUM_VALUE6589 = 0;
+ ENUM_VALUE6590 = 1;
+ ENUM_VALUE6591 = 2;
+ ENUM_VALUE6592 = 3;
+ ENUM_VALUE6593 = 4;
+ ENUM_VALUE6594 = 5;
+ ENUM_VALUE6595 = 6;
+ ENUM_VALUE6596 = 7;
+ ENUM_VALUE6597 = 8;
+ ENUM_VALUE6598 = 9;
+ ENUM_VALUE6599 = 10;
+ ENUM_VALUE6600 = 11;
+ ENUM_VALUE6601 = 12;
+ ENUM_VALUE6602 = 13;
+ ENUM_VALUE6603 = 14;
+ ENUM_VALUE6604 = 15;
+ ENUM_VALUE6605 = 16;
+ ENUM_VALUE6606 = 17;
+ ENUM_VALUE6607 = 19;
+ ENUM_VALUE6608 = 20;
+ ENUM_VALUE6609 = 21;
+ ENUM_VALUE6610 = 22;
+ ENUM_VALUE6611 = 23;
+ ENUM_VALUE6612 = 24;
+ ENUM_VALUE6613 = 25;
+ ENUM_VALUE6614 = 26;
+ ENUM_VALUE6615 = 27;
+ ENUM_VALUE6616 = 28;
+ ENUM_VALUE6617 = 29;
+ ENUM_VALUE6618 = 30;
+ ENUM_VALUE6619 = 31;
+ ENUM_VALUE6620 = 32;
+ ENUM_VALUE6621 = 33;
+ ENUM_VALUE6622 = 34;
+}
+
+enum Enum7288 {
+ ENUM_VALUE7289 = 0;
+ ENUM_VALUE7290 = 1;
+ ENUM_VALUE7291 = 2;
+ ENUM_VALUE7292 = 3;
+}
+
+enum Enum7512 {
+ ENUM_VALUE7513 = 0;
+ ENUM_VALUE7514 = 1;
+ ENUM_VALUE7515 = 2;
+ ENUM_VALUE7516 = 3;
+ ENUM_VALUE7517 = 4;
+ ENUM_VALUE7518 = 5;
+ ENUM_VALUE7519 = 6;
+ ENUM_VALUE7520 = 7;
+}
+
+enum Enum7922 {
+ ENUM_VALUE7923 = 1;
+ ENUM_VALUE7924 = 2;
+ ENUM_VALUE7925 = 3;
+ ENUM_VALUE7926 = 4;
+ ENUM_VALUE7927 = 5;
+}
+
+enum Enum3476 {
+ ENUM_VALUE3477 = 0;
+ ENUM_VALUE3478 = 1;
+ ENUM_VALUE3479 = 2;
+ ENUM_VALUE3480 = 3;
+ ENUM_VALUE3481 = 4;
+ ENUM_VALUE3482 = 5;
+ ENUM_VALUE3483 = 6;
+ ENUM_VALUE3484 = 7;
+ ENUM_VALUE3485 = 8;
+ ENUM_VALUE3486 = 9;
+ ENUM_VALUE3487 = 10;
+ ENUM_VALUE3488 = 11;
+ ENUM_VALUE3489 = 12;
+ ENUM_VALUE3490 = 13;
+ ENUM_VALUE3491 = 14;
+ ENUM_VALUE3492 = 15;
+ ENUM_VALUE3493 = 16;
+ ENUM_VALUE3494 = 17;
+ ENUM_VALUE3495 = 18;
+ ENUM_VALUE3496 = 19;
+ ENUM_VALUE3497 = 20;
+ ENUM_VALUE3498 = 21;
+ ENUM_VALUE3499 = 22;
+ ENUM_VALUE3500 = 23;
+ ENUM_VALUE3501 = 24;
+ ENUM_VALUE3502 = 25;
+ ENUM_VALUE3503 = 26;
+ ENUM_VALUE3504 = 27;
+ ENUM_VALUE3505 = 28;
+ ENUM_VALUE3506 = 29;
+ ENUM_VALUE3507 = 30;
+ ENUM_VALUE3508 = 31;
+ ENUM_VALUE3509 = 32;
+ ENUM_VALUE3510 = 33;
+ ENUM_VALUE3511 = 34;
+ ENUM_VALUE3512 = 35;
+ ENUM_VALUE3513 = 36;
+ ENUM_VALUE3514 = 37;
+ ENUM_VALUE3515 = 38;
+ ENUM_VALUE3516 = 39;
+ ENUM_VALUE3517 = 40;
+ ENUM_VALUE3518 = 41;
+ ENUM_VALUE3519 = 42;
+ ENUM_VALUE3520 = 43;
+ ENUM_VALUE3521 = 44;
+ ENUM_VALUE3522 = 45;
+ ENUM_VALUE3523 = 46;
+ ENUM_VALUE3524 = 47;
+ ENUM_VALUE3525 = 48;
+ ENUM_VALUE3526 = 49;
+ ENUM_VALUE3527 = 50;
+ ENUM_VALUE3528 = 51;
+ ENUM_VALUE3529 = 52;
+ ENUM_VALUE3530 = 53;
+ ENUM_VALUE3531 = 54;
+ ENUM_VALUE3532 = 55;
+ ENUM_VALUE3533 = 56;
+ ENUM_VALUE3534 = 57;
+ ENUM_VALUE3535 = 58;
+ ENUM_VALUE3536 = 59;
+ ENUM_VALUE3537 = 60;
+ ENUM_VALUE3538 = 61;
+ ENUM_VALUE3539 = 62;
+ ENUM_VALUE3540 = 63;
+ ENUM_VALUE3541 = 64;
+ ENUM_VALUE3542 = 65;
+ ENUM_VALUE3543 = 66;
+ ENUM_VALUE3544 = 67;
+ ENUM_VALUE3545 = 68;
+ ENUM_VALUE3546 = 69;
+ ENUM_VALUE3547 = 70;
+ ENUM_VALUE3548 = 71;
+ ENUM_VALUE3549 = 72;
+ ENUM_VALUE3550 = 73;
+ ENUM_VALUE3551 = 74;
+ ENUM_VALUE3552 = 75;
+ ENUM_VALUE3553 = 76;
+ ENUM_VALUE3554 = 77;
+ ENUM_VALUE3555 = 78;
+ ENUM_VALUE3556 = 79;
+ ENUM_VALUE3557 = 80;
+ ENUM_VALUE3558 = 81;
+ ENUM_VALUE3559 = 82;
+ ENUM_VALUE3560 = 83;
+ ENUM_VALUE3561 = 84;
+ ENUM_VALUE3562 = 85;
+ ENUM_VALUE3563 = 86;
+ ENUM_VALUE3564 = 87;
+ ENUM_VALUE3565 = 88;
+ ENUM_VALUE3566 = 89;
+ ENUM_VALUE3567 = 90;
+ ENUM_VALUE3568 = 91;
+ ENUM_VALUE3569 = 92;
+ ENUM_VALUE3570 = 93;
+ ENUM_VALUE3571 = 94;
+ ENUM_VALUE3572 = 95;
+ ENUM_VALUE3573 = 96;
+ ENUM_VALUE3574 = 97;
+ ENUM_VALUE3575 = 98;
+ ENUM_VALUE3576 = 99;
+ ENUM_VALUE3577 = 100;
+ ENUM_VALUE3578 = 101;
+ ENUM_VALUE3579 = 102;
+ ENUM_VALUE3580 = 103;
+ ENUM_VALUE3581 = 104;
+ ENUM_VALUE3582 = 105;
+ ENUM_VALUE3583 = 106;
+ ENUM_VALUE3584 = 107;
+ ENUM_VALUE3585 = 108;
+ ENUM_VALUE3586 = 109;
+ ENUM_VALUE3587 = 110;
+ ENUM_VALUE3588 = 111;
+ ENUM_VALUE3589 = 112;
+ ENUM_VALUE3590 = 113;
+ ENUM_VALUE3591 = 114;
+ ENUM_VALUE3592 = 115;
+ ENUM_VALUE3593 = 116;
+ ENUM_VALUE3594 = 117;
+ ENUM_VALUE3595 = 118;
+ ENUM_VALUE3596 = 119;
+ ENUM_VALUE3597 = 120;
+ ENUM_VALUE3598 = 121;
+ ENUM_VALUE3599 = 122;
+ ENUM_VALUE3600 = 123;
+ ENUM_VALUE3601 = 124;
+ ENUM_VALUE3602 = 125;
+ ENUM_VALUE3603 = 126;
+ ENUM_VALUE3604 = 127;
+ ENUM_VALUE3605 = 128;
+ ENUM_VALUE3606 = 129;
+ ENUM_VALUE3607 = 130;
+ ENUM_VALUE3608 = 131;
+ ENUM_VALUE3609 = 132;
+ ENUM_VALUE3610 = 133;
+ ENUM_VALUE3611 = 134;
+ ENUM_VALUE3612 = 135;
+ ENUM_VALUE3613 = 136;
+ ENUM_VALUE3614 = 137;
+ ENUM_VALUE3615 = 138;
+ ENUM_VALUE3616 = 139;
+ ENUM_VALUE3617 = 140;
+ ENUM_VALUE3618 = 141;
+ ENUM_VALUE3619 = 142;
+ ENUM_VALUE3620 = 143;
+ ENUM_VALUE3621 = 144;
+ ENUM_VALUE3622 = 145;
+ ENUM_VALUE3623 = 146;
+ ENUM_VALUE3624 = 147;
+ ENUM_VALUE3625 = 148;
+ ENUM_VALUE3626 = 149;
+ ENUM_VALUE3627 = 150;
+ ENUM_VALUE3628 = 151;
+ ENUM_VALUE3629 = 152;
+ ENUM_VALUE3630 = 153;
+ ENUM_VALUE3631 = 154;
+ ENUM_VALUE3632 = 155;
+ ENUM_VALUE3633 = 156;
+ ENUM_VALUE3634 = 157;
+ ENUM_VALUE3635 = 158;
+ ENUM_VALUE3636 = 159;
+ ENUM_VALUE3637 = 160;
+ ENUM_VALUE3638 = 161;
+ ENUM_VALUE3639 = 162;
+ ENUM_VALUE3640 = 163;
+ ENUM_VALUE3641 = 164;
+ ENUM_VALUE3642 = 165;
+ ENUM_VALUE3643 = 166;
+ ENUM_VALUE3644 = 167;
+ ENUM_VALUE3645 = 168;
+ ENUM_VALUE3646 = 169;
+ ENUM_VALUE3647 = 170;
+ ENUM_VALUE3648 = 171;
+ ENUM_VALUE3649 = 172;
+ ENUM_VALUE3650 = 173;
+ ENUM_VALUE3651 = 174;
+ ENUM_VALUE3652 = 175;
+ ENUM_VALUE3653 = 176;
+ ENUM_VALUE3654 = 177;
+ ENUM_VALUE3655 = 178;
+ ENUM_VALUE3656 = 179;
+ ENUM_VALUE3657 = 180;
+ ENUM_VALUE3658 = 181;
+ ENUM_VALUE3659 = 182;
+ ENUM_VALUE3660 = 183;
+}
+
+enum Enum10325 {
+ ENUM_VALUE10326 = 0;
+ ENUM_VALUE10327 = 1;
+ ENUM_VALUE10328 = 2;
+ ENUM_VALUE10329 = 3;
+ ENUM_VALUE10330 = 4;
+ ENUM_VALUE10331 = 5;
+ ENUM_VALUE10332 = 6;
+ ENUM_VALUE10333 = 7;
+ ENUM_VALUE10334 = 8;
+}
+
+enum Enum10335 {
+ ENUM_VALUE10336 = 0;
+}
+
+enum Enum10337 {
+ ENUM_VALUE10338 = 0;
+ ENUM_VALUE10339 = 1;
+}
+
+enum Enum11901 {
+ ENUM_VALUE11902 = 0;
+ ENUM_VALUE11903 = 1;
+ ENUM_VALUE11904 = 2;
+ ENUM_VALUE11905 = 3;
+}
+
+enum Enum12735 {
+ ENUM_VALUE12736 = 0;
+ ENUM_VALUE12737 = 1;
+ ENUM_VALUE12738 = 2;
+ ENUM_VALUE12739 = 3;
+}
+
+enum Enum12871 {
+ ENUM_VALUE12872 = 1;
+ ENUM_VALUE12873 = 2;
+ ENUM_VALUE12874 = 3;
+ ENUM_VALUE12875 = 4;
+ ENUM_VALUE12876 = 5;
+ ENUM_VALUE12877 = 6;
+}
+
diff --git a/benchmarks/download_data.sh b/benchmarks/download_data.sh
new file mode 100755
index 00000000..fa0729e9
--- /dev/null
+++ b/benchmarks/download_data.sh
@@ -0,0 +1,5 @@
+#! /bin/sh
+
+curl -O https://storage.googleapis.com/protobuf_opensource_benchmark_data/datasets.tar.gz
+tar -zvxf datasets.tar.gz
+
diff --git a/benchmarks/generate_datasets.cc b/benchmarks/generate_datasets.cc
deleted file mode 100644
index 61e7adf1..00000000
--- a/benchmarks/generate_datasets.cc
+++ /dev/null
@@ -1,117 +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 <fstream>
-#include <iostream>
-#include "benchmarks.pb.h"
-
-using benchmarks::BenchmarkDataset;
-using google::protobuf::Descriptor;
-using google::protobuf::DescriptorPool;
-using google::protobuf::Message;
-using google::protobuf::MessageFactory;
-
-std::set<std::string> names;
-
-const char *file_prefix = "dataset.";
-const char *file_suffix = ".pb";
-
-void WriteFileWithPayloads(const std::string& name,
- const std::string& message_name,
- const std::vector<std::string>& payload) {
- if (!names.insert(name).second) {
- std::cerr << "Duplicate test name: " << name << "\n";
- abort();
- }
-
- // First verify that this message name exists in our set of benchmark messages
- // and that these payloads are valid for the given message.
- const Descriptor* d =
- DescriptorPool::generated_pool()->FindMessageTypeByName(message_name);
-
- if (!d) {
- std::cerr << "For dataset " << name << ", no such message: "
- << message_name << "\n";
- abort();
- }
-
- Message* m = MessageFactory::generated_factory()->GetPrototype(d)->New();
-
- for (size_t i = 0; i < payload.size(); i++) {
- if (!m->ParseFromString(payload[i])) {
- std::cerr << "For dataset " << name << ", payload[" << i << "] fails "
- << "to parse\n";
- abort();
- }
- }
-
- BenchmarkDataset dataset;
- dataset.set_name(name);
- dataset.set_message_name(message_name);
- for (size_t i = 0; i < payload.size(); i++) {
- dataset.add_payload()->assign(payload[i]);
- }
-
- std::ofstream writer;
- std::string fname = file_prefix + name + file_suffix;
- writer.open(fname.c_str());
- dataset.SerializeToOstream(&writer);
- writer.close();
-
- std::cerr << "Wrote dataset: " << fname << "\n";
-}
-
-void WriteFile(const std::string& name, const std::string& message_name,
- const std::string& payload) {
- std::vector<std::string> payloads;
- payloads.push_back(payload);
- WriteFileWithPayloads(name, message_name, payloads);
-}
-
-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() {
- WriteFile("google_message1_proto3", "benchmarks.proto3.GoogleMessage1",
- ReadFile("google_message1.dat"));
- WriteFile("google_message1_proto2", "benchmarks.proto2.GoogleMessage1",
- ReadFile("google_message1.dat"));
-
- // Not in proto3 because it has a group, which is not supported.
- WriteFile("google_message2", "benchmarks.proto2.GoogleMessage2",
- ReadFile("google_message2.dat"));
-}
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
new file mode 100755
index 00000000..c2cd78a1
--- /dev/null
+++ b/benchmarks/java/pom.xml
@@ -0,0 +1,95 @@
+<?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>
+ <artifactId>protobuf-java-benchmark</artifactId>
+ <groupId>com.google.protobuf</groupId>
+ <version>1.0.0</version>
+ <name>Protocol Buffers [Benchmark]</name>
+ <description>The benchmark tools for Protobuf Java.</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>com.google.protobuf</groupId>
+ <artifactId>protobuf-java</artifactId>
+ <version>3.5.0</version>
+ </dependency>
+ <dependency>
+ <groupId>com.google.caliper</groupId>
+ <artifactId>caliper</artifactId>
+ <version>1.0-beta-2</version>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>2.4.1</version>
+ <configuration>
+ <!-- get all project dependencies -->
+ <descriptorRefs>
+ <descriptorRef>jar-with-dependencies</descriptorRef>
+ </descriptorRefs>
+ <!-- MainClass in mainfest make a executable jar -->
+ <archive>
+ <manifest>
+ <mainClass>com.mkyong.core.utils.App</mainClass>
+ </manifest>
+ </archive>
+ </configuration>
+ <executions>
+ <execution>
+ <id>make-assembly</id>
+ <!-- bind to the packaging phase -->
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>3.5.1</version>
+ <configuration>
+ <source>1.8</source>
+ <target>1.8</target>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <version>2.5</version>
+ <configuration>
+ <archive>
+ <manifest>
+ <addClasspath>true</addClasspath>
+ <mainClass>com.google.protocolbuffers.ProtoBench</mainClass>
+ </manifest>
+ </archive>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-source-plugin</artifactId>
+ <version>2.4</version>
+ <executions>
+ <execution>
+ <id>attach-sources</id>
+ <goals>
+ <goal>jar-no-fork</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ </build>
+</project>
+
diff --git a/benchmarks/java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java b/benchmarks/java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java
new file mode 100755
index 00000000..94568aea
--- /dev/null
+++ b/benchmarks/java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java
@@ -0,0 +1,232 @@
+
+package com.google.protobuf;
+
+import com.google.caliper.BeforeExperiment;
+import com.google.caliper.AfterExperiment;
+import com.google.caliper.Benchmark;
+import com.google.caliper.Param;
+import com.google.protobuf.ByteString;
+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.BufferedWriter;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.util.ArrayList;
+import java.util.List;
+
+public class ProtoCaliperBenchmark {
+ public enum BenchmarkMessageType {
+ GOOGLE_MESSAGE1_PROTO3 {
+ @Override ExtensionRegistry getExtensionRegistry() { return ExtensionRegistry.newInstance(); }
+ @Override
+ Message getDefaultInstance() {
+ return com.google.protobuf.benchmarks.BenchmarkMessage1Proto3.GoogleMessage1
+ .getDefaultInstance();
+ }
+ },
+ GOOGLE_MESSAGE1_PROTO2 {
+ @Override ExtensionRegistry getExtensionRegistry() { return ExtensionRegistry.newInstance(); }
+ @Override
+ Message getDefaultInstance() {
+ return com.google.protobuf.benchmarks.BenchmarkMessage1Proto2.GoogleMessage1
+ .getDefaultInstance();
+ }
+ },
+ GOOGLE_MESSAGE2 {
+ @Override ExtensionRegistry getExtensionRegistry() { return ExtensionRegistry.newInstance(); }
+ @Override
+ Message getDefaultInstance() {
+ return com.google.protobuf.benchmarks.BenchmarkMessage2.GoogleMessage2.getDefaultInstance();
+ }
+ },
+ GOOGLE_MESSAGE3 {
+ @Override
+ ExtensionRegistry getExtensionRegistry() {
+ ExtensionRegistry extensions = ExtensionRegistry.newInstance();
+ com.google.protobuf.benchmarks.BenchmarkMessage38.registerAllExtensions(extensions);
+ com.google.protobuf.benchmarks.BenchmarkMessage37.registerAllExtensions(extensions);
+ com.google.protobuf.benchmarks.BenchmarkMessage36.registerAllExtensions(extensions);
+ com.google.protobuf.benchmarks.BenchmarkMessage35.registerAllExtensions(extensions);
+ com.google.protobuf.benchmarks.BenchmarkMessage34.registerAllExtensions(extensions);
+ com.google.protobuf.benchmarks.BenchmarkMessage33.registerAllExtensions(extensions);
+ com.google.protobuf.benchmarks.BenchmarkMessage32.registerAllExtensions(extensions);
+ com.google.protobuf.benchmarks.BenchmarkMessage31.registerAllExtensions(extensions);
+ com.google.protobuf.benchmarks.BenchmarkMessage3.registerAllExtensions(extensions);
+ return extensions;
+ }
+ @Override
+ Message getDefaultInstance() {
+ return com.google.protobuf.benchmarks.BenchmarkMessage3.GoogleMessage3.getDefaultInstance();
+ }
+ },
+ GOOGLE_MESSAGE4 {
+ @Override
+ ExtensionRegistry getExtensionRegistry() {
+ ExtensionRegistry extensions = ExtensionRegistry.newInstance();
+ com.google.protobuf.benchmarks.BenchmarkMessage43.registerAllExtensions(extensions);
+ com.google.protobuf.benchmarks.BenchmarkMessage42.registerAllExtensions(extensions);
+ com.google.protobuf.benchmarks.BenchmarkMessage41.registerAllExtensions(extensions);
+ com.google.protobuf.benchmarks.BenchmarkMessage4.registerAllExtensions(extensions);
+ return extensions;
+ }
+ @Override
+ Message getDefaultInstance() {
+ return com.google.protobuf.benchmarks.BenchmarkMessage4.GoogleMessage4.getDefaultInstance();
+ }
+ };
+
+ abstract ExtensionRegistry getExtensionRegistry();
+ abstract Message getDefaultInstance();
+ }
+
+ private BenchmarkMessageType benchmarkMessageType;
+ @Param("")
+ private String dataFile;
+
+ private byte[] inputData;
+ private BenchmarkDataset benchmarkDataset;
+ private Message defaultMessage;
+ private ExtensionRegistry extensions;
+ private List<byte[]> inputDataList;
+ private List<ByteArrayInputStream> inputStreamList;
+ private List<ByteString> inputStringList;
+ private List<Message> sampleMessageList;
+
+ private BenchmarkMessageType getMessageType() throws IOException {
+ if (benchmarkDataset.getMessageName().equals("benchmarks.proto3.GoogleMessage1")) {
+ return BenchmarkMessageType.GOOGLE_MESSAGE1_PROTO3;
+ } else if (benchmarkDataset.getMessageName().equals("benchmarks.proto2.GoogleMessage1")) {
+ return BenchmarkMessageType.GOOGLE_MESSAGE1_PROTO2;
+ } else if (benchmarkDataset.getMessageName().equals("benchmarks.proto2.GoogleMessage2")) {
+ return BenchmarkMessageType.GOOGLE_MESSAGE2;
+ } else if (benchmarkDataset.getMessageName().
+ equals("benchmarks.google_message3.GoogleMessage3")) {
+ return BenchmarkMessageType.GOOGLE_MESSAGE3;
+ } else if (benchmarkDataset.getMessageName().
+ equals("benchmarks.google_message4.GoogleMessage4")) {
+ return BenchmarkMessageType.GOOGLE_MESSAGE4;
+ } else {
+ throw new IllegalStateException("Invalid DataFile! There's no testing message named "
+ + benchmarkDataset.getMessageName());
+ }
+ }
+
+ @BeforeExperiment
+ void setUp() throws IOException {
+ if (!dataFile.equals("")) {
+ RandomAccessFile file = new RandomAccessFile(new File(dataFile), "r");
+ inputData = new byte[(int) file.length()];
+ file.readFully(inputData);
+ benchmarkDataset = BenchmarkDataset.parseFrom(inputData);
+ benchmarkMessageType = getMessageType();
+ } else {
+ inputData = new byte[0];
+ benchmarkDataset = BenchmarkDataset.parseFrom(inputData);
+ benchmarkMessageType = BenchmarkMessageType.GOOGLE_MESSAGE2;
+ }
+ defaultMessage = benchmarkMessageType.getDefaultInstance();
+ extensions = benchmarkMessageType.getExtensionRegistry();
+ inputDataList = new ArrayList<byte[]>();
+ inputStreamList = new ArrayList<ByteArrayInputStream>();
+ inputStringList = new ArrayList<ByteString>();
+ sampleMessageList = new ArrayList<Message>();
+
+ for (int i = 0; i < benchmarkDataset.getPayloadCount(); i++) {
+ byte[] singleInputData = benchmarkDataset.getPayload(i).toByteArray();
+ inputDataList.add(benchmarkDataset.getPayload(i).toByteArray());
+ inputStreamList.add(new ByteArrayInputStream(
+ benchmarkDataset.getPayload(i).toByteArray()));
+ inputStringList.add(benchmarkDataset.getPayload(i));
+ sampleMessageList.add(
+ defaultMessage.newBuilderForType().mergeFrom(singleInputData, extensions).build());
+ }
+ }
+
+
+ @Benchmark
+ void serializeToByteString(int reps) throws IOException {
+ if (sampleMessageList.size() == 0) {
+ return;
+ }
+ for (int i = 0; i < reps; i++) {
+ for (int j = 0; j < sampleMessageList.size(); j++) {
+ sampleMessageList.get(j).toByteString();
+ }
+ }
+ }
+
+ @Benchmark
+ void serializeToByteArray(int reps) throws IOException {
+ if (sampleMessageList.size() == 0) {
+ return;
+ }
+ for (int i = 0; i < reps; i++) {
+ for (int j = 0; j < sampleMessageList.size(); j++) {
+ sampleMessageList.get(j).toByteArray();
+ }
+ }
+ }
+
+ @Benchmark
+ void serializeToMemoryStream(int reps) throws IOException {
+ if (sampleMessageList.size() == 0) {
+ return;
+ }
+ for (int i = 0; i < reps; i++) {
+ for (int j = 0; j < sampleMessageList.size(); j++) {
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ sampleMessageList.get(j).writeTo(output);
+ }
+ }
+ }
+
+ @Benchmark
+ void deserializeFromByteString(int reps) throws IOException {
+ if (inputStringList.size() == 0) {
+ return;
+ }
+ for (int i = 0; i < reps; i++) {
+ for (int j = 0; j < inputStringList.size(); j++) {
+ benchmarkMessageType.getDefaultInstance().getParserForType().parseFrom(
+ inputStringList.get(j), extensions);
+ }
+ }
+ }
+
+ @Benchmark
+ void deserializeFromByteArray(int reps) throws IOException {
+ if (inputDataList.size() == 0) {
+ return;
+ }
+ for (int i = 0; i < reps; i++) {
+ for (int j = 0; j < inputDataList.size(); j++) {
+ benchmarkMessageType.getDefaultInstance().getParserForType().parseFrom(
+ inputDataList.get(j), extensions);
+ }
+ }
+ }
+
+ @Benchmark
+ void deserializeFromMemoryStream(int reps) throws IOException {
+ if (inputStreamList.size() == 0) {
+ return;
+ }
+ for (int i = 0; i < reps; i++) {
+ 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/python/py_benchmark.py b/benchmarks/python/py_benchmark.py
new file mode 100755
index 00000000..6942d208
--- /dev/null
+++ b/benchmarks/python/py_benchmark.py
@@ -0,0 +1,152 @@
+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 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" )
+# END CPP GENERATED MESSAGE
+
+
+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
+import benchmarks_pb2 as benchmarks_pb2
+
+
+def run_one_test(filename):
+ 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")
+ result={}
+ result["filename"] = filename
+ result["message_name"] = benchmark_dataset.message_name
+ result["benchmarks"] = {}
+ benchmark_util.set_test_method("parse_from_benchmark")
+ 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")
+ 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
+ message_list=[]
+ counter = 0
+ data = open(os.path.dirname(sys.argv[0]) + "/../" + filename).read()
+ benchmark_dataset = benchmarks_pb2.BenchmarkDataset()
+ benchmark_dataset.ParseFromString(data)
+
+ if benchmark_dataset.message_name == "benchmarks.proto3.GoogleMessage1":
+ message_class = benchmark_message1_proto3_pb2.GoogleMessage1
+ elif benchmark_dataset.message_name == "benchmarks.proto2.GoogleMessage1":
+ message_class = benchmark_message1_proto2_pb2.GoogleMessage1
+ elif benchmark_dataset.message_name == "benchmarks.proto2.GoogleMessage2":
+ message_class = benchmark_message2_pb2.GoogleMessage2
+ elif benchmark_dataset.message_name == "benchmarks.google_message3.GoogleMessage3":
+ message_class = benchmark_message3_pb2.GoogleMessage3
+ elif benchmark_dataset.message_name == "benchmarks.google_message4.GoogleMessage4":
+ message_class = benchmark_message4_pb2.GoogleMessage4
+ else:
+ raise IOError("Message %s not found!" % (benchmark_dataset.message_name))
+
+ for one_payload in benchmark_dataset.payload:
+ temp = message_class()
+ 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()
+ counter = counter + 1
+
+
+class Benchmark:
+ def __init__(self, module=None, test_method=None,
+ setup_method=None, full_iteration = 1):
+ self.full_iteration = full_iteration
+ self.module = module
+ self.test_method = test_method
+ self.setup_method = setup_method
+
+ def set_test_method(self, test_method):
+ self.test_method = test_method
+
+ def full_setup_code(self, setup_method_args=''):
+ setup_code = ""
+ setup_code += "from %s import %s\n" % (self.module, self.test_method)
+ setup_code += "from %s import %s\n" % (self.module, self.setup_method)
+ setup_code += "%s(%s)\n" % (self.setup_method, setup_method_args)
+ return setup_code
+
+ def dry_run(self, test_method_args='', setup_method_args=''):
+ return timeit.timeit(stmt="%s(%s)" % (self.test_method, test_method_args),
+ setup=self.full_setup_code(setup_method_args),
+ number=self.full_iteration);
+
+ def run_benchmark(self, test_method_args='', setup_method_args=''):
+ reps = self.full_iteration;
+ t = self.dry_run(test_method_args, setup_method_args);
+ if t < 3 :
+ reps = int(math.ceil(3 / t)) * self.full_iteration
+ t = timeit.timeit(stmt="%s(%s)" % (self.test_method, test_method_args),
+ setup=self.full_setup_code(setup_method_args),
+ number=reps);
+ return 1.0 * t / reps * (10 ** 9)
+
+
+if __name__ == "__main__":
+ 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/python_benchmark_messages.cc b/benchmarks/python/python_benchmark_messages.cc
new file mode 100644
index 00000000..ded16fe9
--- /dev/null
+++ b/benchmarks/python/python_benchmark_messages.cc
@@ -0,0 +1,29 @@
+#include <Python.h>
+
+#include "benchmarks.pb.h"
+#include "datasets/google_message1/proto2/benchmark_message1_proto2.pb.h"
+#include "datasets/google_message1/proto3/benchmark_message1_proto3.pb.h"
+#include "datasets/google_message2/benchmark_message2.pb.h"
+#include "datasets/google_message3/benchmark_message3.pb.h"
+#include "datasets/google_message4/benchmark_message4.pb.h"
+
+static PyMethodDef python_benchmark_methods[] = {
+ {NULL, NULL, 0, NULL} /* Sentinel */
+};
+
+
+PyMODINIT_FUNC
+initlibbenchmark_messages() {
+ benchmarks::BenchmarkDataset().descriptor();
+ benchmarks::proto3::GoogleMessage1().descriptor();
+ benchmarks::proto2::GoogleMessage1().descriptor();
+ benchmarks::proto2::GoogleMessage2().descriptor();
+ benchmarks::google_message3::GoogleMessage3().descriptor();
+ benchmarks::google_message4::GoogleMessage4().descriptor();
+
+ PyObject *m;
+
+ m = Py_InitModule("libbenchmark_messages", python_benchmark_methods);
+ if (m == NULL)
+ return;
+}
diff --git a/benchmarks/readme.txt b/benchmarks/readme.txt
deleted file mode 100644
index b08b8bc0..00000000
--- a/benchmarks/readme.txt
+++ /dev/null
@@ -1,46 +0,0 @@
-Contents
---------
-
-This folder contains three kinds of file:
-
-- Code, such as ProtoBench.java, to build the benchmarking framework.
-- Protocol buffer definitions (.proto files)
-- Sample data files
-
-If we end up with a lot of different benchmarks it may be worth
-separating these out info different directories, but while there are
-so few they might as well all be together.
-
-Running a benchmark (Java)
---------------------------
-
-1) Build protoc and the Java protocol buffer library. The examples
- below assume a jar file (protobuf.jar) has been built and copied
- into this directory.
-
-2) Build ProtoBench:
- $ javac -d tmp -cp protobuf.jar ProtoBench.java
-
-3) Generate code for the relevant benchmark protocol buffer, e.g.
- $ protoc --java_out=tmp google_size.proto
-
-4) Build the generated code, e.g.
- $ javac -d tmp -cp protobuf.jar tmp/benchmarks/*.java
-
-5) Run the test. Arguments are given in pairs - the first argument
- is the descriptor type; the second is the filename. For example:
- $ java -cp tmp:protobuf.jar com.google.protocolbuffers.ProtoBench \
- 'benchmarks.GoogleSize$SizeMessage1' google_message1.dat \
- 'benchmarks.GoogleSize$SizeMessage2' google_message2.dat
-
-6) Wait! Each test runs for around 30 seconds, and there are 8 tests
- per class/data combination. The above command would therefore take
- about 8 minutes to run.
-
-
-Benchmarks available
---------------------
-
-From Google:
-google_size.proto,
-messages google_message1.dat and google_message2.dat.
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..14105aa6
--- /dev/null
+++ b/benchmarks/util/big_query_utils.py
@@ -0,0 +1,188 @@
+#!/usr/bin/env python2.7
+
+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/gogo_data_scrubber.cc b/benchmarks/util/gogo_data_scrubber.cc
new file mode 100644
index 00000000..fb9af6e2
--- /dev/null
+++ b/benchmarks/util/gogo_data_scrubber.cc
@@ -0,0 +1,105 @@
+#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 "google/protobuf/message.h"
+#include "google/protobuf/descriptor.h"
+
+#include <fstream>
+
+using google::protobuf::FieldDescriptor;
+using google::protobuf::Message;
+using google::protobuf::Reflection;
+
+
+class DataGroupStripper {
+ public:
+ static void StripMessage(Message *message) {
+ std::vector<const FieldDescriptor*> set_fields;
+ const Reflection* reflection = message->GetReflection();
+ reflection->ListFields(*message, &set_fields);
+
+ for (size_t i = 0; i < set_fields.size(); i++) {
+ const FieldDescriptor* field = set_fields[i];
+ if (field->type() == FieldDescriptor::TYPE_GROUP) {
+ reflection->ClearField(message, field);
+ }
+ if (field->type() == FieldDescriptor::TYPE_MESSAGE) {
+ if (field->is_repeated()) {
+ for (int j = 0; j < reflection->FieldSize(*message, field); j++) {
+ StripMessage(reflection->MutableRepeatedMessage(message, field, j));
+ }
+ } else {
+ StripMessage(reflection->MutableMessage(message, field));
+ }
+ }
+ }
+
+ reflection->MutableUnknownFields(message)->Clear();
+ }
+};
+
+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));
+ DataGroupStripper::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..bfa6a5e5
--- /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::SchemaAddZeroEnumValue;
+
+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);
+
+ SchemaAddZeroEnumValue 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/run_and_upload.py b/benchmarks/util/run_and_upload.py
new file mode 100755
index 00000000..ae22a668
--- /dev/null
+++ b/benchmarks/util/run_and_upload.py
@@ -0,0 +1,290 @@
+import argparse
+import os
+import re
+import copy
+import uuid
+import calendar
+import time
+import big_query_utils
+import datetime
+import json
+# This import depends on the automake rule protoc_middleman, please make sure
+# protoc_middleman has been built before run this file.
+import os.path, sys
+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..089012dd
--- /dev/null
+++ b/benchmarks/util/schema_proto2_to_proto3_util.h
@@ -0,0 +1,137 @@
+#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 SchemaAddZeroEnumValue {
+
+ public:
+ SchemaAddZeroEnumValue()
+ : 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_;
+};
+
+} // 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 f159f60e..ada9dc25 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...")
@@ -8,12 +8,26 @@ endif()
# CMake policies
cmake_policy(SET CMP0022 NEW)
+if(POLICY CMP0048)
+ cmake_policy(SET CMP0048 NEW)
+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)
+option(protobuf_BUILD_PROTOC_BINARIES "Build libprotoc and protoc compiler" ON)
if (BUILD_SHARED_LIBS)
set(protobuf_BUILD_SHARED_LIBS_DEFAULT ON)
else (BUILD_SHARED_LIBS)
@@ -23,11 +37,7 @@ option(protobuf_BUILD_SHARED_LIBS "Build Shared Libraries" ${protobuf_BUILD_SHAR
include(CMakeDependentOption)
cmake_dependent_option(protobuf_MSVC_STATIC_RUNTIME "Link static runtime libraries" ON
"NOT protobuf_BUILD_SHARED_LIBS" OFF)
-if (MSVC)
- set(protobuf_WITH_ZLIB_DEFAULT OFF)
-else (MSVC)
- set(protobuf_WITH_ZLIB_DEFAULT ON)
-endif (MSVC)
+set(protobuf_WITH_ZLIB_DEFAULT ON)
option(protobuf_WITH_ZLIB "Build with zlib support" ${protobuf_WITH_ZLIB_DEFAULT})
set(protobuf_DEBUG_POSTFIX "d"
CACHE STRING "Default debug postfix")
@@ -156,12 +166,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(
@@ -184,8 +205,10 @@ endif (protobuf_UNICODE)
include(libprotobuf-lite.cmake)
include(libprotobuf.cmake)
-include(libprotoc.cmake)
-include(protoc.cmake)
+if (protobuf_BUILD_PROTOC_BINARIES)
+ include(libprotoc.cmake)
+ include(protoc.cmake)
+endif (protobuf_BUILD_PROTOC_BINARIES)
if (protobuf_BUILD_TESTS)
include(tests.cmake)
diff --git a/cmake/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 5212d00a..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
@@ -53,6 +51,8 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_message_ref
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_message_table_driven.h" include\google\protobuf\generated_message_table_driven.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_message_util.h" include\google\protobuf\generated_message_util.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\has_bits.h" include\google\protobuf\has_bits.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\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
@@ -78,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
@@ -104,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
@@ -128,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 441bf553..82036cb6 100644
--- a/cmake/install.cmake
+++ b/cmake/install.cmake
@@ -5,10 +5,12 @@ configure_file(${CMAKE_CURRENT_SOURCE_DIR}/protobuf.pc.cmake
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/protobuf-lite.pc.cmake
${CMAKE_CURRENT_BINARY_DIR}/protobuf-lite.pc @ONLY)
-foreach(_library
- libprotobuf-lite
- libprotobuf
- libprotoc)
+set(_protobuf_libraries libprotobuf-lite libprotobuf)
+if (protobuf_BUILD_PROTOC_BINARIES)
+ list(APPEND _protobuf_libraries libprotoc)
+endif (protobuf_BUILD_PROTOC_BINARIES)
+
+foreach(_library ${_protobuf_libraries})
set_property(TARGET ${_library}
PROPERTY INTERFACE_INCLUDE_DIRECTORIES
$<BUILD_INTERFACE:${protobuf_source_dir}/src>
@@ -19,8 +21,10 @@ foreach(_library
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT ${_library})
endforeach()
-install(TARGETS protoc EXPORT protobuf-targets
- RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT protoc)
+if (protobuf_BUILD_PROTOC_BINARIES)
+ install(TARGETS protoc EXPORT protobuf-targets
+ RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT protoc)
+endif (protobuf_BUILD_PROTOC_BINARIES)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/protobuf.pc ${CMAKE_CURRENT_BINARY_DIR}/protobuf-lite.pc DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
@@ -101,10 +105,18 @@ configure_file(protobuf-options.cmake
${CMAKE_INSTALL_CMAKEDIR}/protobuf-options.cmake @ONLY)
# Allows the build directory to be used as a find directory.
-export(TARGETS libprotobuf-lite libprotobuf libprotoc protoc
- NAMESPACE protobuf::
- FILE ${CMAKE_INSTALL_CMAKEDIR}/protobuf-targets.cmake
-)
+
+if (protobuf_BUILD_PROTOC_BINARIES)
+ export(TARGETS libprotobuf-lite libprotobuf libprotoc protoc
+ NAMESPACE protobuf::
+ FILE ${CMAKE_INSTALL_CMAKEDIR}/protobuf-targets.cmake
+ )
+else (protobuf_BUILD_PROTOC_BINARIES)
+ export(TARGETS libprotobuf-lite libprotobuf
+ NAMESPACE protobuf::
+ FILE ${CMAKE_INSTALL_CMAKEDIR}/protobuf-targets.cmake
+ )
+endif (protobuf_BUILD_PROTOC_BINARIES)
install(EXPORT protobuf-targets
DESTINATION "${CMAKE_INSTALL_CMAKEDIR}"
diff --git a/cmake/libprotobuf-lite.cmake b/cmake/libprotobuf-lite.cmake
index 9e1fab0a..1d0b0b84 100644
--- a/cmake/libprotobuf-lite.cmake
+++ b/cmake/libprotobuf-lite.cmake
@@ -4,18 +4,16 @@ set(libprotobuf_lite_files
${protobuf_source_dir}/src/google/protobuf/extension_set.cc
${protobuf_source_dir}/src/google/protobuf/generated_message_table_driven_lite.cc
${protobuf_source_dir}/src/google/protobuf/generated_message_util.cc
+ ${protobuf_source_dir}/src/google/protobuf/implicit_weak_message.cc
${protobuf_source_dir}/src/google/protobuf/io/coded_stream.cc
${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream.cc
${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
@@ -31,12 +29,12 @@ set(libprotobuf_lite_includes
${protobuf_source_dir}/src/google/protobuf/arenastring.h
${protobuf_source_dir}/src/google/protobuf/extension_set.h
${protobuf_source_dir}/src/google/protobuf/generated_message_util.h
+ ${protobuf_source_dir}/src/google/protobuf/implicit_weak_message.h
${protobuf_source_dir}/src/google/protobuf/io/coded_stream.h
${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream.h
${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_impl_lite.h
${protobuf_source_dir}/src/google/protobuf/message_lite.h
${protobuf_source_dir}/src/google/protobuf/repeated_field.h
- ${protobuf_source_dir}/src/google/protobuf/stubs/atomicops_internals_x86_msvc.h
${protobuf_source_dir}/src/google/protobuf/stubs/bytestream.h
${protobuf_source_dir}/src/google/protobuf/stubs/common.h
${protobuf_source_dir}/src/google/protobuf/stubs/int128.h
@@ -50,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)
@@ -60,5 +64,7 @@ if(MSVC AND protobuf_BUILD_SHARED_LIBS)
PRIVATE LIBPROTOBUF_EXPORTS)
endif()
set_target_properties(libprotobuf-lite PROPERTIES
+ VERSION ${protobuf_VERSION}
OUTPUT_NAME ${LIB_PREFIX}protobuf-lite
DEBUG_POSTFIX "${protobuf_DEBUG_POSTFIX}")
+add_library(protobuf::libprotobuf-lite ALIAS libprotobuf-lite)
diff --git a/cmake/libprotobuf.cmake b/cmake/libprotobuf.cmake
index 72db915b..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})
@@ -125,5 +131,7 @@ if(MSVC AND protobuf_BUILD_SHARED_LIBS)
PRIVATE LIBPROTOBUF_EXPORTS)
endif()
set_target_properties(libprotobuf PROPERTIES
+ VERSION ${protobuf_VERSION}
OUTPUT_NAME ${LIB_PREFIX}protobuf
DEBUG_POSTFIX "${protobuf_DEBUG_POSTFIX}")
+add_library(protobuf::libprotobuf ALIAS libprotobuf)
diff --git a/cmake/libprotoc.cmake b/cmake/libprotoc.cmake
index 107c1c52..04701818 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,38 +146,27 @@ 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
)
+if (MSVC)
+set(libprotoc_rc_files
+ ${CMAKE_CURRENT_BINARY_DIR}/version.rc
+)
+endif()
+
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
@@ -216,7 +180,7 @@ add_custom_command(
)
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
@@ -225,5 +189,7 @@ if(MSVC AND protobuf_BUILD_SHARED_LIBS)
endif()
set_target_properties(libprotoc PROPERTIES
COMPILE_DEFINITIONS LIBPROTOC_EXPORTS
+ VERSION ${protobuf_VERSION}
OUTPUT_NAME ${LIB_PREFIX}protoc
DEBUG_POSTFIX "${protobuf_DEBUG_POSTFIX}")
+add_library(protobuf::libprotoc ALIAS libprotoc)
diff --git a/cmake/protobuf-config.cmake.in b/cmake/protobuf-config.cmake.in
index fd67edc3..3480c17c 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()
@@ -91,16 +95,16 @@ function(protobuf_generate)
get_filename_component(_basename ${_proto} NAME_WE)
set(_generated_srcs)
- foreach(_ext ${protobuf_GENERATE_EXTENSIONS})
- list(APPEND _generated_srcs "${CMAKE_CURRENT_BINARY_DIR}/${_basename}${_ext}")
+ foreach(_ext ${protobuf_generate_GENERATE_EXTENSIONS})
+ list(APPEND _generated_srcs "${protobuf_generate_PROTOC_OUT_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()
@@ -110,7 +114,7 @@ function(protobuf_generate)
set(${protobuf_generate_OUT_VAR} ${_generated_srcs_all} PARENT_SCOPE)
endif()
if(protobuf_generate_TARGET)
- target_sources(${protobuf_generate_TARGET} PUBLIC ${_generated_srcs_all})
+ target_sources(${protobuf_generate_TARGET} PRIVATE ${_generated_srcs_all})
endif()
endfunction()
diff --git a/cmake/protoc.cmake b/cmake/protoc.cmake
index 4f07c389..bb160f47 100644
--- a/cmake/protoc.cmake
+++ b/cmake/protoc.cmake
@@ -2,5 +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 839aa04d..7a5e3ab2 100644
--- a/configure.ac
+++ b/configure.ac
@@ -52,6 +52,16 @@ AC_ARG_WITH([zlib],
[include classes for streaming compressed data in and out @<:@default=check@:>@])],
[],[with_zlib=check])
+AC_ARG_WITH([zlib-include],
+ [AS_HELP_STRING([--with-zlib-include=PATH],
+ [zlib include directory])],
+ [CPPFLAGS="-I$withval $CPPFLAGS"])
+
+AC_ARG_WITH([zlib-lib],
+ [AS_HELP_STRING([--with-zlib-lib=PATH],
+ [zlib lib directory])],
+ [LDFLAGS="-L$withval $LDFLAGS"])
+
AC_ARG_WITH([protoc],
[AS_HELP_STRING([--with-protoc=COMMAND],
[use the given protoc command instead of building a new one when building tests (useful for cross-compiling)])],
@@ -174,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*)
+ mingw* | cygwin* | win* | aix* | *android* )
;;
*)
# Need to link against rt on Solaris
@@ -205,7 +214,7 @@ AX_CXX_COMPILE_STDCXX([11], [noext], [optional])
# 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 98c2eae4..22bbbfb3 100644
--- a/conformance/conformance_test.cc
+++ b/conformance/conformance_test.cc
@@ -754,7 +754,7 @@ void ConformanceTestSuite::TestValidDataForType(
}
void ConformanceTestSuite::SetFailureList(const string& filename,
- const vector<string>& failure_list) {
+ const std::vector<string>& failure_list) {
failure_list_filename_ = filename;
expected_to_fail_.clear();
std::copy(failure_list.begin(), failure_list.end(),
@@ -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 7e91d388..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';
@@ -264,7 +263,7 @@ void UsageError() {
exit(1);
}
-void ParseFailureList(const char *filename, vector<string>* failure_list) {
+void ParseFailureList(const char *filename, std::vector<string>* failure_list) {
std::ifstream infile(filename);
if (!infile.is_open()) {
@@ -291,7 +290,7 @@ int main(int argc, char *argv[]) {
google::protobuf::ConformanceTestSuite suite;
string failure_list_filename;
- vector<string> failure_list;
+ std::vector<string> failure_list;
for (int arg = 1; arg < argc; ++arg) {
if (strcmp(argv[arg], "--failure_list") == 0) {
diff --git a/conformance/failure_list_cpp.txt b/conformance/failure_list_cpp.txt
index 8c328890..752fbb5d 100644
--- a/conformance/failure_list_cpp.txt
+++ b/conformance/failure_list_cpp.txt
@@ -54,4 +54,3 @@ Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT32
Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT64
Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT32
Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT64
-
diff --git a/conformance/failure_list_java.txt b/conformance/failure_list_java.txt
index 5116c569..dc1f9ba5 100644
--- a/conformance/failure_list_java.txt
+++ b/conformance/failure_list_java.txt
@@ -44,4 +44,4 @@ Required.Proto3.JsonInput.StringFieldNotAString
Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
-Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE \ No newline at end of file
+Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
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/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/global.json b/csharp/global.json
index 3622b564..5ab775b9 100644
--- a/csharp/global.json
+++ b/csharp/global.json
@@ -1,5 +1,5 @@
{
"sdk": {
- "version": "1.0.0"
+ "version": "2.0.3"
}
}
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/CodedInputStreamTest.cs b/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs
index e7c6b805..8795fa65 100644..100755
--- 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/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.Test/UnknownFieldSetTest.cs b/csharp/src/Google.Protobuf.Test/UnknownFieldSetTest.cs
index 1edd6fba..ddf62321 100644
--- a/csharp/src/Google.Protobuf.Test/UnknownFieldSetTest.cs
+++ b/csharp/src/Google.Protobuf.Test/UnknownFieldSetTest.cs
@@ -31,6 +31,7 @@
#endregion
using System;
+using System.IO;
using Google.Protobuf.TestProtos;
using NUnit.Framework;
@@ -124,5 +125,52 @@ namespace Google.Protobuf
Assert.AreEqual(message.CalculateSize(), otherEmptyMessage.CalculateSize());
Assert.AreEqual(message.ToByteArray(), otherEmptyMessage.ToByteArray());
}
+
+ [Test]
+ public void TestDiscardUnknownFields()
+ {
+ var message = SampleMessages.CreateFullTestAllTypes();
+ var goldenEmptyMessage = new TestEmptyMessage();
+ byte[] data = message.ToByteArray();
+ int fullSize = message.CalculateSize();
+
+ Action<IMessage> assertEmpty = msg =>
+ {
+ Assert.AreEqual(0, msg.CalculateSize());
+ Assert.AreEqual(goldenEmptyMessage, msg);
+ };
+
+ Action<IMessage> assertFull = msg => Assert.AreEqual(fullSize, msg.CalculateSize());
+
+ // Test the behavior of the parsers with and without discarding, both generic and non-generic.
+ MessageParser<TestEmptyMessage> retainingParser1 = TestEmptyMessage.Parser;
+ MessageParser retainingParser2 = retainingParser1;
+ MessageParser<TestEmptyMessage> discardingParser1 = retainingParser1.WithDiscardUnknownFields(true);
+ MessageParser discardingParser2 = retainingParser2.WithDiscardUnknownFields(true);
+
+ // Test parse from byte[]
+ assertFull(retainingParser1.ParseFrom(data));
+ assertFull(retainingParser2.ParseFrom(data));
+ assertEmpty(discardingParser1.ParseFrom(data));
+ assertEmpty(discardingParser2.ParseFrom(data));
+
+ // Test parse from byte[] with offset
+ assertFull(retainingParser1.ParseFrom(data, 0, data.Length));
+ assertFull(retainingParser2.ParseFrom(data, 0, data.Length));
+ assertEmpty(discardingParser1.ParseFrom(data, 0, data.Length));
+ assertEmpty(discardingParser2.ParseFrom(data, 0, data.Length));
+
+ // Test parse from CodedInputStream
+ assertFull(retainingParser1.ParseFrom(new CodedInputStream(data)));
+ assertFull(retainingParser2.ParseFrom(new CodedInputStream(data)));
+ assertEmpty(discardingParser1.ParseFrom(new CodedInputStream(data)));
+ assertEmpty(discardingParser2.ParseFrom(new CodedInputStream(data)));
+
+ // Test parse from Stream
+ assertFull(retainingParser1.ParseFrom(new MemoryStream(data)));
+ assertFull(retainingParser2.ParseFrom(new MemoryStream(data)));
+ assertEmpty(discardingParser1.ParseFrom(new MemoryStream(data)));
+ assertEmpty(discardingParser2.ParseFrom(new MemoryStream(data)));
+ }
}
}
diff --git a/csharp/src/Google.Protobuf/CodedInputStream.cs b/csharp/src/Google.Protobuf/CodedInputStream.cs
index 24d436c0..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.
@@ -268,6 +268,11 @@ namespace Google.Protobuf
public int RecursionLimit { get { return recursionLimit; } }
/// <summary>
+ /// Internal-only property; when set to true, unknown fields will be discarded while parsing.
+ /// </summary>
+ internal bool DiscardUnknownFields { get; set; }
+
+ /// <summary>
/// Disposes of this instance, potentially closing any underlying stream.
/// </summary>
/// <remarks>
@@ -1053,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.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/Google.Protobuf.csproj b/csharp/src/Google.Protobuf/Google.Protobuf.csproj
index 6e4e1e2b..93dcd854 100644
--- a/csharp/src/Google.Protobuf/Google.Protobuf.csproj
+++ b/csharp/src/Google.Protobuf/Google.Protobuf.csproj
@@ -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/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/MessageExtensions.cs b/csharp/src/Google.Protobuf/MessageExtensions.cs
index 9dbc49d6..62181eb9 100644
--- a/csharp/src/Google.Protobuf/MessageExtensions.cs
+++ b/csharp/src/Google.Protobuf/MessageExtensions.cs
@@ -44,14 +44,8 @@ namespace Google.Protobuf
/// </summary>
/// <param name="message">The message to merge the data into.</param>
/// <param name="data">The data to merge, which must be protobuf-encoded binary data.</param>
- public static void MergeFrom(this IMessage message, byte[] data)
- {
- ProtoPreconditions.CheckNotNull(message, "message");
- ProtoPreconditions.CheckNotNull(data, "data");
- CodedInputStream input = new CodedInputStream(data);
- message.MergeFrom(input);
- input.CheckReadEndOfStreamTag();
- }
+ public static void MergeFrom(this IMessage message, byte[] data) =>
+ MergeFrom(message, data, false);
/// <summary>
/// Merges data from the given byte array slice into an existing message.
@@ -60,42 +54,24 @@ namespace Google.Protobuf
/// <param name="data">The data containing the slice to merge, which must be protobuf-encoded binary data.</param>
/// <param name="offset">The offset of the slice to merge.</param>
/// <param name="length">The length of the slice to merge.</param>
- public static void MergeFrom(this IMessage message, byte[] data, int offset, int length)
- {
- ProtoPreconditions.CheckNotNull(message, "message");
- ProtoPreconditions.CheckNotNull(data, "data");
- CodedInputStream input = new CodedInputStream(data, offset, length);
- message.MergeFrom(input);
- input.CheckReadEndOfStreamTag();
- }
+ public static void MergeFrom(this IMessage message, byte[] data, int offset, int length) =>
+ MergeFrom(message, data, offset, length, false);
/// <summary>
/// Merges data from the given byte string into an existing message.
/// </summary>
/// <param name="message">The message to merge the data into.</param>
/// <param name="data">The data to merge, which must be protobuf-encoded binary data.</param>
- public static void MergeFrom(this IMessage message, ByteString data)
- {
- ProtoPreconditions.CheckNotNull(message, "message");
- ProtoPreconditions.CheckNotNull(data, "data");
- CodedInputStream input = data.CreateCodedInput();
- message.MergeFrom(input);
- input.CheckReadEndOfStreamTag();
- }
+ public static void MergeFrom(this IMessage message, ByteString data) =>
+ MergeFrom(message, data, false);
/// <summary>
/// Merges data from the given stream into an existing message.
/// </summary>
/// <param name="message">The message to merge the data into.</param>
/// <param name="input">Stream containing the data to merge, which must be protobuf-encoded binary data.</param>
- public static void MergeFrom(this IMessage message, Stream input)
- {
- ProtoPreconditions.CheckNotNull(message, "message");
- ProtoPreconditions.CheckNotNull(input, "input");
- CodedInputStream codedInput = new CodedInputStream(input);
- message.MergeFrom(codedInput);
- codedInput.CheckReadEndOfStreamTag();
- }
+ public static void MergeFrom(this IMessage message, Stream input) =>
+ MergeFrom(message, input, false);
/// <summary>
/// Merges length-delimited data from the given stream into an existing message.
@@ -106,14 +82,8 @@ namespace Google.Protobuf
/// </remarks>
/// <param name="message">The message to merge the data into.</param>
/// <param name="input">Stream containing the data to merge, which must be protobuf-encoded binary data.</param>
- public static void MergeDelimitedFrom(this IMessage message, Stream input)
- {
- ProtoPreconditions.CheckNotNull(message, "message");
- ProtoPreconditions.CheckNotNull(input, "input");
- int size = (int) CodedInputStream.ReadRawVarint32(input);
- Stream limitedStream = new LimitedInputStream(input, size);
- message.MergeFrom(limitedStream);
- }
+ public static void MergeDelimitedFrom(this IMessage message, Stream input) =>
+ MergeDelimitedFrom(message, input, false);
/// <summary>
/// Converts the given message into a byte array in protobuf encoding.
@@ -168,6 +138,56 @@ namespace Google.Protobuf
{
ProtoPreconditions.CheckNotNull(message, "message");
return ByteString.AttachBytes(message.ToByteArray());
- }
+ }
+
+ // Implementations allowing unknown fields to be discarded.
+ internal static void MergeFrom(this IMessage message, byte[] data, bool discardUnknownFields)
+ {
+ ProtoPreconditions.CheckNotNull(message, "message");
+ ProtoPreconditions.CheckNotNull(data, "data");
+ CodedInputStream input = new CodedInputStream(data);
+ input.DiscardUnknownFields = discardUnknownFields;
+ message.MergeFrom(input);
+ input.CheckReadEndOfStreamTag();
+ }
+
+ internal static void MergeFrom(this IMessage message, byte[] data, int offset, int length, bool discardUnknownFields)
+ {
+ ProtoPreconditions.CheckNotNull(message, "message");
+ ProtoPreconditions.CheckNotNull(data, "data");
+ CodedInputStream input = new CodedInputStream(data, offset, length);
+ input.DiscardUnknownFields = discardUnknownFields;
+ message.MergeFrom(input);
+ input.CheckReadEndOfStreamTag();
+ }
+
+ internal static void MergeFrom(this IMessage message, ByteString data, bool discardUnknownFields)
+ {
+ ProtoPreconditions.CheckNotNull(message, "message");
+ ProtoPreconditions.CheckNotNull(data, "data");
+ CodedInputStream input = data.CreateCodedInput();
+ input.DiscardUnknownFields = discardUnknownFields;
+ message.MergeFrom(input);
+ input.CheckReadEndOfStreamTag();
+ }
+
+ internal static void MergeFrom(this IMessage message, Stream input, bool discardUnknownFields)
+ {
+ ProtoPreconditions.CheckNotNull(message, "message");
+ ProtoPreconditions.CheckNotNull(input, "input");
+ CodedInputStream codedInput = new CodedInputStream(input);
+ codedInput.DiscardUnknownFields = discardUnknownFields;
+ message.MergeFrom(codedInput);
+ codedInput.CheckReadEndOfStreamTag();
+ }
+
+ internal static void MergeDelimitedFrom(this IMessage message, Stream input, bool discardUnknownFields)
+ {
+ ProtoPreconditions.CheckNotNull(message, "message");
+ ProtoPreconditions.CheckNotNull(input, "input");
+ int size = (int) CodedInputStream.ReadRawVarint32(input);
+ Stream limitedStream = new LimitedInputStream(input, size);
+ MergeFrom(message, limitedStream, discardUnknownFields);
+ }
}
}
diff --git a/csharp/src/Google.Protobuf/MessageParser.cs b/csharp/src/Google.Protobuf/MessageParser.cs
index 66d44135..4d35554a 100644
--- a/csharp/src/Google.Protobuf/MessageParser.cs
+++ b/csharp/src/Google.Protobuf/MessageParser.cs
@@ -42,10 +42,13 @@ namespace Google.Protobuf
public class MessageParser
{
private Func<IMessage> factory;
+ // TODO: When we use a C# 7.1 compiler, make this private protected.
+ internal bool DiscardUnknownFields { get; }
- internal MessageParser(Func<IMessage> factory)
+ internal MessageParser(Func<IMessage> factory, bool discardUnknownFields)
{
this.factory = factory;
+ DiscardUnknownFields = discardUnknownFields;
}
/// <summary>
@@ -65,7 +68,7 @@ namespace Google.Protobuf
public IMessage ParseFrom(byte[] data)
{
IMessage message = factory();
- message.MergeFrom(data);
+ message.MergeFrom(data, DiscardUnknownFields);
return message;
}
@@ -79,7 +82,7 @@ namespace Google.Protobuf
public IMessage ParseFrom(byte[] data, int offset, int length)
{
IMessage message = factory();
- message.MergeFrom(data, offset, length);
+ message.MergeFrom(data, offset, length, DiscardUnknownFields);
return message;
}
@@ -91,7 +94,7 @@ namespace Google.Protobuf
public IMessage ParseFrom(ByteString data)
{
IMessage message = factory();
- message.MergeFrom(data);
+ message.MergeFrom(data, DiscardUnknownFields);
return message;
}
@@ -103,7 +106,7 @@ namespace Google.Protobuf
public IMessage ParseFrom(Stream input)
{
IMessage message = factory();
- message.MergeFrom(input);
+ message.MergeFrom(input, DiscardUnknownFields);
return message;
}
@@ -119,7 +122,7 @@ namespace Google.Protobuf
public IMessage ParseDelimitedFrom(Stream input)
{
IMessage message = factory();
- message.MergeDelimitedFrom(input);
+ message.MergeDelimitedFrom(input, DiscardUnknownFields);
return message;
}
@@ -131,7 +134,7 @@ namespace Google.Protobuf
public IMessage ParseFrom(CodedInputStream input)
{
IMessage message = factory();
- message.MergeFrom(input);
+ MergeFrom(message, input);
return message;
}
@@ -148,6 +151,29 @@ namespace Google.Protobuf
JsonParser.Default.Merge(message, json);
return message;
}
+
+ // TODO: When we're using a C# 7.1 compiler, make this private protected.
+ internal void MergeFrom(IMessage message, CodedInputStream codedInput)
+ {
+ bool originalDiscard = codedInput.DiscardUnknownFields;
+ try
+ {
+ codedInput.DiscardUnknownFields = DiscardUnknownFields;
+ message.MergeFrom(codedInput);
+ }
+ finally
+ {
+ codedInput.DiscardUnknownFields = originalDiscard;
+ }
+ }
+
+ /// <summary>
+ /// Creates a new message parser which optionally discards unknown fields when parsing.
+ /// </summary>
+ /// <param name="discardUnknownFields">Whether or not to discard unknown fields when parsing.</param>
+ /// <returns>A newly configured message parser.</returns>
+ public MessageParser WithDiscardUnknownFields(bool discardUnknownFields) =>
+ new MessageParser(factory, discardUnknownFields);
}
/// <summary>
@@ -182,7 +208,11 @@ namespace Google.Protobuf
/// to require a parameterless constructor: delegates are significantly faster to execute.
/// </remarks>
/// <param name="factory">Function to invoke when a new, empty message is required.</param>
- public MessageParser(Func<T> factory) : base(() => factory())
+ public MessageParser(Func<T> factory) : this(factory, false)
+ {
+ }
+
+ internal MessageParser(Func<T> factory, bool discardUnknownFields) : base(() => factory(), discardUnknownFields)
{
this.factory = factory;
}
@@ -204,7 +234,7 @@ namespace Google.Protobuf
public new T ParseFrom(byte[] data)
{
T message = factory();
- message.MergeFrom(data);
+ message.MergeFrom(data, DiscardUnknownFields);
return message;
}
@@ -218,7 +248,7 @@ namespace Google.Protobuf
public new T ParseFrom(byte[] data, int offset, int length)
{
T message = factory();
- message.MergeFrom(data, offset, length);
+ message.MergeFrom(data, offset, length, DiscardUnknownFields);
return message;
}
@@ -230,7 +260,7 @@ namespace Google.Protobuf
public new T ParseFrom(ByteString data)
{
T message = factory();
- message.MergeFrom(data);
+ message.MergeFrom(data, DiscardUnknownFields);
return message;
}
@@ -242,7 +272,7 @@ namespace Google.Protobuf
public new T ParseFrom(Stream input)
{
T message = factory();
- message.MergeFrom(input);
+ message.MergeFrom(input, DiscardUnknownFields);
return message;
}
@@ -258,7 +288,7 @@ namespace Google.Protobuf
public new T ParseDelimitedFrom(Stream input)
{
T message = factory();
- message.MergeDelimitedFrom(input);
+ message.MergeDelimitedFrom(input, DiscardUnknownFields);
return message;
}
@@ -270,7 +300,7 @@ namespace Google.Protobuf
public new T ParseFrom(CodedInputStream input)
{
T message = factory();
- message.MergeFrom(input);
+ MergeFrom(message, input);
return message;
}
@@ -287,5 +317,13 @@ namespace Google.Protobuf
JsonParser.Default.Merge(message, json);
return message;
}
+
+ /// <summary>
+ /// Creates a new message parser which optionally discards unknown fields when parsing.
+ /// </summary>
+ /// <param name="discardUnknownFields">Whether or not to discard unknown fields when parsing.</param>
+ /// <returns>A newly configured message parser.</returns>
+ public new MessageParser<T> WithDiscardUnknownFields(bool discardUnknownFields) =>
+ new MessageParser<T>(factory, discardUnknownFields);
}
}
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/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..18a70b80 100644
--- a/csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs
+++ b/csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs
@@ -30,11 +30,14 @@
// 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;
+#if NET35
+using Google.Protobuf.Compatibility;
+#endif
+
namespace Google.Protobuf.Reflection
{
/// <summary>
@@ -47,61 +50,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
+ {
+ 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
{
- 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();
- }
+ 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/UnknownFieldSet.cs b/csharp/src/Google.Protobuf/UnknownFieldSet.cs
index b43f4774..6404c3c0 100644
--- a/csharp/src/Google.Protobuf/UnknownFieldSet.cs
+++ b/csharp/src/Google.Protobuf/UnknownFieldSet.cs
@@ -230,7 +230,8 @@ namespace Google.Protobuf
/// <summary>
/// Create a new UnknownFieldSet if unknownFields is null.
/// Parse a single field from <paramref name="input"/> and merge it
- /// into unknownFields.
+ /// into unknownFields. If <paramref name="input"/> is configured to discard unknown fields,
+ /// <paramref name="unknownFields"/> will be returned as-is and the field will be skipped.
/// </summary>
/// <param name="unknownFields">The UnknownFieldSet which need to be merged</param>
/// <param name="input">The coded input stream containing the field</param>
@@ -238,6 +239,11 @@ namespace Google.Protobuf
public static UnknownFieldSet MergeFieldFrom(UnknownFieldSet unknownFields,
CodedInputStream input)
{
+ if (input.DiscardUnknownFields)
+ {
+ input.SkipLastField();
+ return unknownFields;
+ }
if (unknownFields == null)
{
unknownFields = new UnknownFieldSet();
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs
index 5836dfff..378b61d4 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs
@@ -158,17 +158,18 @@ namespace Google.Protobuf.WellKnownTypes {
public const int TypeUrlFieldNumber = 1;
private string typeUrl_ = "";
/// <summary>
- /// A URL/resource name whose content describes the type of the
- /// serialized protocol buffer message.
+ /// 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).
///
- /// For URLs which use the scheme `http`, `https`, or no scheme, the
- /// following restrictions and interpretations apply:
+ /// 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
@@ -177,6 +178,10 @@ namespace Google.Protobuf.WellKnownTypes {
/// 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.
/// </summary>
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/Timestamp.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs
index bf2943df..ef752be7 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs
@@ -103,7 +103,9 @@ namespace Google.Protobuf.WellKnownTypes {
/// {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.
@@ -114,8 +116,8 @@ namespace Google.Protobuf.WellKnownTypes {
/// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
/// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
/// can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
- /// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--)
- /// 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.
/// </summary>
public sealed partial class Timestamp : pb::IMessage<Timestamp> {
private static readonly pb::MessageParser<Timestamp> _parser = new pb::MessageParser<Timestamp>(() => new Timestamp());
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs
index 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..6a5316c8
--- /dev/null
+++ b/docs/performance.md
@@ -0,0 +1,304 @@
+# Protobuf Perforamcne
+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 b20d4cb1..3f267dde 100644
--- a/docs/third_party.md
+++ b/docs/third_party.md
@@ -45,6 +45,7 @@ These are projects we know about implementing Protocol Buffers for other program
* GopherJS: https://github.com/johanbrandhorst/protobuf
* Haskell: http://hackage.haskell.org/package/hprotoc
* Haskell: https://github.com/google/proto-lens (Google-unofficial implementation)
+* Haskell: https://github.com/awakesecurity/proto3-suite (code generator) https://github.com/awakesecurity/proto3-wire (binary serializer/deserializer)
* Haxe: https://github.com/Atry/protoc-gen-haxe
* Java: https://github.com/google/protobuf (Google-official implementation)
* Java/Android: https://github.com/square/wire
@@ -57,6 +58,7 @@ These are projects we know about implementing Protocol Buffers for other program
* Javascript: http://code.google.com/p/protobuf-for-node/
* Javascript: http://code.google.com/p/protostuff/
* Julia: https://github.com/tanmaykm/ProtoBuf.jl
+* Kotlin: https://github.com/Kotlin/kotlinx.serialization
* Lua: http://code.google.com/p/protoc-gen-lua/
* Lua: http://github.com/indygreg/lua-protobuf
* Lua: https://github.com/Neopallium/lua-pb
@@ -109,7 +111,6 @@ GRPC (http://www.grpc.io/) is Google's RPC implementation for Protocol Buffers.
* http://code.google.com/p/cxf-protobuf/ (Java)
* http://code.google.com/p/protobuf-remote/ (C++/C#)
* http://code.google.com/p/protobuf-rpc-pro/ (Java)
-* https://code.google.com/p/protorpc/ (Go/C++)
* https://code.google.com/p/eneter-protobuf-serializer/ (Java/.NET)
* http://www.deltavsoft.com/RCFProto.html (C++/Java/Python/C#)
* https://github.com/robbinfan/claire-protorpc (C++)
@@ -122,6 +123,8 @@ GRPC (http://www.grpc.io/) is Google's RPC implementation for Protocol Buffers.
* https://github.com/SeriousMa/grpc-protobuf-validation (Java)
* 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++)
## Other Utilities
@@ -159,6 +162,7 @@ There are miscellaneous other things you may find useful as a Protocol Buffers d
* [ProtoBuf with Java EE7 Expression Language 3.0; pure Java ProtoBuf Parser and Builder.](https://github.com/protobufel/protobuf-el)
* [Notepad++ Syntax Highlighting for .proto files](https://github.com/chai2010/notepadplus-protobuf)
* [Linter for .proto files](https://github.com/ckaznocha/protoc-gen-lint)
-* [Protocol Buffers Dynamic Schema - create protobuf schemas programmatically (Java)] (https://github.com/os72/protobuf-dynamic)
+* [Protocol Buffers Dynamic Schema - create protobuf schemas programmatically (Java)](https://github.com/os72/protobuf-dynamic)
* [Make protoc plugins in NodeJS](https://github.com/konsumer/node-protoc-plugin)
* [ProfaneDB - A Protocol Buffers database](https://profanedb.gitlab.io)
+* [Protocol Buffer property-based testing utility and example message generator (Python / Hypothesis)](https://github.com/CurataEng/hypothesis-protobuf)
diff --git a/examples/WORKSPACE b/examples/WORKSPACE
index bb003107..936f2441 100644
--- a/examples/WORKSPACE
+++ b/examples/WORKSPACE
@@ -5,6 +5,8 @@ http_archive(
strip_prefix = "protobuf-master",
urls = ["https://github.com/google/protobuf/archive/master.zip"],
)
+load("@com_google_protobuf//:protobuf.bzl", "check_protobuf_required_bazel_version")
+check_protobuf_required_bazel_version()
# This com_google_protobuf_cc repository is required for cc_proto_library
# rule. It provides protobuf C++ runtime. Note that it actually is the same
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/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/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/javanano/src/test/java/com/google/protobuf/nano/unittest_simple_nano.proto b/java/core/src/main/java/com/google/protobuf/Android.java
index 25786cc2..cad54783 100644
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_simple_nano.proto
+++ b/java/core/src/main/java/com/google/protobuf/Android.java
@@ -28,27 +28,30 @@
// (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 com.google.protobuf;
-package protobuf_unittest_import;
+final class Android {
-option java_package = "com.google.protobuf";
-// Explicit outer classname to suppress legacy info.
-option java_outer_classname = "UnittestSimpleNano";
+ private static final Class<?> MEMORY_CLASS = getClassForName("libcore.io.Memory");
+ private static final boolean IS_ROBOLECTRIC =
+ getClassForName("org.robolectric.Robolectric") != null;
-message SimpleMessageNano {
- message NestedMessage {
- optional int32 bb = 1;
+ /** Returns {@code true} if running on an Android device. */
+ static boolean isOnAndroidDevice() {
+ return MEMORY_CLASS != null && !IS_ROBOLECTRIC;
}
- enum NestedEnum {
- FOO = 1;
- BAR = 2;
- BAZ = 3;
+ /** Returns the memory class or {@code null} if not on Android device. */
+ static Class<?> getMemoryClass() {
+ return MEMORY_CLASS;
}
- optional int32 d = 1 [default = 123];
- optional NestedMessage nested_msg = 2;
- optional NestedEnum default_nested_enum = 3 [default = BAZ];
+ @SuppressWarnings("unchecked")
+ private static <T> Class<T> getClassForName(String name) {
+ try {
+ return (Class<T>) Class.forName(name);
+ } catch (Throwable e) {
+ return null;
+ }
+ }
}
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/ByteString.java b/java/core/src/main/java/com/google/protobuf/ByteString.java
index 99a31209..d67bb54a 100644
--- a/java/core/src/main/java/com/google/protobuf/ByteString.java
+++ b/java/core/src/main/java/com/google/protobuf/ByteString.java
@@ -124,14 +124,8 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
private static final ByteArrayCopier byteArrayCopier;
static {
- boolean isAndroid = true;
- try {
- Class.forName("android.content.Context");
- } catch (ClassNotFoundException e) {
- isAndroid = false;
- }
-
- byteArrayCopier = isAndroid ? new SystemByteArrayCopier() : new ArraysByteArrayCopier();
+ byteArrayCopier =
+ Android.isOnAndroidDevice() ? new SystemByteArrayCopier() : new ArraysByteArrayCopier();
}
/**
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 e08a993b..1297462e 100644
--- a/java/core/src/main/java/com/google/protobuf/CodedInputStream.java
+++ b/java/core/src/main/java/com/google/protobuf/CodedInputStream.java
@@ -64,6 +64,12 @@ public abstract class CodedInputStream {
// Integer.MAX_VALUE == 0x7FFFFFF == INT_MAX from limits.h
private static final int DEFAULT_SIZE_LIMIT = Integer.MAX_VALUE;
+ /**
+ * Whether to enable our custom UTF-8 decode codepath which does not use {@link StringCoding}.
+ * Currently disabled.
+ */
+ private static final boolean ENABLE_CUSTOM_UTF8_DECODE = false;
+
/** Visible for subclasses. See setRecursionLimit() */
int recursionDepth;
@@ -825,13 +831,19 @@ public abstract class CodedInputStream {
public String readStringRequireUtf8() throws IOException {
final int size = readRawVarint32();
if (size > 0 && size <= (limit - pos)) {
- // TODO(martinrb): We could save a pass by validating while decoding.
- if (!Utf8.isValidUtf8(buffer, pos, pos + size)) {
- throw InvalidProtocolBufferException.invalidUtf8();
+ if (ENABLE_CUSTOM_UTF8_DECODE) {
+ String result = Utf8.decodeUtf8(buffer, pos, size);
+ pos += size;
+ return result;
+ } else {
+ // TODO(martinrb): We could save a pass by validating while decoding.
+ if (!Utf8.isValidUtf8(buffer, pos, pos + size)) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ final int tempPos = pos;
+ pos += size;
+ return new String(buffer, tempPos, size, UTF_8);
}
- final int tempPos = pos;
- pos += size;
- return new String(buffer, tempPos, size, UTF_8);
}
if (size == 0) {
@@ -1524,6 +1536,8 @@ public abstract class CodedInputStream {
final int size = readRawVarint32();
if (size > 0 && size <= remaining()) {
// TODO(nathanmittler): Is there a way to avoid this copy?
+ // TODO(anuraaga): It might be possible to share the optimized loop with
+ // readStringRequireUtf8 by implementing Java replacement logic there.
// The same as readBytes' logic
byte[] bytes = new byte[size];
UnsafeUtil.copyMemory(pos, bytes, 0, size);
@@ -1544,19 +1558,26 @@ public abstract class CodedInputStream {
@Override
public String readStringRequireUtf8() throws IOException {
final int size = readRawVarint32();
- if (size >= 0 && size <= remaining()) {
- // TODO(nathanmittler): Is there a way to avoid this copy?
- // The same as readBytes' logic
- byte[] bytes = new byte[size];
- UnsafeUtil.copyMemory(pos, bytes, 0, size);
- // TODO(martinrb): We could save a pass by validating while decoding.
- if (!Utf8.isValidUtf8(bytes)) {
- throw InvalidProtocolBufferException.invalidUtf8();
- }
+ if (size > 0 && size <= remaining()) {
+ if (ENABLE_CUSTOM_UTF8_DECODE) {
+ final int bufferPos = bufferPos(pos);
+ String result = Utf8.decodeUtf8(buffer, bufferPos, size);
+ pos += size;
+ return result;
+ } else {
+ // TODO(nathanmittler): Is there a way to avoid this copy?
+ // The same as readBytes' logic
+ byte[] bytes = new byte[size];
+ UnsafeUtil.copyMemory(pos, bytes, 0, size);
+ // TODO(martinrb): We could save a pass by validating while decoding.
+ if (!Utf8.isValidUtf8(bytes)) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
- String result = new String(bytes, UTF_8);
- pos += size;
- return result;
+ String result = new String(bytes, UTF_8);
+ pos += size;
+ return result;
+ }
}
if (size == 0) {
@@ -2324,11 +2345,15 @@ public abstract class CodedInputStream {
bytes = readRawBytesSlowPath(size);
tempPos = 0;
}
- // TODO(martinrb): We could save a pass by validating while decoding.
- if (!Utf8.isValidUtf8(bytes, tempPos, tempPos + size)) {
- throw InvalidProtocolBufferException.invalidUtf8();
+ if (ENABLE_CUSTOM_UTF8_DECODE) {
+ return Utf8.decodeUtf8(bytes, tempPos, size);
+ } else {
+ // TODO(martinrb): We could save a pass by validating while decoding.
+ if (!Utf8.isValidUtf8(bytes, tempPos, tempPos + size)) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ return new String(bytes, tempPos, size, UTF_8);
}
- return new String(bytes, tempPos, size, UTF_8);
}
@Override
@@ -3348,23 +3373,34 @@ public abstract class CodedInputStream {
public String readStringRequireUtf8() throws IOException {
final int size = readRawVarint32();
if (size > 0 && size <= currentByteBufferLimit - currentByteBufferPos) {
- byte[] bytes = new byte[size];
- UnsafeUtil.copyMemory(currentByteBufferPos, bytes, 0, size);
- if (!Utf8.isValidUtf8(bytes)) {
- throw InvalidProtocolBufferException.invalidUtf8();
+ if (ENABLE_CUSTOM_UTF8_DECODE) {
+ final int bufferPos = (int) (currentByteBufferPos - currentByteBufferStartPos);
+ String result = Utf8.decodeUtf8(currentByteBuffer, bufferPos, size);
+ currentByteBufferPos += size;
+ return result;
+ } else {
+ byte[] bytes = new byte[size];
+ UnsafeUtil.copyMemory(currentByteBufferPos, bytes, 0, size);
+ if (!Utf8.isValidUtf8(bytes)) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ String result = new String(bytes, UTF_8);
+ currentByteBufferPos += size;
+ return result;
}
- String result = new String(bytes, UTF_8);
- currentByteBufferPos += size;
- return result;
}
if (size >= 0 && size <= remaining()) {
byte[] bytes = new byte[size];
readRawBytesTo(bytes, 0, size);
- if (!Utf8.isValidUtf8(bytes)) {
- throw InvalidProtocolBufferException.invalidUtf8();
+ if (ENABLE_CUSTOM_UTF8_DECODE) {
+ return Utf8.decodeUtf8(bytes, 0, size);
+ } else {
+ if (!Utf8.isValidUtf8(bytes)) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ String result = new String(bytes, UTF_8);
+ return result;
}
- String result = new String(bytes, UTF_8);
- return result;
}
if (size == 0) {
diff --git a/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java b/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java
index 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/FieldSet.java b/java/core/src/main/java/com/google/protobuf/FieldSet.java
index 8a9239ed..c09daa32 100644
--- a/java/core/src/main/java/com/google/protobuf/FieldSet.java
+++ b/java/core/src/main/java/com/google/protobuf/FieldSet.java
@@ -102,6 +102,11 @@ final class FieldSet<FieldDescriptorType extends
@SuppressWarnings("rawtypes")
private static final FieldSet DEFAULT_INSTANCE = new FieldSet(true);
+ /** Returns {@code true} if empty, {@code false} otherwise. */
+ boolean isEmpty() {
+ return fields.isEmpty();
+ }
+
/** Make this FieldSet immutable from this point forward. */
@SuppressWarnings("unchecked")
public void makeImmutable() {
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 09084646..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();
@@ -504,11 +546,8 @@ public abstract class GeneratedMessageLite<
extends GeneratedMessageLite<MessageType, BuilderType>
implements ExtendableMessageOrBuilder<MessageType, BuilderType> {
- /**
- * Represents the set of extensions on this message. For use by generated
- * code only.
- */
- protected FieldSet<ExtensionDescriptor> extensions = FieldSet.newFieldSet();
+ /** Represents the set of extensions on this message. For use by generated code only. */
+ protected FieldSet<ExtensionDescriptor> extensions = FieldSet.emptySet();
@SuppressWarnings("unchecked")
protected final void mergeExtensionFields(final MessageType other) {
@@ -578,7 +617,9 @@ public abstract class GeneratedMessageLite<
if (unknown) { // Unknown field or wrong wire type. Skip.
return parseUnknownField(tag, input);
}
-
+
+ ensureExtensionsAreMutable();
+
if (packed) {
int length = input.readRawVarint32();
int limit = input.pushLimit(length);
@@ -793,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(
@@ -868,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
@@ -942,12 +993,6 @@ public abstract class GeneratedMessageLite<
implements ExtendableMessageOrBuilder<MessageType, BuilderType> {
protected ExtendableBuilder(MessageType defaultInstance) {
super(defaultInstance);
-
- // TODO(dweis): This is kind of an unnecessary clone since we construct a
- // new instance in the parent constructor which makes the extensions
- // immutable. This extra allocation shouldn't matter in practice
- // though.
- instance.extensions = instance.extensions.clone();
}
// For immutable message conversion.
@@ -966,6 +1011,15 @@ public abstract class GeneratedMessageLite<
instance.extensions = instance.extensions.clone();
}
+ private FieldSet<ExtensionDescriptor> ensureExtensionsAreMutable() {
+ FieldSet<ExtensionDescriptor> extensions = instance.extensions;
+ if (extensions.isImmutable()) {
+ extensions = extensions.clone();
+ instance.extensions = extensions;
+ }
+ return extensions;
+ }
+
@Override
public final MessageType buildPartial() {
if (isBuilt) {
@@ -1024,7 +1078,8 @@ public abstract class GeneratedMessageLite<
verifyExtensionContainingType(extensionLite);
copyOnWrite();
- instance.extensions.setField(extensionLite.descriptor, extensionLite.toFieldSetType(value));
+ ensureExtensionsAreMutable()
+ .setField(extensionLite.descriptor, extensionLite.toFieldSetType(value));
return (BuilderType) this;
}
@@ -1037,8 +1092,9 @@ public abstract class GeneratedMessageLite<
verifyExtensionContainingType(extensionLite);
copyOnWrite();
- instance.extensions.setRepeatedField(
- extensionLite.descriptor, index, extensionLite.singularToFieldSetType(value));
+ ensureExtensionsAreMutable()
+ .setRepeatedField(
+ extensionLite.descriptor, index, extensionLite.singularToFieldSetType(value));
return (BuilderType) this;
}
@@ -1051,8 +1107,8 @@ public abstract class GeneratedMessageLite<
verifyExtensionContainingType(extensionLite);
copyOnWrite();
- instance.extensions.addRepeatedField(
- extensionLite.descriptor, extensionLite.singularToFieldSetType(value));
+ ensureExtensionsAreMutable()
+ .addRepeatedField(extensionLite.descriptor, extensionLite.singularToFieldSetType(value));
return (BuilderType) this;
}
@@ -1063,7 +1119,7 @@ public abstract class GeneratedMessageLite<
verifyExtensionContainingType(extensionLite);
copyOnWrite();
- instance.extensions.clearField(extensionLite.descriptor);
+ ensureExtensionsAreMutable().clearField(extensionLite.descriptor);
return (BuilderType) this;
}
}
@@ -1462,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);
@@ -1471,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();
}
@@ -1554,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);
+ }
}
/**
@@ -1567,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();
@@ -1578,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)
@@ -1674,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 ab9acf2f..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 + "\".");
}
}
@@ -1224,6 +1224,22 @@ public final class TextFormat {
}
/**
+ * Parse a text-format message from {@code input}.
+ *
+ * @return the parsed message, guaranteed initialized
+ */
+ public static <T extends Message> T parse(final CharSequence input,
+ final Class<T> protoClass)
+ throws ParseException {
+ Message.Builder builder =
+ Internal.getDefaultInstance(protoClass).newBuilderForType();
+ merge(input, builder);
+ @SuppressWarnings("unchecked")
+ T output = (T) builder.build();
+ return output;
+ }
+
+ /**
* Parse a text-format message from {@code input} and merge the contents
* into {@code builder}. Extensions will be recognized if they are
* registered in {@code extensionRegistry}.
@@ -1248,6 +1264,25 @@ public final class TextFormat {
PARSER.merge(input, extensionRegistry, builder);
}
+ /**
+ * Parse a text-format message from {@code input}. Extensions will be
+ * recognized if they are registered in {@code extensionRegistry}.
+ *
+ * @return the parsed message, guaranteed initialized
+ */
+ public static <T extends Message> T parse(
+ final CharSequence input,
+ final ExtensionRegistry extensionRegistry,
+ final Class<T> protoClass)
+ throws ParseException {
+ Message.Builder builder =
+ Internal.getDefaultInstance(protoClass).newBuilderForType();
+ merge(input, extensionRegistry, builder);
+ @SuppressWarnings("unchecked")
+ T output = (T) builder.build();
+ return output;
+ }
+
/**
* Parser for text-format proto2 instances. This class is thread-safe.
@@ -1276,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;
}
@@ -1299,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;
@@ -1320,7 +1360,10 @@ public final class TextFormat {
public Parser build() {
return new Parser(
- allowUnknownFields, singularOverwritePolicy, parseInfoTreeBuilder);
+ allowUnknownFields,
+ allowUnknownEnumValues,
+ singularOverwritePolicy,
+ parseInfoTreeBuilder);
}
}
@@ -1384,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 {
@@ -1702,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 88315cb6..d84ef3c5 100644
--- a/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
+++ b/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
@@ -33,7 +33,6 @@ package com.google.protobuf;
import java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.logging.Level;
@@ -82,6 +81,7 @@ final class UnsafeUtil {
return HAS_UNSAFE_BYTEBUFFER_OPERATIONS;
}
+
static long objectFieldOffset(Field field) {
return MEMORY_ACCESSOR.objectFieldOffset(field);
}
@@ -146,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);
}
@@ -266,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 =
@@ -346,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);
@@ -364,18 +364,16 @@ final class UnsafeUtil {
}
- @SuppressWarnings("unchecked")
- private static <T> Class<T> getClassForName(String name) {
- try {
- return (Class<T>) Class.forName(name);
- } catch (Throwable e) {
- return null;
- }
- }
-
/** Finds the address field within a direct {@link Buffer}. */
private static Field bufferAddressField() {
- return field(Buffer.class, "address");
+ 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() {
+ Field field = field(String.class, "value");
+ return field != null && field.getType() == char[].class ? 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 1b136144..de75fe6b 100644
--- a/java/core/src/main/java/com/google/protobuf/Utf8.java
+++ b/java/core/src/main/java/com/google/protobuf/Utf8.java
@@ -34,11 +34,15 @@ import static com.google.protobuf.UnsafeUtil.addressOffset;
import static com.google.protobuf.UnsafeUtil.hasUnsafeArrayOperations;
import static com.google.protobuf.UnsafeUtil.hasUnsafeByteBufferOperations;
import static java.lang.Character.MAX_SURROGATE;
+import static java.lang.Character.MIN_HIGH_SURROGATE;
+import static java.lang.Character.MIN_LOW_SURROGATE;
+import static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT;
import static java.lang.Character.MIN_SURROGATE;
import static java.lang.Character.isSurrogatePair;
import static java.lang.Character.toCodePoint;
import java.nio.ByteBuffer;
+import java.util.Arrays;
/**
* A set of low-level, high-performance static utility methods related
@@ -289,7 +293,7 @@ final class Utf8 {
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) {
+ if (cp < MIN_SUPPLEMENTARY_CODE_POINT) {
throw new UnpairedSurrogateException(i, utf16Length);
}
i++;
@@ -331,6 +335,26 @@ final class Utf8 {
}
/**
+ * Decodes the given UTF-8 portion of the {@link ByteBuffer} into a {@link String}.
+ *
+ * @throws InvalidProtocolBufferException if the input is not valid UTF-8.
+ */
+ static String decodeUtf8(ByteBuffer buffer, int index, int size)
+ throws InvalidProtocolBufferException {
+ return processor.decodeUtf8(buffer, index, size);
+ }
+
+ /**
+ * Decodes the given UTF-8 encoded byte array slice into a {@link String}.
+ *
+ * @throws InvalidProtocolBufferException if the input is not valid UTF-8.
+ */
+ static String decodeUtf8(byte[] bytes, int index, int size)
+ throws InvalidProtocolBufferException {
+ return processor.decodeUtf8(bytes, index, size);
+ }
+
+ /**
* Encodes the given characters to the target {@link ByteBuffer} using UTF-8 encoding.
*
* <p>Selects an optimal algorithm based on the type of {@link ByteBuffer} (i.e. heap or direct)
@@ -610,6 +634,116 @@ final class Utf8 {
}
/**
+ * Decodes the given byte array slice into a {@link String}.
+ *
+ * @throws InvalidProtocolBufferException if the byte array slice is not valid UTF-8.
+ */
+ abstract String decodeUtf8(byte[] bytes, int index, int size)
+ throws InvalidProtocolBufferException;
+
+ /**
+ * Decodes the given portion of the {@link ByteBuffer} into a {@link String}.
+ *
+ * @throws InvalidProtocolBufferException if the portion of the buffer is not valid UTF-8.
+ */
+ final String decodeUtf8(ByteBuffer buffer, int index, int size)
+ throws InvalidProtocolBufferException {
+ if (buffer.hasArray()) {
+ final int offset = buffer.arrayOffset();
+ return decodeUtf8(buffer.array(), offset + index, size);
+ } else if (buffer.isDirect()) {
+ return decodeUtf8Direct(buffer, index, size);
+ }
+ return decodeUtf8Default(buffer, index, size);
+ }
+
+ /**
+ * Decodes direct {@link ByteBuffer} instances into {@link String}.
+ */
+ abstract String decodeUtf8Direct(ByteBuffer buffer, int index, int size)
+ throws InvalidProtocolBufferException;
+
+ /**
+ * Decodes {@link ByteBuffer} instances using the {@link ByteBuffer} API rather than
+ * potentially faster approaches.
+ */
+ final String decodeUtf8Default(ByteBuffer buffer, int index, int size)
+ throws InvalidProtocolBufferException {
+ // Bitwise OR combines the sign bits so any negative value fails the check.
+ if ((index | size | buffer.limit() - index - size) < 0) {
+ throw new ArrayIndexOutOfBoundsException(
+ String.format("buffer limit=%d, index=%d, limit=%d", buffer.limit(), index, size));
+ }
+
+ int offset = index;
+ final int limit = offset + size;
+
+ // The longest possible resulting String is the same as the number of input bytes, when it is
+ // all ASCII. For other cases, this over-allocates and we will truncate in the end.
+ char[] resultArr = new char[size];
+ int resultPos = 0;
+
+ // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this).
+ // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII).
+ while (offset < limit) {
+ byte b = buffer.get(offset);
+ if (!DecodeUtil.isOneByte(b)) {
+ break;
+ }
+ offset++;
+ DecodeUtil.handleOneByte(b, resultArr, resultPos++);
+ }
+
+ while (offset < limit) {
+ byte byte1 = buffer.get(offset++);
+ if (DecodeUtil.isOneByte(byte1)) {
+ DecodeUtil.handleOneByte(byte1, resultArr, resultPos++);
+ // It's common for there to be multiple ASCII characters in a run mixed in, so add an
+ // extra optimized loop to take care of these runs.
+ while (offset < limit) {
+ byte b = buffer.get(offset);
+ if (!DecodeUtil.isOneByte(b)) {
+ break;
+ }
+ offset++;
+ DecodeUtil.handleOneByte(b, resultArr, resultPos++);
+ }
+ } else if (DecodeUtil.isTwoBytes(byte1)) {
+ if (offset >= limit) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ DecodeUtil.handleTwoBytes(
+ byte1, /* byte2 */ buffer.get(offset++), resultArr, resultPos++);
+ } else if (DecodeUtil.isThreeBytes(byte1)) {
+ if (offset >= limit - 1) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ DecodeUtil.handleThreeBytes(
+ byte1,
+ /* byte2 */ buffer.get(offset++),
+ /* byte3 */ buffer.get(offset++),
+ resultArr,
+ resultPos++);
+ } else {
+ if (offset >= limit - 2) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ DecodeUtil.handleFourBytes(
+ byte1,
+ /* byte2 */ buffer.get(offset++),
+ /* byte3 */ buffer.get(offset++),
+ /* byte4 */ buffer.get(offset++),
+ resultArr,
+ resultPos++);
+ // 4-byte case requires two chars.
+ resultPos++;
+ }
+ }
+
+ return new String(resultArr, 0, resultPos);
+ }
+
+ /**
* Encodes an input character sequence ({@code in}) to UTF-8 in the target array ({@code out}).
* For a string, this method is similar to
* <pre>{@code
@@ -851,6 +985,88 @@ final class Utf8 {
}
@Override
+ String decodeUtf8(byte[] bytes, int index, int size) throws InvalidProtocolBufferException {
+ // Bitwise OR combines the sign bits so any negative value fails the check.
+ if ((index | size | bytes.length - index - size) < 0) {
+ throw new ArrayIndexOutOfBoundsException(
+ String.format("buffer length=%d, index=%d, size=%d", bytes.length, index, size));
+ }
+
+ int offset = index;
+ final int limit = offset + size;
+
+ // The longest possible resulting String is the same as the number of input bytes, when it is
+ // all ASCII. For other cases, this over-allocates and we will truncate in the end.
+ char[] resultArr = new char[size];
+ int resultPos = 0;
+
+ // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this).
+ // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII).
+ while (offset < limit) {
+ byte b = bytes[offset];
+ if (!DecodeUtil.isOneByte(b)) {
+ break;
+ }
+ offset++;
+ DecodeUtil.handleOneByte(b, resultArr, resultPos++);
+ }
+
+ while (offset < limit) {
+ byte byte1 = bytes[offset++];
+ if (DecodeUtil.isOneByte(byte1)) {
+ DecodeUtil.handleOneByte(byte1, resultArr, resultPos++);
+ // It's common for there to be multiple ASCII characters in a run mixed in, so add an
+ // extra optimized loop to take care of these runs.
+ while (offset < limit) {
+ byte b = bytes[offset];
+ if (!DecodeUtil.isOneByte(b)) {
+ break;
+ }
+ offset++;
+ DecodeUtil.handleOneByte(b, resultArr, resultPos++);
+ }
+ } else if (DecodeUtil.isTwoBytes(byte1)) {
+ if (offset >= limit) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ DecodeUtil.handleTwoBytes(byte1, /* byte2 */ bytes[offset++], resultArr, resultPos++);
+ } else if (DecodeUtil.isThreeBytes(byte1)) {
+ if (offset >= limit - 1) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ DecodeUtil.handleThreeBytes(
+ byte1,
+ /* byte2 */ bytes[offset++],
+ /* byte3 */ bytes[offset++],
+ resultArr,
+ resultPos++);
+ } else {
+ if (offset >= limit - 2) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ DecodeUtil.handleFourBytes(
+ byte1,
+ /* byte2 */ bytes[offset++],
+ /* byte3 */ bytes[offset++],
+ /* byte4 */ bytes[offset++],
+ resultArr,
+ resultPos++);
+ // 4-byte case requires two chars.
+ resultPos++;
+ }
+ }
+
+ return new String(resultArr, 0, resultPos);
+ }
+
+ @Override
+ String decodeUtf8Direct(ByteBuffer buffer, int index, int size)
+ throws InvalidProtocolBufferException {
+ // For safe processing, we have to use the ByteBufferAPI.
+ return decodeUtf8Default(buffer, index, size);
+ }
+
+ @Override
int encodeUtf8(CharSequence in, byte[] out, int offset, int length) {
int utf16Length = in.length();
int j = offset;
@@ -996,6 +1212,7 @@ final class Utf8 {
@Override
int partialIsValidUtf8(int state, byte[] bytes, final int index, final int limit) {
+ // Bitwise OR combines the sign bits so any negative value fails the check.
if ((index | limit | bytes.length - limit) < 0) {
throw new ArrayIndexOutOfBoundsException(
String.format("Array length=%d, index=%d, limit=%d", bytes.length, index, limit));
@@ -1091,6 +1308,7 @@ final class Utf8 {
@Override
int partialIsValidUtf8Direct(
final int state, ByteBuffer buffer, final int index, final int limit) {
+ // Bitwise OR combines the sign bits so any negative value fails the check.
if ((index | limit | buffer.limit() - limit) < 0) {
throw new ArrayIndexOutOfBoundsException(
String.format("buffer limit=%d, index=%d, limit=%d", buffer.limit(), index, limit));
@@ -1185,6 +1403,157 @@ final class Utf8 {
}
@Override
+ String decodeUtf8(byte[] bytes, int index, int size) throws InvalidProtocolBufferException {
+ if ((index | size | bytes.length - index - size) < 0) {
+ throw new ArrayIndexOutOfBoundsException(
+ String.format("buffer length=%d, index=%d, size=%d", bytes.length, index, size));
+ }
+
+ int offset = index;
+ final int limit = offset + size;
+
+ // The longest possible resulting String is the same as the number of input bytes, when it is
+ // all ASCII. For other cases, this over-allocates and we will truncate in the end.
+ char[] resultArr = new char[size];
+ int resultPos = 0;
+
+ // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this).
+ // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII).
+ while (offset < limit) {
+ byte b = UnsafeUtil.getByte(bytes, offset);
+ if (!DecodeUtil.isOneByte(b)) {
+ break;
+ }
+ offset++;
+ DecodeUtil.handleOneByte(b, resultArr, resultPos++);
+ }
+
+ while (offset < limit) {
+ byte byte1 = UnsafeUtil.getByte(bytes, offset++);
+ if (DecodeUtil.isOneByte(byte1)) {
+ DecodeUtil.handleOneByte(byte1, resultArr, resultPos++);
+ // It's common for there to be multiple ASCII characters in a run mixed in, so add an
+ // extra optimized loop to take care of these runs.
+ while (offset < limit) {
+ byte b = UnsafeUtil.getByte(bytes, offset);
+ if (!DecodeUtil.isOneByte(b)) {
+ break;
+ }
+ offset++;
+ DecodeUtil.handleOneByte(b, resultArr, resultPos++);
+ }
+ } else if (DecodeUtil.isTwoBytes(byte1)) {
+ if (offset >= limit) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ DecodeUtil.handleTwoBytes(
+ byte1, /* byte2 */ UnsafeUtil.getByte(bytes, offset++), resultArr, resultPos++);
+ } else if (DecodeUtil.isThreeBytes(byte1)) {
+ if (offset >= limit - 1) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ DecodeUtil.handleThreeBytes(
+ byte1,
+ /* byte2 */ UnsafeUtil.getByte(bytes, offset++),
+ /* byte3 */ UnsafeUtil.getByte(bytes, offset++),
+ resultArr,
+ resultPos++);
+ } else {
+ if (offset >= limit - 2) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ DecodeUtil.handleFourBytes(
+ byte1,
+ /* byte2 */ UnsafeUtil.getByte(bytes, offset++),
+ /* byte3 */ UnsafeUtil.getByte(bytes, offset++),
+ /* byte4 */ UnsafeUtil.getByte(bytes, offset++),
+ resultArr,
+ resultPos++);
+ // 4-byte case requires two chars.
+ resultPos++;
+ }
+ }
+
+ return new String(resultArr, 0, resultPos);
+ }
+
+ @Override
+ String decodeUtf8Direct(ByteBuffer buffer, int index, int size)
+ throws InvalidProtocolBufferException {
+ // Bitwise OR combines the sign bits so any negative value fails the check.
+ if ((index | size | buffer.limit() - index - size) < 0) {
+ throw new ArrayIndexOutOfBoundsException(
+ String.format("buffer limit=%d, index=%d, limit=%d", buffer.limit(), index, size));
+ }
+ long address = UnsafeUtil.addressOffset(buffer) + index;
+ final long addressLimit = address + size;
+
+ // The longest possible resulting String is the same as the number of input bytes, when it is
+ // all ASCII. For other cases, this over-allocates and we will truncate in the end.
+ char[] resultArr = new char[size];
+ int resultPos = 0;
+
+ // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this).
+ // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII).
+ while (address < addressLimit) {
+ byte b = UnsafeUtil.getByte(address);
+ if (!DecodeUtil.isOneByte(b)) {
+ break;
+ }
+ address++;
+ DecodeUtil.handleOneByte(b, resultArr, resultPos++);
+ }
+
+ while (address < addressLimit) {
+ byte byte1 = UnsafeUtil.getByte(address++);
+ if (DecodeUtil.isOneByte(byte1)) {
+ DecodeUtil.handleOneByte(byte1, resultArr, resultPos++);
+ // It's common for there to be multiple ASCII characters in a run mixed in, so add an
+ // extra optimized loop to take care of these runs.
+ while (address < addressLimit) {
+ byte b = UnsafeUtil.getByte(address);
+ if (!DecodeUtil.isOneByte(b)) {
+ break;
+ }
+ address++;
+ DecodeUtil.handleOneByte(b, resultArr, resultPos++);
+ }
+ } else if (DecodeUtil.isTwoBytes(byte1)) {
+ if (address >= addressLimit) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ DecodeUtil.handleTwoBytes(
+ byte1, /* byte2 */ UnsafeUtil.getByte(address++), resultArr, resultPos++);
+ } else if (DecodeUtil.isThreeBytes(byte1)) {
+ if (address >= addressLimit - 1) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ DecodeUtil.handleThreeBytes(
+ byte1,
+ /* byte2 */ UnsafeUtil.getByte(address++),
+ /* byte3 */ UnsafeUtil.getByte(address++),
+ resultArr,
+ resultPos++);
+ } else {
+ if (address >= addressLimit - 2) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ DecodeUtil.handleFourBytes(
+ byte1,
+ /* byte2 */ UnsafeUtil.getByte(address++),
+ /* byte3 */ UnsafeUtil.getByte(address++),
+ /* byte4 */ UnsafeUtil.getByte(address++),
+ resultArr,
+ resultPos++);
+ // 4-byte case requires two chars.
+ resultPos++;
+ }
+ }
+
+ return new String(resultArr, 0, resultPos);
+ }
+
+ @Override
int encodeUtf8(final CharSequence in, final byte[] out, final int offset, final int length) {
long outIx = offset;
final long outLimit = outIx + length;
@@ -1554,5 +1923,112 @@ final class Utf8 {
}
}
+ /**
+ * Utility methods for decoding bytes into {@link String}. Callers are responsible for extracting
+ * bytes (possibly using Unsafe methods), and checking remaining bytes. All other UTF-8 validity
+ * checks and codepoint conversion happen in this class.
+ */
+ private static class DecodeUtil {
+
+ /**
+ * Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'.
+ */
+ private static boolean isOneByte(byte b) {
+ return b >= 0;
+ }
+
+ /**
+ * Returns whether this is a two-byte codepoint with the form '10XXXXXX'.
+ */
+ private static boolean isTwoBytes(byte b) {
+ return b < (byte) 0xE0;
+ }
+
+ /**
+ * Returns whether this is a three-byte codepoint with the form '110XXXXX'.
+ */
+ private static boolean isThreeBytes(byte b) {
+ return b < (byte) 0xF0;
+ }
+
+ private static void handleOneByte(byte byte1, char[] resultArr, int resultPos) {
+ resultArr[resultPos] = (char) byte1;
+ }
+
+ private static void handleTwoBytes(
+ byte byte1, byte byte2, char[] resultArr, int resultPos)
+ throws InvalidProtocolBufferException {
+ // Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and
+ // overlong 2-byte, '11000001'.
+ if (byte1 < (byte) 0xC2
+ || isNotTrailingByte(byte2)) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ resultArr[resultPos] = (char) (((byte1 & 0x1F) << 6) | trailingByteValue(byte2));
+ }
+
+ private static void handleThreeBytes(
+ byte byte1, byte byte2, byte byte3, char[] resultArr, int resultPos)
+ throws InvalidProtocolBufferException {
+ if (isNotTrailingByte(byte2)
+ // overlong? 5 most significant bits must not all be zero
+ || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0)
+ // check for illegal surrogate codepoints
+ || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0)
+ || isNotTrailingByte(byte3)) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ resultArr[resultPos] = (char)
+ (((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3));
+ }
+
+ private static void handleFourBytes(
+ byte byte1, byte byte2, byte byte3, byte byte4, char[] resultArr, int resultPos)
+ throws InvalidProtocolBufferException{
+ if (isNotTrailingByte(byte2)
+ // Check that 1 <= plane <= 16. Tricky optimized form of:
+ // valid 4-byte leading byte?
+ // if (byte1 > (byte) 0xF4 ||
+ // overlong? 4 most significant bits must not all be zero
+ // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 ||
+ // codepoint larger than the highest code point (U+10FFFF)?
+ // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F)
+ || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0
+ || isNotTrailingByte(byte3)
+ || isNotTrailingByte(byte4)) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ int codepoint = ((byte1 & 0x07) << 18)
+ | (trailingByteValue(byte2) << 12)
+ | (trailingByteValue(byte3) << 6)
+ | trailingByteValue(byte4);
+ resultArr[resultPos] = DecodeUtil.highSurrogate(codepoint);
+ resultArr[resultPos + 1] = DecodeUtil.lowSurrogate(codepoint);
+ }
+
+ /**
+ * Returns whether the byte is not a valid continuation of the form '10XXXXXX'.
+ */
+ private static boolean isNotTrailingByte(byte b) {
+ return b > (byte) 0xBF;
+ }
+
+ /**
+ * Returns the actual value of the trailing byte (removes the prefix '10') for composition.
+ */
+ private static int trailingByteValue(byte b) {
+ return b & 0x3F;
+ }
+
+ private static char highSurrogate(int codePoint) {
+ return (char) ((MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10))
+ + (codePoint >>> 10));
+ }
+
+ private static char lowSurrogate(int codePoint) {
+ return (char) (MIN_LOW_SURROGATE + (codePoint & 0x3ff));
+ }
+ }
+
private Utf8() {}
}
diff --git a/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java b/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java
index 622e36a4..cb2d34eb 100644
--- a/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java
+++ b/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java
@@ -30,6 +30,9 @@
package com.google.protobuf;
+import static com.google.protobuf.TestUtil.TEST_REQUIRED_INITIALIZED;
+import static com.google.protobuf.TestUtil.TEST_REQUIRED_UNINITIALIZED;
+
import com.google.protobuf.Descriptors.FieldDescriptor;
import protobuf_unittest.UnittestOptimizeFor.TestOptimizedForSize;
import protobuf_unittest.UnittestProto;
@@ -346,11 +349,6 @@ public class AbstractMessageTest extends TestCase {
// -----------------------------------------------------------------
// Tests for isInitialized().
- private static final TestRequired TEST_REQUIRED_UNINITIALIZED =
- TestRequired.getDefaultInstance();
- private static final TestRequired TEST_REQUIRED_INITIALIZED =
- TestRequired.newBuilder().setA(1).setB(2).setC(3).build();
-
public void testIsInitialized() throws Exception {
TestRequired.Builder builder = TestRequired.newBuilder();
AbstractMessageWrapper.Builder abstractBuilder =
@@ -380,7 +378,7 @@ public class AbstractMessageTest extends TestCase {
builder.setOptionalMessage(TEST_REQUIRED_UNINITIALIZED);
assertFalse(abstractBuilder.isInitialized());
assertEquals(
- "optional_message.a, optional_message.b, optional_message.c",
+ "optional_message.b, optional_message.c",
abstractBuilder.getInitializationErrorString());
builder.setOptionalMessage(TEST_REQUIRED_INITIALIZED);
@@ -390,7 +388,7 @@ public class AbstractMessageTest extends TestCase {
builder.addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED);
assertFalse(abstractBuilder.isInitialized());
assertEquals(
- "repeated_message[0].a, repeated_message[0].b, repeated_message[0].c",
+ "repeated_message[0].b, repeated_message[0].c",
abstractBuilder.getInitializationErrorString());
builder.setRepeatedMessage(0, TEST_REQUIRED_INITIALIZED);
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/DecodeUtf8Test.java b/java/core/src/test/java/com/google/protobuf/DecodeUtf8Test.java
new file mode 100644
index 00000000..359d4d74
--- /dev/null
+++ b/java/core/src/test/java/com/google/protobuf/DecodeUtf8Test.java
@@ -0,0 +1,325 @@
+package com.google.protobuf;
+
+import com.google.protobuf.Utf8.Processor;
+import com.google.protobuf.Utf8.SafeProcessor;
+import com.google.protobuf.Utf8.UnsafeProcessor;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Logger;
+import junit.framework.TestCase;
+
+public class DecodeUtf8Test extends TestCase {
+ private static Logger logger = Logger.getLogger(DecodeUtf8Test.class.getName());
+
+ private static final Processor SAFE_PROCESSOR = new SafeProcessor();
+ private static final Processor UNSAFE_PROCESSOR = new UnsafeProcessor();
+
+ public void testRoundTripAllValidChars() throws Exception {
+ for (int i = Character.MIN_CODE_POINT; i < Character.MAX_CODE_POINT; i++) {
+ if (i < Character.MIN_SURROGATE || i > Character.MAX_SURROGATE) {
+ String str = new String(Character.toChars(i));
+ assertRoundTrips(str);
+ }
+ }
+ }
+
+ // Test all 1, 2, 3 invalid byte combinations. Valid ones would have been covered above.
+
+ public void testOneByte() throws Exception {
+ int valid = 0;
+ for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
+ ByteString bs = ByteString.copyFrom(new byte[] { (byte) i });
+ if (!bs.isValidUtf8()) {
+ assertInvalid(bs.toByteArray());
+ } else {
+ valid++;
+ }
+ }
+ assertEquals(IsValidUtf8TestUtil.EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, valid);
+ }
+
+ public void testTwoBytes() throws Exception {
+ int valid = 0;
+ for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
+ for (int j = Byte.MIN_VALUE; j <= Byte.MAX_VALUE; j++) {
+ ByteString bs = ByteString.copyFrom(new byte[]{(byte) i, (byte) j});
+ if (!bs.isValidUtf8()) {
+ assertInvalid(bs.toByteArray());
+ } else {
+ valid++;
+ }
+ }
+ }
+ assertEquals(IsValidUtf8TestUtil.EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT, valid);
+ }
+
+ public void testThreeBytes() throws Exception {
+ // Travis' OOM killer doesn't like this test
+ if (System.getenv("TRAVIS") == null) {
+ int count = 0;
+ int valid = 0;
+ for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
+ for (int j = Byte.MIN_VALUE; j <= Byte.MAX_VALUE; j++) {
+ for (int k = Byte.MIN_VALUE; k <= Byte.MAX_VALUE; k++) {
+ byte[] bytes = new byte[]{(byte) i, (byte) j, (byte) k};
+ ByteString bs = ByteString.copyFrom(bytes);
+ if (!bs.isValidUtf8()) {
+ assertInvalid(bytes);
+ } else {
+ valid++;
+ }
+ count++;
+ if (count % 1000000L == 0) {
+ logger.info("Processed " + (count / 1000000L) + " million characters");
+ }
+ }
+ }
+ }
+ assertEquals(IsValidUtf8TestUtil.EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT, valid);
+ }
+ }
+
+ /**
+ * Tests that round tripping of a sample of four byte permutations work.
+ */
+ public void testInvalid_4BytesSamples() throws Exception {
+ // Bad trailing bytes
+ assertInvalid(0xF0, 0xA4, 0xAD, 0x7F);
+ assertInvalid(0xF0, 0xA4, 0xAD, 0xC0);
+
+ // Special cases for byte2
+ assertInvalid(0xF0, 0x8F, 0xAD, 0xA2);
+ assertInvalid(0xF4, 0x90, 0xAD, 0xA2);
+ }
+
+ public void testRealStrings() throws Exception {
+ // English
+ assertRoundTrips("The quick brown fox jumps over the lazy dog");
+ // German
+ assertRoundTrips("Quizdeltagerne spiste jordb\u00e6r med fl\u00f8de, mens cirkusklovnen");
+ // Japanese
+ assertRoundTrips(
+ "\u3044\u308d\u306f\u306b\u307b\u3078\u3068\u3061\u308a\u306c\u308b\u3092");
+ // Hebrew
+ assertRoundTrips(
+ "\u05d3\u05d2 \u05e1\u05e7\u05e8\u05df \u05e9\u05d8 \u05d1\u05d9\u05dd "
+ + "\u05de\u05d0\u05d5\u05db\u05d6\u05d1 \u05d5\u05dc\u05e4\u05ea\u05e2"
+ + " \u05de\u05e6\u05d0 \u05dc\u05d5 \u05d7\u05d1\u05e8\u05d4 "
+ + "\u05d0\u05d9\u05da \u05d4\u05e7\u05dc\u05d9\u05d8\u05d4");
+ // Thai
+ assertRoundTrips(
+ " \u0e08\u0e07\u0e1d\u0e48\u0e32\u0e1f\u0e31\u0e19\u0e1e\u0e31\u0e12"
+ + "\u0e19\u0e32\u0e27\u0e34\u0e0a\u0e32\u0e01\u0e32\u0e23");
+ // Chinese
+ assertRoundTrips(
+ "\u8fd4\u56de\u94fe\u4e2d\u7684\u4e0b\u4e00\u4e2a\u4ee3\u7406\u9879\u9009\u62e9\u5668");
+ // Chinese with 4-byte chars
+ assertRoundTrips("\uD841\uDF0E\uD841\uDF31\uD841\uDF79\uD843\uDC53\uD843\uDC78"
+ + "\uD843\uDC96\uD843\uDCCF\uD843\uDCD5\uD843\uDD15\uD843\uDD7C\uD843\uDD7F"
+ + "\uD843\uDE0E\uD843\uDE0F\uD843\uDE77\uD843\uDE9D\uD843\uDEA2");
+ // Mixed
+ assertRoundTrips(
+ "The quick brown \u3044\u308d\u306f\u306b\u307b\u3078\u8fd4\u56de\u94fe"
+ + "\u4e2d\u7684\u4e0b\u4e00");
+ }
+
+ public void testOverlong() throws Exception {
+ assertInvalid(0xc0, 0xaf);
+ assertInvalid(0xe0, 0x80, 0xaf);
+ assertInvalid(0xf0, 0x80, 0x80, 0xaf);
+
+ // Max overlong
+ assertInvalid(0xc1, 0xbf);
+ assertInvalid(0xe0, 0x9f, 0xbf);
+ assertInvalid(0xf0 ,0x8f, 0xbf, 0xbf);
+
+ // null overlong
+ assertInvalid(0xc0, 0x80);
+ assertInvalid(0xe0, 0x80, 0x80);
+ assertInvalid(0xf0, 0x80, 0x80, 0x80);
+ }
+
+ public void testIllegalCodepoints() throws Exception {
+ // Single surrogate
+ assertInvalid(0xed, 0xa0, 0x80);
+ assertInvalid(0xed, 0xad, 0xbf);
+ assertInvalid(0xed, 0xae, 0x80);
+ assertInvalid(0xed, 0xaf, 0xbf);
+ assertInvalid(0xed, 0xb0, 0x80);
+ assertInvalid(0xed, 0xbe, 0x80);
+ assertInvalid(0xed, 0xbf, 0xbf);
+
+ // Paired surrogates
+ assertInvalid(0xed, 0xa0, 0x80, 0xed, 0xb0, 0x80);
+ assertInvalid(0xed, 0xa0, 0x80, 0xed, 0xbf, 0xbf);
+ assertInvalid(0xed, 0xad, 0xbf, 0xed, 0xb0, 0x80);
+ assertInvalid(0xed, 0xad, 0xbf, 0xed, 0xbf, 0xbf);
+ assertInvalid(0xed, 0xae, 0x80, 0xed, 0xb0, 0x80);
+ assertInvalid(0xed, 0xae, 0x80, 0xed, 0xbf, 0xbf);
+ assertInvalid(0xed, 0xaf, 0xbf, 0xed, 0xb0, 0x80);
+ assertInvalid(0xed, 0xaf, 0xbf, 0xed, 0xbf, 0xbf);
+ }
+
+ public void testBufferSlice() throws Exception {
+ String str = "The quick brown fox jumps over the lazy dog";
+ assertRoundTrips(str, 10, 4);
+ assertRoundTrips(str, str.length(), 0);
+ }
+
+ public void testInvalidBufferSlice() throws Exception {
+ byte[] bytes = "The quick brown fox jumps over the lazy dog".getBytes(Internal.UTF_8);
+ assertInvalidSlice(bytes, bytes.length - 3, 4);
+ assertInvalidSlice(bytes, bytes.length, 1);
+ assertInvalidSlice(bytes, bytes.length + 1, 0);
+ assertInvalidSlice(bytes, 0, bytes.length + 1);
+ }
+
+ private void assertInvalid(int... bytesAsInt) throws Exception {
+ byte[] bytes = new byte[bytesAsInt.length];
+ for (int i = 0; i < bytesAsInt.length; i++) {
+ bytes[i] = (byte) bytesAsInt[i];
+ }
+ assertInvalid(bytes);
+ }
+
+ private void assertInvalid(byte[] bytes) throws Exception {
+ try {
+ UNSAFE_PROCESSOR.decodeUtf8(bytes, 0, bytes.length);
+ fail();
+ } catch (InvalidProtocolBufferException e) {
+ // Expected.
+ }
+ try {
+ SAFE_PROCESSOR.decodeUtf8(bytes, 0, bytes.length);
+ fail();
+ } catch (InvalidProtocolBufferException e) {
+ // Expected.
+ }
+
+ ByteBuffer direct = ByteBuffer.allocateDirect(bytes.length);
+ direct.put(bytes);
+ direct.flip();
+ try {
+ UNSAFE_PROCESSOR.decodeUtf8(direct, 0, bytes.length);
+ fail();
+ } catch (InvalidProtocolBufferException e) {
+ // Expected.
+ }
+ try {
+ SAFE_PROCESSOR.decodeUtf8(direct, 0, bytes.length);
+ fail();
+ } catch (InvalidProtocolBufferException e) {
+ // Expected.
+ }
+
+ ByteBuffer heap = ByteBuffer.allocate(bytes.length);
+ heap.put(bytes);
+ heap.flip();
+ try {
+ UNSAFE_PROCESSOR.decodeUtf8(heap, 0, bytes.length);
+ fail();
+ } catch (InvalidProtocolBufferException e) {
+ // Expected.
+ }
+ try {
+ SAFE_PROCESSOR.decodeUtf8(heap, 0, bytes.length);
+ fail();
+ } catch (InvalidProtocolBufferException e) {
+ // Expected.
+ }
+ }
+
+ private void assertInvalidSlice(byte[] bytes, int index, int size) throws Exception {
+ try {
+ UNSAFE_PROCESSOR.decodeUtf8(bytes, index, size);
+ fail();
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected.
+ }
+ try {
+ SAFE_PROCESSOR.decodeUtf8(bytes, index, size);
+ fail();
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected.
+ }
+
+ ByteBuffer direct = ByteBuffer.allocateDirect(bytes.length);
+ direct.put(bytes);
+ direct.flip();
+ try {
+ UNSAFE_PROCESSOR.decodeUtf8(direct, index, size);
+ fail();
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected.
+ }
+ try {
+ SAFE_PROCESSOR.decodeUtf8(direct, index, size);
+ fail();
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected.
+ }
+
+ ByteBuffer heap = ByteBuffer.allocate(bytes.length);
+ heap.put(bytes);
+ heap.flip();
+ try {
+ UNSAFE_PROCESSOR.decodeUtf8(heap, index, size);
+ fail();
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected.
+ }
+ try {
+ SAFE_PROCESSOR.decodeUtf8(heap, index, size);
+ fail();
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected.
+ }
+ }
+
+ private void assertRoundTrips(String str) throws Exception {
+ assertRoundTrips(str, 0, -1);
+ }
+
+ private void assertRoundTrips(String str, int index, int size) throws Exception {
+ byte[] bytes = str.getBytes(Internal.UTF_8);
+ if (size == -1) {
+ size = bytes.length;
+ }
+ assertDecode(new String(bytes, index, size, Internal.UTF_8),
+ UNSAFE_PROCESSOR.decodeUtf8(bytes, index, size));
+ assertDecode(new String(bytes, index, size, Internal.UTF_8),
+ SAFE_PROCESSOR.decodeUtf8(bytes, index, size));
+
+ ByteBuffer direct = ByteBuffer.allocateDirect(bytes.length);
+ direct.put(bytes);
+ direct.flip();
+ assertDecode(new String(bytes, index, size, Internal.UTF_8),
+ UNSAFE_PROCESSOR.decodeUtf8(direct, index, size));
+ assertDecode(new String(bytes, index, size, Internal.UTF_8),
+ SAFE_PROCESSOR.decodeUtf8(direct, index, size));
+
+ ByteBuffer heap = ByteBuffer.allocate(bytes.length);
+ heap.put(bytes);
+ heap.flip();
+ assertDecode(new String(bytes, index, size, Internal.UTF_8),
+ UNSAFE_PROCESSOR.decodeUtf8(heap, index, size));
+ assertDecode(new String(bytes, index, size, Internal.UTF_8),
+ SAFE_PROCESSOR.decodeUtf8(heap, index, size));
+ }
+
+ private void assertDecode(String expected, String actual) {
+ if (!expected.equals(actual)) {
+ fail("Failure: Expected (" + codepoints(expected) + ") Actual (" + codepoints(actual) + ")");
+ }
+ }
+
+ private List<String> codepoints(String str) {
+ List<String> codepoints = new ArrayList<String>();
+ for (int i = 0; i < str.length(); i++) {
+ codepoints.add(Long.toHexString(str.charAt(i)));
+ }
+ return codepoints;
+ }
+
+}
diff --git a/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java b/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java
index 2c272a73..9c0997c4 100644
--- a/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java
+++ b/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java
@@ -37,22 +37,22 @@ import junit.framework.TestCase;
/**
* Test field deprecation
- *
+ *
* @author birdo@google.com (Roberto Scaramuzzi)
*/
public class DeprecatedFieldTest extends TestCase {
private String[] deprecatedGetterNames = {
"hasDeprecatedInt32",
"getDeprecatedInt32"};
-
+
private String[] deprecatedBuilderGetterNames = {
"hasDeprecatedInt32",
"getDeprecatedInt32",
"clearDeprecatedInt32"};
-
+
private String[] deprecatedBuilderSetterNames = {
- "setDeprecatedInt32"};
-
+ "setDeprecatedInt32"};
+
public void testDeprecatedField() throws Exception {
Class<?> deprecatedFields = TestDeprecatedFields.class;
Class<?> deprecatedFieldsBuilder = TestDeprecatedFields.Builder.class;
@@ -72,7 +72,15 @@ public class DeprecatedFieldTest extends TestCase {
isDeprecated(method));
}
}
-
+
+ public void testDeprecatedFieldInOneof() throws Exception {
+ Class<?> oneofCase = TestDeprecatedFields.OneofFieldsCase.class;
+ String name = "DEPRECATED_INT32_IN_ONEOF";
+ java.lang.reflect.Field enumValue = oneofCase.getField(name);
+ assertTrue("Enum value " + name + " should be deprecated.",
+ isDeprecated(enumValue));
+ }
+
private boolean isDeprecated(AnnotatedElement annotated) {
return annotated.isAnnotationPresent(Deprecated.class);
}
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/IsValidUtf8TestUtil.java b/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java
index 16a808bf..1bcf63e7 100644
--- a/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java
+++ b/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java
@@ -273,6 +273,15 @@ final class IsValidUtf8TestUtil {
assertEquals(isRoundTrippable, Utf8.isValidUtf8(bytes));
assertEquals(isRoundTrippable, Utf8.isValidUtf8(bytes, 0, numBytes));
+ try {
+ assertEquals(s, Utf8.decodeUtf8(bytes, 0, numBytes));
+ } catch (InvalidProtocolBufferException e) {
+ if (isRoundTrippable) {
+ System.out.println("Could not decode utf-8");
+ outputFailure(byteChar, bytes, bytesReencoded);
+ }
+ }
+
// Test partial sequences.
// Partition numBytes into three segments (not necessarily non-empty).
int i = rnd.nextInt(numBytes);
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/TestUtil.java b/java/core/src/test/java/com/google/protobuf/TestUtil.java
index e96adf07..b4bc3a3d 100644
--- a/java/core/src/test/java/com/google/protobuf/TestUtil.java
+++ b/java/core/src/test/java/com/google/protobuf/TestUtil.java
@@ -231,6 +231,7 @@ import protobuf_unittest.UnittestProto.TestAllTypesOrBuilder;
import protobuf_unittest.UnittestProto.TestOneof2;
import protobuf_unittest.UnittestProto.TestPackedExtensions;
import protobuf_unittest.UnittestProto.TestPackedTypes;
+import protobuf_unittest.UnittestProto.TestRequired;
import protobuf_unittest.UnittestProto.TestUnpackedTypes;
import java.io.File;
import java.io.IOException;
@@ -252,6 +253,11 @@ import junit.framework.Assert;
public final class TestUtil {
private TestUtil() {}
+ public static final TestRequired TEST_REQUIRED_UNINITIALIZED =
+ TestRequired.newBuilder().setA(1).buildPartial();
+ public static final TestRequired TEST_REQUIRED_INITIALIZED =
+ TestRequired.newBuilder().setA(1).setB(2).setC(3).build();
+
/** Helper to convert a String to ByteString. */
static ByteString toBytes(String str) {
return ByteString.copyFrom(str.getBytes(Internal.UTF_8));
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 28c4fdea..720061d2 100644
--- a/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
+++ b/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
@@ -30,6 +30,9 @@
package com.google.protobuf;
+import static com.google.protobuf.TestUtil.TEST_REQUIRED_INITIALIZED;
+import static com.google.protobuf.TestUtil.TEST_REQUIRED_UNINITIALIZED;
+
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.TextFormat.Parser.SingularOverwritePolicy;
@@ -42,6 +45,7 @@ import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestAllTypes.NestedMessage;
import protobuf_unittest.UnittestProto.TestEmptyMessage;
import protobuf_unittest.UnittestProto.TestOneof2;
+import protobuf_unittest.UnittestProto.TestRequired;
import proto2_wireformat_unittest.UnittestMsetWireFormat.TestMessageSet;
import java.io.StringReader;
import java.util.List;
@@ -57,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 \\\\";
@@ -326,19 +329,58 @@ public class TextFormatTest extends TestCase {
// =================================================================
- public void testParse() throws Exception {
+ public void testMerge() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(allFieldsSetText, builder);
TestUtil.assertAllFieldsSet(builder.build());
}
- public void testParseReader() throws Exception {
+ public void testParse() throws Exception {
+ TestUtil.assertAllFieldsSet(
+ TextFormat.parse(allFieldsSetText, TestAllTypes.class));
+ }
+
+ public void testMergeInitialized() throws Exception {
+ TestRequired.Builder builder = TestRequired.newBuilder();
+ TextFormat.merge(TEST_REQUIRED_INITIALIZED.toString(), builder);
+ assertEquals(TEST_REQUIRED_INITIALIZED.toString(),
+ builder.buildPartial().toString());
+ assertTrue(builder.isInitialized());
+ }
+
+ public void testParseInitialized() throws Exception {
+ TestRequired parsed =
+ TextFormat.parse(TEST_REQUIRED_INITIALIZED.toString(),
+ TestRequired.class);
+ assertEquals(TEST_REQUIRED_INITIALIZED.toString(), parsed.toString());
+ assertTrue(parsed.isInitialized());
+ }
+
+ public void testMergeUninitialized() throws Exception {
+ TestRequired.Builder builder = TestRequired.newBuilder();
+ TextFormat.merge(TEST_REQUIRED_UNINITIALIZED.toString(), builder);
+ assertEquals(TEST_REQUIRED_UNINITIALIZED.toString(),
+ builder.buildPartial().toString());
+ assertFalse(builder.isInitialized());
+ }
+
+ public void testParseUninitialized() throws Exception {
+ try {
+ TextFormat.parse(TEST_REQUIRED_UNINITIALIZED.toString(),
+ TestRequired.class);
+ fail("Expected UninitializedMessageException.");
+ } catch (UninitializedMessageException e) {
+ assertEquals("Message missing required fields: b, c", e.getMessage());
+ }
+ }
+
+ public void testMergeReader() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(new StringReader(allFieldsSetText), builder);
TestUtil.assertAllFieldsSet(builder.build());
}
- public void testParseExtensions() throws Exception {
+ public void testMergeExtensions() throws Exception {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
TextFormat.merge(allExtensionsSetText,
TestUtil.getExtensionRegistry(),
@@ -346,7 +388,14 @@ public class TextFormatTest extends TestCase {
TestUtil.assertAllExtensionsSet(builder.build());
}
- public void testParseCompatibility() throws Exception {
+ public void testParseExtensions() throws Exception {
+ TestUtil.assertAllExtensionsSet(
+ TextFormat.parse(allExtensionsSetText,
+ TestUtil.getExtensionRegistry(),
+ TestAllExtensions.class));
+ }
+
+ public void testMergeAndParseCompatibility() throws Exception {
String original = "repeated_float: inf\n" +
"repeated_float: -inf\n" +
"repeated_float: nan\n" +
@@ -371,21 +420,29 @@ public class TextFormatTest extends TestCase {
"repeated_double: Infinity\n" +
"repeated_double: -Infinity\n" +
"repeated_double: NaN\n";
+
+ // Test merge().
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(original, builder);
assertEquals(canonical, builder.build().toString());
+
+ // Test parse().
+ assertEquals(canonical,
+ TextFormat.parse(original, TestAllTypes.class).toString());
}
- public void testParseExotic() throws Exception {
+ public void testMergeAndParseExotic() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(exoticText, builder);
// Too lazy to check things individually. Don't try to debug this
// if testPrintExotic() is failing.
assertEquals(canonicalExoticText, builder.build().toString());
+ assertEquals(canonicalExoticText,
+ TextFormat.parse(exoticText, TestAllTypes.class).toString());
}
- public void testParseMessageSet() throws Exception {
+ public void testMergeMessageSet() throws Exception {
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
extensionRegistry.add(TestMessageSetExtension1.messageSetExtension);
extensionRegistry.add(TestMessageSetExtension2.messageSetExtension);
@@ -411,7 +468,7 @@ public class TextFormatTest extends TestCase {
TestMessageSetExtension1.messageSetExtension).getI());
}
- public void testParseMessageSetWithOverwriteForbidden() throws Exception {
+ public void testMergeMessageSetWithOverwriteForbidden() throws Exception {
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
extensionRegistry.add(TestMessageSetExtension1.messageSetExtension);
extensionRegistry.add(TestMessageSetExtension2.messageSetExtension);
@@ -438,20 +495,20 @@ public class TextFormatTest extends TestCase {
}
}
- public void testParseNumericEnum() throws Exception {
+ public void testMergeNumericEnum() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge("optional_nested_enum: 2", builder);
assertEquals(TestAllTypes.NestedEnum.BAR, builder.getOptionalNestedEnum());
}
- public void testParseAngleBrackets() throws Exception {
+ public void testMergeAngleBrackets() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge("OptionalGroup: < a: 1 >", builder);
assertTrue(builder.hasOptionalGroup());
assertEquals(1, builder.getOptionalGroup().getA());
}
- public void testParseComment() throws Exception {
+ public void testMergeComment() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(
"# this is a comment\n" +
@@ -463,6 +520,7 @@ public class TextFormatTest extends TestCase {
}
private void assertParseError(String error, String text) {
+ // Test merge().
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
try {
TextFormat.merge(text, TestUtil.getExtensionRegistry(), builder);
@@ -470,6 +528,15 @@ public class TextFormatTest extends TestCase {
} catch (TextFormat.ParseException e) {
assertEquals(error, e.getMessage());
}
+
+ // Test parse().
+ try {
+ TextFormat.parse(
+ text, TestUtil.getExtensionRegistry(), TestAllTypes.class);
+ fail("Expected parse exception.");
+ } catch (TextFormat.ParseException e) {
+ assertEquals(error, e.getMessage());
+ }
}
@@ -508,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.",
@@ -575,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 58af8939..f2284918 100644
--- a/java/pom.xml
+++ b/java/pom.xml
@@ -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>
@@ -96,8 +94,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
- <source>1.6</source>
- <target>1.6</target>
+ <source>1.7</source>
+ <target>1.7</target>
</configuration>
</plugin>
<plugin>
@@ -208,7 +206,6 @@
<modules>
<module>core</module>
- <!-- <module>lite</module> -->
<module>util</module>
</modules>
diff --git a/java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java b/java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java
index e017b987..4a13fb1d 100644
--- a/java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java
+++ b/java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java
@@ -245,7 +245,7 @@ final class FieldMaskTree {
}
if (!source.hasField(field) && !destination.hasField(field)) {
// If the message field is not present in both source and destination, skip recursing
- // so we don't create unneccessary empty messages.
+ // so we don't create unnecessary empty messages.
continue;
}
String childPath = path.isEmpty() ? entry.getKey() : path + "." + entry.getKey();
diff --git a/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java b/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java
index a26dbc2d..7f69ee68 100644
--- a/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java
+++ b/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java
@@ -105,7 +105,7 @@ public class JsonFormat {
public static Printer printer() {
return new Printer(
TypeRegistry.getEmptyTypeRegistry(), false, Collections.<FieldDescriptor>emptySet(),
- false, false);
+ false, false, false);
}
/**
@@ -125,18 +125,21 @@ public class JsonFormat {
private Set<FieldDescriptor> includingDefaultValueFields;
private final boolean preservingProtoFieldNames;
private final boolean omittingInsignificantWhitespace;
+ private final boolean printingEnumsAsInts;
private Printer(
TypeRegistry registry,
boolean alwaysOutputDefaultValueFields,
Set<FieldDescriptor> includingDefaultValueFields,
boolean preservingProtoFieldNames,
- boolean omittingInsignificantWhitespace) {
+ boolean omittingInsignificantWhitespace,
+ boolean printingEnumsAsInts) {
this.registry = registry;
this.alwaysOutputDefaultValueFields = alwaysOutputDefaultValueFields;
this.includingDefaultValueFields = includingDefaultValueFields;
this.preservingProtoFieldNames = preservingProtoFieldNames;
this.omittingInsignificantWhitespace = omittingInsignificantWhitespace;
+ this.printingEnumsAsInts = printingEnumsAsInts;
}
/**
@@ -154,7 +157,8 @@ public class JsonFormat {
alwaysOutputDefaultValueFields,
includingDefaultValueFields,
preservingProtoFieldNames,
- omittingInsignificantWhitespace);
+ omittingInsignificantWhitespace,
+ printingEnumsAsInts);
}
/**
@@ -170,7 +174,31 @@ public class JsonFormat {
true,
Collections.<FieldDescriptor>emptySet(),
preservingProtoFieldNames,
- omittingInsignificantWhitespace);
+ omittingInsignificantWhitespace,
+ printingEnumsAsInts);
+ }
+
+ /**
+ * Creates a new {@link Printer} that will print enum field values as integers instead of as
+ * string.
+ * The new Printer clones all other configurations from the current
+ * {@link Printer}.
+ */
+ public Printer printingEnumsAsInts() {
+ checkUnsetPrintingEnumsAsInts();
+ return new Printer(
+ registry,
+ alwaysOutputDefaultValueFields,
+ Collections.<FieldDescriptor>emptySet(),
+ preservingProtoFieldNames,
+ omittingInsignificantWhitespace,
+ true);
+ }
+
+ private void checkUnsetPrintingEnumsAsInts() {
+ if (printingEnumsAsInts) {
+ throw new IllegalStateException("JsonFormat printingEnumsAsInts has already been set.");
+ }
}
/**
@@ -191,7 +219,8 @@ public class JsonFormat {
false,
fieldsToAlwaysOutput,
preservingProtoFieldNames,
- omittingInsignificantWhitespace);
+ omittingInsignificantWhitespace,
+ printingEnumsAsInts);
}
private void checkUnsetIncludingDefaultValueFields() {
@@ -213,7 +242,8 @@ public class JsonFormat {
alwaysOutputDefaultValueFields,
includingDefaultValueFields,
true,
- omittingInsignificantWhitespace);
+ omittingInsignificantWhitespace,
+ printingEnumsAsInts);
}
@@ -240,7 +270,8 @@ public class JsonFormat {
alwaysOutputDefaultValueFields,
includingDefaultValueFields,
preservingProtoFieldNames,
- true);
+ true,
+ printingEnumsAsInts);
}
/**
@@ -259,7 +290,8 @@ public class JsonFormat {
includingDefaultValueFields,
preservingProtoFieldNames,
output,
- omittingInsignificantWhitespace)
+ omittingInsignificantWhitespace,
+ printingEnumsAsInts)
.print(message);
}
@@ -416,7 +448,7 @@ public class JsonFormat {
*/
public Builder add(Iterable<Descriptor> messageTypes) {
if (types == null) {
- throw new IllegalStateException("A TypeRegistry.Builer can only be used once.");
+ throw new IllegalStateException("A TypeRegistry.Builder can only be used once.");
}
for (Descriptor type : messageTypes) {
addFile(type.getFile());
@@ -570,6 +602,7 @@ public class JsonFormat {
private final boolean alwaysOutputDefaultValueFields;
private final Set<FieldDescriptor> includingDefaultValueFields;
private final boolean preservingProtoFieldNames;
+ private final boolean printingEnumsAsInts;
private final TextGenerator generator;
// We use Gson to help handle string escapes.
private final Gson gson;
@@ -586,11 +619,13 @@ public class JsonFormat {
Set<FieldDescriptor> includingDefaultValueFields,
boolean preservingProtoFieldNames,
Appendable jsonOutput,
- boolean omittingInsignificantWhitespace) {
+ boolean omittingInsignificantWhitespace,
+ boolean printingEnumsAsInts) {
this.registry = registry;
this.alwaysOutputDefaultValueFields = alwaysOutputDefaultValueFields;
this.includingDefaultValueFields = includingDefaultValueFields;
this.preservingProtoFieldNames = preservingProtoFieldNames;
+ this.printingEnumsAsInts = printingEnumsAsInts;
this.gson = GsonHolder.DEFAULT_GSON;
// json format related properties, determined by printerType
if (omittingInsignificantWhitespace) {
@@ -1069,7 +1104,7 @@ public class JsonFormat {
generator.print("\"");
}
} else {
- if (((EnumValueDescriptor) value).getIndex() == -1) {
+ if (printingEnumsAsInts || ((EnumValueDescriptor) value).getIndex() == -1) {
generator.print(String.valueOf(((EnumValueDescriptor) value).getNumber()));
} else {
generator.print("\"" + ((EnumValueDescriptor) value).getName() + "\"");
diff --git a/java/util/src/main/java/com/google/protobuf/util/Timestamps.java b/java/util/src/main/java/com/google/protobuf/util/Timestamps.java
index 7a1f2014..9e528d4a 100644
--- a/java/util/src/main/java/com/google/protobuf/util/Timestamps.java
+++ b/java/util/src/main/java/com/google/protobuf/util/Timestamps.java
@@ -74,6 +74,11 @@ public final class Timestamps {
public static final Timestamp MAX_VALUE =
Timestamp.newBuilder().setSeconds(TIMESTAMP_SECONDS_MAX).setNanos(999999999).build();
+ /**
+ * A constant holding the {@link Timestamp} of epoch time, {@code 1970-01-01T00:00:00.000000000Z}.
+ */
+ public static final Timestamp EPOCH = Timestamp.newBuilder().setSeconds(0).setNanos(0).build();
+
private static final ThreadLocal<SimpleDateFormat> timestampFormat =
new ThreadLocal<SimpleDateFormat>() {
@Override
@@ -358,10 +363,12 @@ public final class Timestamps {
static Timestamp normalizedTimestamp(long seconds, int nanos) {
if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
- nanos %= NANOS_PER_SECOND;
+ nanos = (int) (nanos % NANOS_PER_SECOND);
}
if (nanos < 0) {
- nanos += NANOS_PER_SECOND; // no overflow since nanos is negative (and we're adding)
+ nanos =
+ (int)
+ (nanos + NANOS_PER_SECOND); // no overflow since nanos is negative (and we're adding)
seconds = checkedSubtract(seconds, 1);
}
Timestamp timestamp = Timestamp.newBuilder().setSeconds(seconds).setNanos(nanos).build();
diff --git a/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java b/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java
index e4c5387a..6ef08508 100644
--- a/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java
+++ b/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java
@@ -1174,6 +1174,14 @@ public class JsonFormatTest extends TestCase {
JsonFormat.parser().ignoringUnknownFields().merge(json, builder);
}
+ public void testParserIntegerEnumValue() throws Exception {
+ TestAllTypes.Builder actualBuilder = TestAllTypes.newBuilder();
+ mergeFromJson("{\n" + " \"optionalNestedEnum\": 2\n" + "}", actualBuilder);
+
+ TestAllTypes expected = TestAllTypes.newBuilder().setOptionalNestedEnum(NestedEnum.BAZ).build();
+ assertEquals(expected, actualBuilder.build());
+ }
+
public void testCustomJsonName() throws Exception {
TestCustomJsonName message = TestCustomJsonName.newBuilder().setValue(12345).build();
assertEquals("{\n" + " \"@value\": 12345\n" + "}", JsonFormat.printer().print(message));
@@ -1441,6 +1449,13 @@ public class JsonFormatTest extends TestCase {
assertEquals(54321, builder.getOptionalInt32());
}
+ public void testPrintingEnumsAsInts() throws Exception {
+ TestAllTypes message = TestAllTypes.newBuilder().setOptionalNestedEnum(NestedEnum.BAR).build();
+ assertEquals(
+ "{\n" + " \"optionalNestedEnum\": 1\n" + "}",
+ JsonFormat.printer().printingEnumsAsInts().print(message));
+ }
+
public void testOmittingInsignificantWhiteSpace() throws Exception {
TestAllTypes message = TestAllTypes.newBuilder().setOptionalInt32(12345).build();
assertEquals(
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_class_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_nano.proto
deleted file mode 100644
index 3a1e07f6..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_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: maxtroy@google.com (Max Cai)
-
-package protobuf_unittest;
-
-option java_package = "com.google.protobuf";
-option java_outer_classname = "EnumClassNanos";
-
-enum FileScopeEnum {
- ONE = 1;
-}
-
-message EnumClassNano {
- enum MessageScopeEnum {
- TWO = 2;
- }
- optional FileScopeEnum one = 1 [ default = ONE ];
- optional MessageScopeEnum two = 2 [ default = TWO ];
-}
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_multiple_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nano.proto
deleted file mode 100644
index 406ab774..00000000
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nano.proto
+++ /dev/null
@@ -1,63 +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_import;
-
-import "google/protobuf/nano/unittest_import_nano.proto";
-
-option java_package = "com.google.protobuf";
-option java_multiple_files = true;
-
-enum FileScopeEnum {
- ONE = 1;
- TWO = 2;
-}
-
-message FileScopeEnumRefNano {
- optional FileScopeEnum enum_field = 1;
-}
-
-message MessageScopeEnumRefNano {
- enum MessageScopeEnum {
- ONE = 1;
- TWO = 2;
- }
- optional MessageScopeEnum enum_field = 1;
-}
-
-message MultipleImportingNonMultipleNano1 {
- optional ImportMessageNano field = 1;
-}
-
-message MultipleImportingNonMultipleNano2 {
- optional MultipleImportingNonMultipleNano1 nano1 = 1;
-}
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/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/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_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/js/binary/arith.js b/js/binary/arith.js
index 70257de7..62528a26 100644
--- a/js/binary/arith.js
+++ b/js/binary/arith.js
@@ -221,7 +221,7 @@ jspb.arith.UInt64.prototype.mul = function(a) {
* Divide a 64-bit number by a 32-bit number to produce a
* 64-bit quotient and a 32-bit remainder.
* @param {number} _divisor
- * @return {Array.<jspb.arith.UInt64>} array of [quotient, remainder],
+ * @return {Array<jspb.arith.UInt64>} array of [quotient, remainder],
* unless divisor is 0, in which case an empty array is returned.
*/
jspb.arith.UInt64.prototype.div = function(_divisor) {
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 4ec3cada..e33bf1be 100644
--- a/js/binary/decoder.js
+++ b/js/binary/decoder.js
@@ -58,7 +58,7 @@ goog.require('jspb.utils');
* @param {?jspb.BinaryDecoder=} opt_decoder
* @param {?function(this:jspb.BinaryDecoder):(number|boolean|string)=}
* opt_next The decoder method to use for next().
- * @param {?Array.<number|boolean|string>=} opt_elements
+ * @param {?Array<number|boolean|string>=} opt_elements
* @constructor
* @struct
*/
@@ -92,7 +92,7 @@ jspb.BinaryIterator = function(opt_decoder, opt_next, opt_elements) {
* @param {?jspb.BinaryDecoder=} opt_decoder
* @param {?function(this:jspb.BinaryDecoder):(number|boolean|string)=}
* opt_next The decoder method to use for next().
- * @param {?Array.<number|boolean|string>=} opt_elements
+ * @param {?Array<number|boolean|string>=} opt_elements
* @private
*/
jspb.BinaryIterator.prototype.init_ =
@@ -112,7 +112,7 @@ jspb.BinaryIterator.prototype.init_ =
/**
* Global pool of BinaryIterator instances.
- * @private {!Array.<!jspb.BinaryIterator>}
+ * @private {!Array<!jspb.BinaryIterator>}
*/
jspb.BinaryIterator.instanceCache_ = [];
@@ -123,7 +123,7 @@ jspb.BinaryIterator.instanceCache_ = [];
* @param {?jspb.BinaryDecoder=} opt_decoder
* @param {?function(this:jspb.BinaryDecoder):(number|boolean|string)=}
* opt_next The decoder method to use for next().
- * @param {?Array.<number|boolean|string>=} opt_elements
+ * @param {?Array<number|boolean|string>=} opt_elements
* @return {!jspb.BinaryIterator}
*/
jspb.BinaryIterator.alloc = function(opt_decoder, opt_next, opt_elements) {
@@ -274,7 +274,7 @@ jspb.BinaryDecoder = function(opt_bytes, opt_start, opt_length) {
/**
* Global pool of BinaryDecoder instances.
- * @private {!Array.<!jspb.BinaryDecoder>}
+ * @private {!Array<!jspb.BinaryDecoder>}
*/
jspb.BinaryDecoder.instanceCache_ = [];
@@ -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/encoder.js b/js/binary/encoder.js
index 8e9f5bbc..b2013f63 100644
--- a/js/binary/encoder.js
+++ b/js/binary/encoder.js
@@ -51,7 +51,7 @@ goog.require('jspb.utils');
* @struct
*/
jspb.BinaryEncoder = function() {
- /** @private {!Array.<number>} */
+ /** @private {!Array<number>} */
this.buffer_ = [];
};
@@ -65,7 +65,7 @@ jspb.BinaryEncoder.prototype.length = function() {
/**
- * @return {!Array.<number>}
+ * @return {!Array<number>}
*/
jspb.BinaryEncoder.prototype.end = function() {
var buffer = this.buffer_;
diff --git a/js/binary/reader.js b/js/binary/reader.js
index d5d698f7..2dc3eb70 100644
--- a/js/binary/reader.js
+++ b/js/binary/reader.js
@@ -97,7 +97,7 @@ jspb.BinaryReader = function(opt_bytes, opt_start, opt_length) {
/**
* User-defined reader callbacks.
- * @private {Object.<string, function(!jspb.BinaryReader):*>}
+ * @private {Object<string, function(!jspb.BinaryReader):*>}
*/
this.readCallbacks_ = null;
};
@@ -105,7 +105,7 @@ jspb.BinaryReader = function(opt_bytes, opt_start, opt_length) {
/**
* Global pool of BinaryReader instances.
- * @private {!Array.<!jspb.BinaryReader>}
+ * @private {!Array<!jspb.BinaryReader>}
*/
jspb.BinaryReader.instanceCache_ = [];
@@ -992,7 +992,7 @@ jspb.BinaryReader.prototype.readPackedField_ = function(decodeMethod) {
/**
* Reads a packed int32 field, which consists of a length header and a list of
* signed varints.
- * @return {!Array.<number>}
+ * @return {!Array<number>}
*/
jspb.BinaryReader.prototype.readPackedInt32 = function() {
return this.readPackedField_(this.decoder_.readSignedVarint32);
@@ -1002,7 +1002,7 @@ jspb.BinaryReader.prototype.readPackedInt32 = function() {
/**
* Reads a packed int32 field, which consists of a length header and a list of
* signed varints. Returns a list of strings.
- * @return {!Array.<string>}
+ * @return {!Array<string>}
*/
jspb.BinaryReader.prototype.readPackedInt32String = function() {
return this.readPackedField_(this.decoder_.readSignedVarint32String);
@@ -1012,7 +1012,7 @@ jspb.BinaryReader.prototype.readPackedInt32String = function() {
/**
* Reads a packed int64 field, which consists of a length header and a list of
* signed varints.
- * @return {!Array.<number>}
+ * @return {!Array<number>}
*/
jspb.BinaryReader.prototype.readPackedInt64 = function() {
return this.readPackedField_(this.decoder_.readSignedVarint64);
@@ -1022,7 +1022,7 @@ jspb.BinaryReader.prototype.readPackedInt64 = function() {
/**
* Reads a packed int64 field, which consists of a length header and a list of
* signed varints. Returns a list of strings.
- * @return {!Array.<string>}
+ * @return {!Array<string>}
*/
jspb.BinaryReader.prototype.readPackedInt64String = function() {
return this.readPackedField_(this.decoder_.readSignedVarint64String);
@@ -1032,7 +1032,7 @@ jspb.BinaryReader.prototype.readPackedInt64String = function() {
/**
* Reads a packed uint32 field, which consists of a length header and a list of
* unsigned varints.
- * @return {!Array.<number>}
+ * @return {!Array<number>}
*/
jspb.BinaryReader.prototype.readPackedUint32 = function() {
return this.readPackedField_(this.decoder_.readUnsignedVarint32);
@@ -1042,7 +1042,7 @@ jspb.BinaryReader.prototype.readPackedUint32 = function() {
/**
* Reads a packed uint32 field, which consists of a length header and a list of
* unsigned varints. Returns a list of strings.
- * @return {!Array.<string>}
+ * @return {!Array<string>}
*/
jspb.BinaryReader.prototype.readPackedUint32String = function() {
return this.readPackedField_(this.decoder_.readUnsignedVarint32String);
@@ -1052,7 +1052,7 @@ jspb.BinaryReader.prototype.readPackedUint32String = function() {
/**
* Reads a packed uint64 field, which consists of a length header and a list of
* unsigned varints.
- * @return {!Array.<number>}
+ * @return {!Array<number>}
*/
jspb.BinaryReader.prototype.readPackedUint64 = function() {
return this.readPackedField_(this.decoder_.readUnsignedVarint64);
@@ -1062,7 +1062,7 @@ jspb.BinaryReader.prototype.readPackedUint64 = function() {
/**
* Reads a packed uint64 field, which consists of a length header and a list of
* unsigned varints. Returns a list of strings.
- * @return {!Array.<string>}
+ * @return {!Array<string>}
*/
jspb.BinaryReader.prototype.readPackedUint64String = function() {
return this.readPackedField_(this.decoder_.readUnsignedVarint64String);
@@ -1072,7 +1072,7 @@ jspb.BinaryReader.prototype.readPackedUint64String = function() {
/**
* Reads a packed sint32 field, which consists of a length header and a list of
* zigzag varints.
- * @return {!Array.<number>}
+ * @return {!Array<number>}
*/
jspb.BinaryReader.prototype.readPackedSint32 = function() {
return this.readPackedField_(this.decoder_.readZigzagVarint32);
@@ -1082,7 +1082,7 @@ jspb.BinaryReader.prototype.readPackedSint32 = function() {
/**
* Reads a packed sint64 field, which consists of a length header and a list of
* zigzag varints.
- * @return {!Array.<number>}
+ * @return {!Array<number>}
*/
jspb.BinaryReader.prototype.readPackedSint64 = function() {
return this.readPackedField_(this.decoder_.readZigzagVarint64);
@@ -1092,7 +1092,7 @@ jspb.BinaryReader.prototype.readPackedSint64 = function() {
/**
* Reads a packed sint64 field, which consists of a length header and a list of
* zigzag varints. Returns a list of strings.
- * @return {!Array.<string>}
+ * @return {!Array<string>}
*/
jspb.BinaryReader.prototype.readPackedSint64String = function() {
return this.readPackedField_(this.decoder_.readZigzagVarint64String);
@@ -1102,7 +1102,7 @@ jspb.BinaryReader.prototype.readPackedSint64String = function() {
/**
* Reads a packed fixed32 field, which consists of a length header and a list
* of unsigned 32-bit ints.
- * @return {!Array.<number>}
+ * @return {!Array<number>}
*/
jspb.BinaryReader.prototype.readPackedFixed32 = function() {
return this.readPackedField_(this.decoder_.readUint32);
@@ -1112,7 +1112,7 @@ jspb.BinaryReader.prototype.readPackedFixed32 = function() {
/**
* Reads a packed fixed64 field, which consists of a length header and a list
* of unsigned 64-bit ints.
- * @return {!Array.<number>}
+ * @return {!Array<number>}
*/
jspb.BinaryReader.prototype.readPackedFixed64 = function() {
return this.readPackedField_(this.decoder_.readUint64);
@@ -1122,7 +1122,7 @@ jspb.BinaryReader.prototype.readPackedFixed64 = function() {
/**
* Reads a packed fixed64 field, which consists of a length header and a list
* of unsigned 64-bit ints. Returns a list of strings.
- * @return {!Array.<number>}
+ * @return {!Array<number>}
*/
jspb.BinaryReader.prototype.readPackedFixed64String = function() {
return this.readPackedField_(this.decoder_.readUint64String);
@@ -1132,7 +1132,7 @@ jspb.BinaryReader.prototype.readPackedFixed64String = function() {
/**
* Reads a packed sfixed32 field, which consists of a length header and a list
* of 32-bit ints.
- * @return {!Array.<number>}
+ * @return {!Array<number>}
*/
jspb.BinaryReader.prototype.readPackedSfixed32 = function() {
return this.readPackedField_(this.decoder_.readInt32);
@@ -1142,7 +1142,7 @@ jspb.BinaryReader.prototype.readPackedSfixed32 = function() {
/**
* Reads a packed sfixed64 field, which consists of a length header and a list
* of 64-bit ints.
- * @return {!Array.<number>}
+ * @return {!Array<number>}
*/
jspb.BinaryReader.prototype.readPackedSfixed64 = function() {
return this.readPackedField_(this.decoder_.readInt64);
@@ -1152,7 +1152,7 @@ jspb.BinaryReader.prototype.readPackedSfixed64 = function() {
/**
* Reads a packed sfixed64 field, which consists of a length header and a list
* of 64-bit ints. Returns a list of strings.
- * @return {!Array.<string>}
+ * @return {!Array<string>}
*/
jspb.BinaryReader.prototype.readPackedSfixed64String = function() {
return this.readPackedField_(this.decoder_.readInt64String);
@@ -1162,7 +1162,7 @@ jspb.BinaryReader.prototype.readPackedSfixed64String = function() {
/**
* Reads a packed float field, which consists of a length header and a list of
* floats.
- * @return {!Array.<number>}
+ * @return {!Array<number>}
*/
jspb.BinaryReader.prototype.readPackedFloat = function() {
return this.readPackedField_(this.decoder_.readFloat);
@@ -1172,7 +1172,7 @@ jspb.BinaryReader.prototype.readPackedFloat = function() {
/**
* Reads a packed double field, which consists of a length header and a list of
* doubles.
- * @return {!Array.<number>}
+ * @return {!Array<number>}
*/
jspb.BinaryReader.prototype.readPackedDouble = function() {
return this.readPackedField_(this.decoder_.readDouble);
@@ -1182,7 +1182,7 @@ jspb.BinaryReader.prototype.readPackedDouble = function() {
/**
* Reads a packed bool field, which consists of a length header and a list of
* unsigned varints.
- * @return {!Array.<boolean>}
+ * @return {!Array<boolean>}
*/
jspb.BinaryReader.prototype.readPackedBool = function() {
return this.readPackedField_(this.decoder_.readBool);
@@ -1192,7 +1192,7 @@ jspb.BinaryReader.prototype.readPackedBool = function() {
/**
* Reads a packed enum field, which consists of a length header and a list of
* unsigned varints.
- * @return {!Array.<number>}
+ * @return {!Array<number>}
*/
jspb.BinaryReader.prototype.readPackedEnum = function() {
return this.readPackedField_(this.decoder_.readEnum);
@@ -1202,7 +1202,7 @@ jspb.BinaryReader.prototype.readPackedEnum = function() {
/**
* Reads a packed varint hash64 field, which consists of a length header and a
* list of varint hash64s.
- * @return {!Array.<string>}
+ * @return {!Array<string>}
*/
jspb.BinaryReader.prototype.readPackedVarintHash64 = function() {
return this.readPackedField_(this.decoder_.readVarintHash64);
@@ -1212,7 +1212,7 @@ jspb.BinaryReader.prototype.readPackedVarintHash64 = function() {
/**
* Reads a packed fixed hash64 field, which consists of a length header and a
* list of fixed hash64s.
- * @return {!Array.<string>}
+ * @return {!Array<string>}
*/
jspb.BinaryReader.prototype.readPackedFixedHash64 = function() {
return this.readPackedField_(this.decoder_.readFixedHash64);
diff --git a/js/binary/utils.js b/js/binary/utils.js
index c706bff4..55a9ccd4 100644
--- a/js/binary/utils.js
+++ b/js/binary/utils.js
@@ -431,7 +431,7 @@ jspb.utils.joinHash64 = function(bitsLow, bitsHigh) {
/**
* Individual digits for number->string conversion.
- * @const {!Array.<string>}
+ * @const {!Array<string>}
*/
jspb.utils.DIGITS = [
'0', '1', '2', '3', '4', '5', '6', '7',
@@ -554,10 +554,10 @@ jspb.utils.hash64ToDecimalString = function(hash, signed) {
/**
* Converts an array of 8-character hash strings into their decimal
* representations.
- * @param {!Array.<string>} hashes The array of hash strings to convert.
+ * @param {!Array<string>} hashes The array of hash strings to convert.
* @param {boolean} signed True if we should treat the hash string as encoding
* a signed integer.
- * @return {!Array.<string>}
+ * @return {!Array<string>}
*/
jspb.utils.hash64ArrayToDecimalStrings = function(hashes, signed) {
var result = new Array(hashes.length);
@@ -971,8 +971,12 @@ 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);
+ data = /** @type {!Array<number>} */(data);
return /** @type {!Uint8Array} */(new Uint8Array(data));
}
diff --git a/js/binary/utils_test.js b/js/binary/utils_test.js
index 6b481dce..13450644 100644
--- a/js/binary/utils_test.js
+++ b/js/binary/utils_test.js
@@ -657,7 +657,7 @@ describe('binaryUtilsTest', function() {
// Converting Uint8Arrays into Uint8Arrays should be a no-op.
assertEquals(sourceBytes, convert(sourceBytes));
- // Converting Array.<numbers> into Uint8Arrays should work.
+ // Converting Array<numbers> into Uint8Arrays should work.
check(convert(sourceData));
// Converting ArrayBuffers into Uint8Arrays should work.
diff --git a/js/binary/writer.js b/js/binary/writer.js
index 037e92b2..287d29c3 100644
--- a/js/binary/writer.js
+++ b/js/binary/writer.js
@@ -102,7 +102,7 @@ jspb.BinaryWriter = function() {
* A stack of bookmarks containing the parent blocks for each message started
* via beginSubMessage(), needed as bookkeeping for endSubMessage().
* TODO(aappleby): Deprecated, users should be calling writeMessage().
- * @private {!Array.<!Array.<number>>}
+ * @private {!Array<!Array<number>>}
*/
this.bookmarks_ = [];
};
@@ -126,7 +126,7 @@ jspb.BinaryWriter.prototype.appendUint8Array_ = function(arr) {
* Begins a new message by writing the field header and returning a bookmark
* which we will use to patch in the message length to in endDelimited_ below.
* @param {number} field
- * @return {!Array.<number>}
+ * @return {!Array<number>}
* @private
*/
jspb.BinaryWriter.prototype.beginDelimited_ = function(field) {
@@ -143,7 +143,7 @@ jspb.BinaryWriter.prototype.beginDelimited_ = function(field) {
* Ends a message by encoding the _change_ in length of the buffer to the
* parent block and adds the number of bytes needed to encode that length to
* the total byte length.
- * @param {!Array.<number>} bookmark
+ * @param {!Array<number>} bookmark
* @private
*/
jspb.BinaryWriter.prototype.endDelimited_ = function(bookmark) {
@@ -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);
};
@@ -855,7 +857,7 @@ jspb.BinaryWriter.prototype.writeVarintHash64 = function(field, value) {
/**
* Writes an array of numbers to the buffer as a repeated 32-bit int field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedInt32 = function(field, value) {
if (value == null) return;
@@ -869,7 +871,7 @@ jspb.BinaryWriter.prototype.writeRepeatedInt32 = function(field, value) {
* Writes an array of numbers formatted as strings to the buffer as a repeated
* 32-bit int field.
* @param {number} field The field number.
- * @param {?Array.<string>} value The array of ints to write.
+ * @param {?Array<string>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedInt32String = function(field, value) {
if (value == null) return;
@@ -882,7 +884,7 @@ jspb.BinaryWriter.prototype.writeRepeatedInt32String = function(field, value) {
/**
* Writes an array of numbers to the buffer as a repeated 64-bit int field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedInt64 = function(field, value) {
if (value == null) return;
@@ -896,7 +898,7 @@ jspb.BinaryWriter.prototype.writeRepeatedInt64 = function(field, value) {
* Writes an array of numbers formatted as strings to the buffer as a repeated
* 64-bit int field.
* @param {number} field The field number.
- * @param {?Array.<string>} value The array of ints to write.
+ * @param {?Array<string>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedInt64String = function(field, value) {
if (value == null) return;
@@ -910,7 +912,7 @@ jspb.BinaryWriter.prototype.writeRepeatedInt64String = function(field, value) {
* Writes an array numbers to the buffer as a repeated unsigned 32-bit int
* field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedUint32 = function(field, value) {
if (value == null) return;
@@ -924,7 +926,7 @@ jspb.BinaryWriter.prototype.writeRepeatedUint32 = function(field, value) {
* Writes an array of numbers formatted as strings to the buffer as a repeated
* unsigned 32-bit int field.
* @param {number} field The field number.
- * @param {?Array.<string>} value The array of ints to write.
+ * @param {?Array<string>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedUint32String = function(field, value) {
if (value == null) return;
@@ -938,7 +940,7 @@ jspb.BinaryWriter.prototype.writeRepeatedUint32String = function(field, value) {
* Writes an array numbers to the buffer as a repeated unsigned 64-bit int
* field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedUint64 = function(field, value) {
if (value == null) return;
@@ -952,7 +954,7 @@ jspb.BinaryWriter.prototype.writeRepeatedUint64 = function(field, value) {
* Writes an array of numbers formatted as strings to the buffer as a repeated
* unsigned 64-bit int field.
* @param {number} field The field number.
- * @param {?Array.<string>} value The array of ints to write.
+ * @param {?Array<string>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedUint64String = function(field, value) {
if (value == null) return;
@@ -965,7 +967,7 @@ jspb.BinaryWriter.prototype.writeRepeatedUint64String = function(field, value) {
/**
* Writes an array numbers to the buffer as a repeated signed 32-bit int field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedSint32 = function(field, value) {
if (value == null) return;
@@ -978,7 +980,7 @@ jspb.BinaryWriter.prototype.writeRepeatedSint32 = function(field, value) {
/**
* Writes an array numbers to the buffer as a repeated signed 64-bit int field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedSint64 = function(field, value) {
if (value == null) return;
@@ -991,7 +993,7 @@ jspb.BinaryWriter.prototype.writeRepeatedSint64 = function(field, value) {
/**
* Writes an array numbers to the buffer as a repeated signed 64-bit int field.
* @param {number} field The field number.
- * @param {?Array.<string>} value The array of ints to write.
+ * @param {?Array<string>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedSint64String = function(field, value) {
if (value == null) return;
@@ -1005,7 +1007,7 @@ jspb.BinaryWriter.prototype.writeRepeatedSint64String = function(field, value) {
* Writes an array of numbers to the buffer as a repeated fixed32 field. This
* works for both signed and unsigned fixed32s.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedFixed32 = function(field, value) {
if (value == null) return;
@@ -1019,7 +1021,7 @@ jspb.BinaryWriter.prototype.writeRepeatedFixed32 = function(field, value) {
* Writes an array of numbers to the buffer as a repeated fixed64 field. This
* works for both signed and unsigned fixed64s.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedFixed64 = function(field, value) {
if (value == null) return;
@@ -1033,7 +1035,7 @@ jspb.BinaryWriter.prototype.writeRepeatedFixed64 = function(field, value) {
* Writes an array of numbers to the buffer as a repeated fixed64 field. This
* works for both signed and unsigned fixed64s.
* @param {number} field The field number.
- * @param {?Array.<string>} value The array of decimal strings to write.
+ * @param {?Array<string>} value The array of decimal strings to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedFixed64String = function(
field, value) {
@@ -1047,7 +1049,7 @@ jspb.BinaryWriter.prototype.writeRepeatedFixed64String = function(
/**
* Writes an array of numbers to the buffer as a repeated sfixed32 field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedSfixed32 = function(field, value) {
if (value == null) return;
@@ -1060,7 +1062,7 @@ jspb.BinaryWriter.prototype.writeRepeatedSfixed32 = function(field, value) {
/**
* Writes an array of numbers to the buffer as a repeated sfixed64 field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedSfixed64 = function(field, value) {
if (value == null) return;
@@ -1074,7 +1076,7 @@ jspb.BinaryWriter.prototype.writeRepeatedSfixed64 = function(field, value) {
* Writes an array of decimal strings to the buffer as a repeated sfixed64
* field.
* @param {number} field The field number.
- * @param {?Array.<string>} value The array of decimal strings to write.
+ * @param {?Array<string>} value The array of decimal strings to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedSfixed64String = function(field, value) {
if (value == null) return;
@@ -1087,7 +1089,7 @@ jspb.BinaryWriter.prototype.writeRepeatedSfixed64String = function(field, value)
/**
* Writes an array of numbers to the buffer as a repeated float field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedFloat = function(field, value) {
if (value == null) return;
@@ -1100,7 +1102,7 @@ jspb.BinaryWriter.prototype.writeRepeatedFloat = function(field, value) {
/**
* Writes an array of numbers to the buffer as a repeated double field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedDouble = function(field, value) {
if (value == null) return;
@@ -1113,7 +1115,7 @@ jspb.BinaryWriter.prototype.writeRepeatedDouble = function(field, value) {
/**
* Writes an array of booleans to the buffer as a repeated bool field.
* @param {number} field The field number.
- * @param {?Array.<boolean>} value The array of ints to write.
+ * @param {?Array<boolean>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedBool = function(field, value) {
if (value == null) return;
@@ -1126,7 +1128,7 @@ jspb.BinaryWriter.prototype.writeRepeatedBool = function(field, value) {
/**
* Writes an array of enums to the buffer as a repeated enum field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedEnum = function(field, value) {
if (value == null) return;
@@ -1139,7 +1141,7 @@ jspb.BinaryWriter.prototype.writeRepeatedEnum = function(field, value) {
/**
* Writes an array of strings to the buffer as a repeated string field.
* @param {number} field The field number.
- * @param {?Array.<string>} value The array of strings to write.
+ * @param {?Array<string>} value The array of strings to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedString = function(field, value) {
if (value == null) return;
@@ -1152,7 +1154,7 @@ jspb.BinaryWriter.prototype.writeRepeatedString = function(field, value) {
/**
* Writes an array of arbitrary byte fields to the buffer.
* @param {number} field The field number.
- * @param {?Array.<!jspb.ByteSource>} value The arrays of arrays of bytes to
+ * @param {?Array<!jspb.ByteSource>} value The arrays of arrays of bytes to
* write.
*/
jspb.BinaryWriter.prototype.writeRepeatedBytes = function(field, value) {
@@ -1167,7 +1169,7 @@ jspb.BinaryWriter.prototype.writeRepeatedBytes = function(field, value) {
* Writes an array of messages to the buffer.
* @template MessageType
* @param {number} field The field number.
- * @param {?Array.<MessageType>} value The array of messages to
+ * @param {?Array<MessageType>} value The array of messages to
* write.
* @param {function(MessageType, !jspb.BinaryWriter)} writerCallback
* Will be invoked with the value to write and the writer to write it with.
@@ -1187,7 +1189,7 @@ jspb.BinaryWriter.prototype.writeRepeatedMessage = function(
* Writes an array of group messages to the buffer.
* @template MessageType
* @param {number} field The field number.
- * @param {?Array.<MessageType>} value The array of messages to
+ * @param {?Array<MessageType>} value The array of messages to
* write.
* @param {function(MessageType, !jspb.BinaryWriter)} writerCallback
* Will be invoked with the value to write and the writer to write it with.
@@ -1207,7 +1209,7 @@ jspb.BinaryWriter.prototype.writeRepeatedGroup = function(
* Writes a 64-bit hash string field (8 characters @ 8 bits of data each) to
* the buffer.
* @param {number} field The field number.
- * @param {?Array.<string>} value The array of hashes to write.
+ * @param {?Array<string>} value The array of hashes to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedFixedHash64 =
function(field, value) {
@@ -1222,7 +1224,7 @@ jspb.BinaryWriter.prototype.writeRepeatedFixedHash64 =
* Writes a repeated 64-bit hash string field (8 characters @ 8 bits of data
* each) to the buffer.
* @param {number} field The field number.
- * @param {?Array.<string>} value The array of hashes to write.
+ * @param {?Array<string>} value The array of hashes to write.
*/
jspb.BinaryWriter.prototype.writeRepeatedVarintHash64 =
function(field, value) {
@@ -1236,7 +1238,7 @@ jspb.BinaryWriter.prototype.writeRepeatedVarintHash64 =
/**
* Writes an array of numbers to the buffer as a packed 32-bit int field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writePackedInt32 = function(field, value) {
if (value == null || !value.length) return;
@@ -1252,7 +1254,7 @@ jspb.BinaryWriter.prototype.writePackedInt32 = function(field, value) {
* Writes an array of numbers represented as strings to the buffer as a packed
* 32-bit int field.
* @param {number} field
- * @param {?Array.<string>} value
+ * @param {?Array<string>} value
*/
jspb.BinaryWriter.prototype.writePackedInt32String = function(field, value) {
if (value == null || !value.length) return;
@@ -1267,7 +1269,7 @@ jspb.BinaryWriter.prototype.writePackedInt32String = function(field, value) {
/**
* Writes an array of numbers to the buffer as a packed 64-bit int field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writePackedInt64 = function(field, value) {
if (value == null || !value.length) return;
@@ -1283,7 +1285,7 @@ jspb.BinaryWriter.prototype.writePackedInt64 = function(field, value) {
* Writes an array of numbers represented as strings to the buffer as a packed
* 64-bit int field.
* @param {number} field
- * @param {?Array.<string>} value
+ * @param {?Array<string>} value
*/
jspb.BinaryWriter.prototype.writePackedInt64String = function(field, value) {
if (value == null || !value.length) return;
@@ -1299,7 +1301,7 @@ jspb.BinaryWriter.prototype.writePackedInt64String = function(field, value) {
/**
* Writes an array numbers to the buffer as a packed unsigned 32-bit int field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writePackedUint32 = function(field, value) {
if (value == null || !value.length) return;
@@ -1315,7 +1317,7 @@ jspb.BinaryWriter.prototype.writePackedUint32 = function(field, value) {
* Writes an array of numbers represented as strings to the buffer as a packed
* unsigned 32-bit int field.
* @param {number} field
- * @param {?Array.<string>} value
+ * @param {?Array<string>} value
*/
jspb.BinaryWriter.prototype.writePackedUint32String =
function(field, value) {
@@ -1331,7 +1333,7 @@ jspb.BinaryWriter.prototype.writePackedUint32String =
/**
* Writes an array numbers to the buffer as a packed unsigned 64-bit int field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writePackedUint64 = function(field, value) {
if (value == null || !value.length) return;
@@ -1347,7 +1349,7 @@ jspb.BinaryWriter.prototype.writePackedUint64 = function(field, value) {
* Writes an array of numbers represented as strings to the buffer as a packed
* unsigned 64-bit int field.
* @param {number} field
- * @param {?Array.<string>} value
+ * @param {?Array<string>} value
*/
jspb.BinaryWriter.prototype.writePackedUint64String =
function(field, value) {
@@ -1364,7 +1366,7 @@ jspb.BinaryWriter.prototype.writePackedUint64String =
/**
* Writes an array numbers to the buffer as a packed signed 32-bit int field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writePackedSint32 = function(field, value) {
if (value == null || !value.length) return;
@@ -1379,7 +1381,7 @@ jspb.BinaryWriter.prototype.writePackedSint32 = function(field, value) {
/**
* Writes an array of numbers to the buffer as a packed signed 64-bit int field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writePackedSint64 = function(field, value) {
if (value == null || !value.length) return;
@@ -1395,7 +1397,7 @@ jspb.BinaryWriter.prototype.writePackedSint64 = function(field, value) {
* Writes an array of decimal strings to the buffer as a packed signed 64-bit
* int field.
* @param {number} field The field number.
- * @param {?Array.<string>} value The array of decimal strings to write.
+ * @param {?Array<string>} value The array of decimal strings to write.
*/
jspb.BinaryWriter.prototype.writePackedSint64String = function(field, value) {
if (value == null || !value.length) return;
@@ -1411,7 +1413,7 @@ jspb.BinaryWriter.prototype.writePackedSint64String = function(field, value) {
/**
* Writes an array of numbers to the buffer as a packed fixed32 field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writePackedFixed32 = function(field, value) {
if (value == null || !value.length) return;
@@ -1426,7 +1428,7 @@ jspb.BinaryWriter.prototype.writePackedFixed32 = function(field, value) {
/**
* Writes an array of numbers to the buffer as a packed fixed64 field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writePackedFixed64 = function(field, value) {
if (value == null || !value.length) return;
@@ -1442,7 +1444,7 @@ jspb.BinaryWriter.prototype.writePackedFixed64 = function(field, value) {
* Writes an array of numbers represented as strings to the buffer as a packed
* fixed64 field.
* @param {number} field The field number.
- * @param {?Array.<string>} value The array of strings to write.
+ * @param {?Array<string>} value The array of strings to write.
*/
jspb.BinaryWriter.prototype.writePackedFixed64String = function(field, value) {
if (value == null || !value.length) return;
@@ -1458,7 +1460,7 @@ jspb.BinaryWriter.prototype.writePackedFixed64String = function(field, value) {
/**
* Writes an array of numbers to the buffer as a packed sfixed32 field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writePackedSfixed32 = function(field, value) {
if (value == null || !value.length) return;
@@ -1473,7 +1475,7 @@ jspb.BinaryWriter.prototype.writePackedSfixed32 = function(field, value) {
/**
* Writes an array of numbers to the buffer as a packed sfixed64 field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writePackedSfixed64 = function(field, value) {
if (value == null || !value.length) return;
@@ -1488,7 +1490,7 @@ jspb.BinaryWriter.prototype.writePackedSfixed64 = function(field, value) {
/**
* Writes an array of numbers to the buffer as a packed sfixed64 field.
* @param {number} field The field number.
- * @param {?Array.<string>} value The array of decimal strings to write.
+ * @param {?Array<string>} value The array of decimal strings to write.
*/
jspb.BinaryWriter.prototype.writePackedSfixed64String = function(field, value) {
if (value == null || !value.length) return;
@@ -1503,7 +1505,7 @@ jspb.BinaryWriter.prototype.writePackedSfixed64String = function(field, value) {
/**
* Writes an array of numbers to the buffer as a packed float field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writePackedFloat = function(field, value) {
if (value == null || !value.length) return;
@@ -1518,7 +1520,7 @@ jspb.BinaryWriter.prototype.writePackedFloat = function(field, value) {
/**
* Writes an array of numbers to the buffer as a packed double field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writePackedDouble = function(field, value) {
if (value == null || !value.length) return;
@@ -1533,7 +1535,7 @@ jspb.BinaryWriter.prototype.writePackedDouble = function(field, value) {
/**
* Writes an array of booleans to the buffer as a packed bool field.
* @param {number} field The field number.
- * @param {?Array.<boolean>} value The array of ints to write.
+ * @param {?Array<boolean>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writePackedBool = function(field, value) {
if (value == null || !value.length) return;
@@ -1548,7 +1550,7 @@ jspb.BinaryWriter.prototype.writePackedBool = function(field, value) {
/**
* Writes an array of enums to the buffer as a packed enum field.
* @param {number} field The field number.
- * @param {?Array.<number>} value The array of ints to write.
+ * @param {?Array<number>} value The array of ints to write.
*/
jspb.BinaryWriter.prototype.writePackedEnum = function(field, value) {
if (value == null || !value.length) return;
@@ -1564,7 +1566,7 @@ jspb.BinaryWriter.prototype.writePackedEnum = function(field, value) {
* Writes a 64-bit hash string field (8 characters @ 8 bits of data each) to
* the buffer.
* @param {number} field The field number.
- * @param {?Array.<string>} value The array of hashes to write.
+ * @param {?Array<string>} value The array of hashes to write.
*/
jspb.BinaryWriter.prototype.writePackedFixedHash64 = function(field, value) {
if (value == null || !value.length) return;
@@ -1580,7 +1582,7 @@ jspb.BinaryWriter.prototype.writePackedFixedHash64 = function(field, value) {
* Writes a 64-bit hash string field (8 characters @ 8 bits of data each) to
* the buffer.
* @param {number} field The field number.
- * @param {?Array.<string>} value The array of hashes to write.
+ * @param {?Array<string>} value The array of hashes to write.
*/
jspb.BinaryWriter.prototype.writePackedVarintHash64 = function(field, value) {
if (value == null || !value.length) return;
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/js/commonjs/export_testdeps.js b/js/commonjs/export_testdeps.js
index 6f5cd083..96d3f347 100644
--- a/js/commonjs/export_testdeps.js
+++ b/js/commonjs/export_testdeps.js
@@ -12,6 +12,7 @@
goog.provide('jspb.ExportTestDeps');
goog.require('goog.crypt.base64');
+goog.require('goog.testing.PropertyReplacer');
goog.require('jspb.arith.Int64');
goog.require('jspb.arith.UInt64');
goog.require('jspb.BinaryEncoder');
diff --git a/js/debug.js b/js/debug.js
index 46b24853..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
@@ -74,15 +74,22 @@ jspb.debug.dump = function(message) {
*/
jspb.debug.dump_ = function(thing) {
var type = goog.typeOf(thing);
+ var message = thing; // Copy because we don't want type inference on thing.
if (type == 'number' || type == 'string' || type == 'boolean' ||
type == 'null' || type == 'undefined') {
return thing;
}
+ if (typeof Uint8Array !== 'undefined') {
+ // Will fail on IE9, where Uint8Array doesn't exist.
+ if (message instanceof Uint8Array) {
+ return thing;
+ }
+ }
+
if (type == 'array') {
goog.asserts.assertArray(thing);
return goog.array.map(thing, jspb.debug.dump_);
}
- var message = thing; // Copy because we don't want type inference on thing.
goog.asserts.assert(message instanceof jspb.Message,
'Only messages expected: ' + thing);
var ctor = message.constructor;
diff --git a/js/debug_test.js b/js/debug_test.js
index 702cc76e..d0d646a5 100644
--- a/js/debug_test.js
+++ b/js/debug_test.js
@@ -41,6 +41,8 @@ goog.require('proto.jspb.test.IsExtension');
goog.require('proto.jspb.test.Simple1');
+// CommonJS-LoadFromFile: testbinary_pb
+goog.require('proto.jspb.test.TestAllTypes');
describe('debugTest', function() {
it('testSimple1', function() {
@@ -74,6 +76,15 @@ describe('debugTest', function() {
}, jspb.debug.dump(message));
});
+ it('testBytes', function() {
+ if (COMPILED || typeof Uint8Array == 'undefined') {
+ return;
+ }
+ var message = new proto.jspb.test.TestAllTypes();
+ var bytes = new Uint8Array(4);
+ message.setOptionalBytes(bytes);
+ assertEquals(jspb.debug.dump(message)['optionalBytes'], bytes);
+ });
it('testExtensions', function() {
if (COMPILED) {
diff --git a/js/map.js b/js/map.js
index d423499f..7b5b2c38 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();
}
@@ -475,10 +476,13 @@ jspb.Map.deserializeBinary = function(map, reader, keyReaderFn, valueReaderFn,
} 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/message.js b/js/message.js
index 1484229d..86d18295 100644
--- a/js/message.js
+++ b/js/message.js
@@ -205,15 +205,14 @@ goog.define('jspb.Message.GENERATE_TO_STRING', true);
goog.define('jspb.Message.ASSUME_LOCAL_ARRAYS', false);
+// TODO(jakubvrana): Turn this off by default.
/**
- * @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.
+ * @define {boolean} Disabling the serialization of empty trailing fields
+ * reduces the size of serialized protos. The price is an extra iteration of
+ * the proto before serialization. This is enabled by default to be
+ * backwards compatible. Projects are advised to turn this flag always off.
*/
-goog.define('jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS', COMPILED);
-// TODO(b/19419436) Turn this on by default.
+goog.define('jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS', true);
/**
@@ -278,6 +277,13 @@ jspb.Message.prototype.convertedFloatingPointFields_;
/**
+ * Repeated fields numbers.
+ * @protected {?Array<number>|undefined}
+ */
+jspb.Message.prototype.repeatedFields;
+
+
+/**
* The xid of this proto type (The same for all instances of a proto). Provides
* a way to identify a proto by stable obfuscated name.
* @see {xid}.
@@ -324,6 +330,18 @@ jspb.Message.getIndex_ = function(msg, fieldNumber) {
/**
+ * Returns the tag number based on the index in msg.array.
+ * @param {!jspb.Message} msg Message for which we're calculating an index.
+ * @param {number} index The tag number.
+ * @return {number} The field number.
+ * @private
+ */
+jspb.Message.getFieldNumber_ = function(msg, index) {
+ return index - msg.arrayIndexOffset_;
+};
+
+
+/**
* Initializes a JsPb Message.
* @param {!jspb.Message} msg The JsPb proto to modify.
* @param {Array|undefined} data An initial data array.
@@ -340,7 +358,7 @@ jspb.Message.getIndex_ = function(msg, fieldNumber) {
*/
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] : [];
}
@@ -353,22 +371,24 @@ jspb.Message.initialize = function(
jspb.Message.initPivotAndExtensionObject_(msg, suggestedPivot);
msg.convertedFloatingPointFields_ = {};
+ if (!jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS) {
+ // TODO(jakubvrana): This is same for all instances, move to prototype.
+ // TODO(jakubvrana): There are indexOf calls on this in serializtion,
+ // consider switching to a set.
+ msg.repeatedFields = repeatedFields;
+ }
+
if (repeatedFields) {
for (var i = 0; i < repeatedFields.length; i++) {
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_;
}
}
}
@@ -376,8 +396,9 @@ jspb.Message.initialize = function(
if (opt_oneofFields && opt_oneofFields.length) {
// Compute the oneof case for each union. This ensures only one value is
// set in the union.
- goog.array.forEach(
- opt_oneofFields, goog.partial(jspb.Message.computeOneofCase, msg));
+ for (var i = 0; i < opt_oneofFields.length; i++) {
+ jspb.Message.computeOneofCase(msg, opt_oneofFields[i]);
+ }
}
};
@@ -428,7 +449,7 @@ jspb.Message.initPivotAndExtensionObject_ = function(msg, suggestedPivot) {
// in Safari on iOS 8. See the description of CL/86511464 for details.
if (obj && typeof obj == 'object' && !jspb.Message.isArray_(obj) &&
!(jspb.Message.SUPPORTS_UINT8ARRAY_ && obj instanceof Uint8Array)) {
- msg.pivot_ = foundIndex - msg.arrayIndexOffset_;
+ msg.pivot_ = jspb.Message.getFieldNumber_(msg, foundIndex);
msg.extensionObject_ = obj;
return;
}
@@ -480,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;
};
@@ -514,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));
}
}
}
@@ -902,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.
@@ -1043,14 +1075,15 @@ jspb.Message.computeOneofCase = function(msg, oneof) {
var oneofField;
var oneofValue;
- goog.array.forEach(oneof, function(fieldNumber) {
+ for (var i = 0; i < oneof.length; i++) {
+ var fieldNumber = oneof[i];
var value = jspb.Message.getField(msg, fieldNumber);
- if (goog.isDefAndNotNull(value)) {
+ if (value != null) {
oneofField = fieldNumber;
oneofValue = value;
jspb.Message.setField(msg, fieldNumber, undefined);
}
- });
+ }
if (oneofField) {
// NB: We know the value is unique, so we can call jspb.Message.setField
@@ -1241,7 +1274,7 @@ jspb.Message.addToRepeatedWrapperField = function(
* dead code removal.
* @param {boolean=} opt_includeInstance Whether to include the JSPB instance
* for transitional soy proto support: http://goto/soy-param-migration
- * @return {!Object.<string, Object>} A map of proto or Soy objects.
+ * @return {!Object<string, Object>} A map of proto or Soy objects.
* @template T
*/
jspb.Message.toMap = function(
@@ -1318,7 +1351,7 @@ jspb.Message.prototype.toString = function() {
/**
* Gets the value of the extension field from the extended object.
- * @param {jspb.ExtensionFieldInfo.<T>} fieldInfo Specifies the field to get.
+ * @param {jspb.ExtensionFieldInfo<T>} fieldInfo Specifies the field to get.
* @return {T} The value of the field.
* @template T
*/
@@ -1381,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 {
@@ -1390,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;
}
@@ -1492,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;
}
@@ -1517,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;
}
@@ -1657,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;
@@ -1668,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;
@@ -1685,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;
};
@@ -1705,7 +1760,11 @@ jspb.Message.registry_ = {};
* non-MessageSet. We special case MessageSet so that we do not need
* to goog.require MessageSet from classes that extends MessageSet.
*
- * @type {!Object.<number, jspb.ExtensionFieldInfo>}
+ * @type {!Object<number, jspb.ExtensionFieldInfo>}
*/
jspb.Message.messageSetExtensions = {};
+
+/**
+ * @type {!Object<number, jspb.ExtensionFieldBinaryInfo>}
+ */
jspb.Message.messageSetExtensionsBinary = {};
diff --git a/js/message_test.js b/js/message_test.js
index 7d61dacb..1be41093 100644
--- a/js/message_test.js
+++ b/js/message_test.js
@@ -34,6 +34,7 @@ goog.setTestOnly();
goog.require('goog.json');
goog.require('goog.string');
+goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.asserts');
goog.require('goog.userAgent');
@@ -85,6 +86,16 @@ goog.require('proto.jspb.test.TestExtensionsMessage');
describe('Message test suite', function() {
+ var stubs = new goog.testing.PropertyReplacer();
+
+ beforeEach(function() {
+ stubs.set(jspb.Message, 'SERIALIZE_EMPTY_TRAILING_FIELDS', false);
+ });
+
+ afterEach(function() {
+ stubs.reset();
+ });
+
it('testEmptyProto', function() {
var empty1 = new proto.jspb.test.Empty([]);
var empty2 = new proto.jspb.test.Empty([]);
@@ -407,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/jenkins/docker32/Dockerfile b/kokoro/linux/32-bit/Dockerfile
index 1278889f..1278889f 100644
--- a/jenkins/docker32/Dockerfile
+++ b/kokoro/linux/32-bit/Dockerfile
diff --git a/kokoro/linux/32-bit/build.sh b/kokoro/linux/32-bit/build.sh
new file mode 100755
index 00000000..04383a57
--- /dev/null
+++ b/kokoro/linux/32-bit/build.sh
@@ -0,0 +1,17 @@
+#!/bin/bash
+#
+# This is the top-level script we give to Kokoro as the entry point for
+# running the "pull request 32" 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/32-bit
+export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
+export OUTPUT_DIR=testoutput
+export TEST_SET="php_all_32"
+./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/32-bit/continuous.cfg b/kokoro/linux/32-bit/continuous.cfg
new file mode 100644
index 00000000..28b66c07
--- /dev/null
+++ b/kokoro/linux/32-bit/continuous.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/32-bit/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/32-bit/presubmit.cfg b/kokoro/linux/32-bit/presubmit.cfg
new file mode 100644
index 00000000..28b66c07
--- /dev/null
+++ b/kokoro/linux/32-bit/presubmit.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/32-bit/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/jenkins/docker/Dockerfile b/kokoro/linux/64-bit/Dockerfile
index 3a279e66..3a279e66 100644
--- a/jenkins/docker/Dockerfile
+++ b/kokoro/linux/64-bit/Dockerfile
diff --git a/jenkins/buildcmds/pull_request.sh b/kokoro/linux/64-bit/build.sh
index 51e4bfa4..48ddbce5 100755
--- a/jenkins/buildcmds/pull_request.sh
+++ b/kokoro/linux/64-bit/build.sh
@@ -1,16 +1,17 @@
#!/bin/bash
#
-# This is the top-level script we give to Jenkins as the entry point for
+# This is the top-level script we give to Kokoro 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
+# 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="csharp java_jdk7 javanano_jdk7 java_oracle7 javanano_oracle7 python python_cpp ruby_all javascript golang php_all"
-./jenkins/build_and_run_docker.sh
+./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/64-bit/continuous.cfg b/kokoro/linux/64-bit/continuous.cfg
new file mode 100644
index 00000000..3a4faac1
--- /dev/null
+++ b/kokoro/linux/64-bit/continuous.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/64-bit/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/64-bit/presubmit.cfg b/kokoro/linux/64-bit/presubmit.cfg
new file mode 100644
index 00000000..3a4faac1
--- /dev/null
+++ b/kokoro/linux/64-bit/presubmit.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/64-bit/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/benchmark/build.sh b/kokoro/linux/benchmark/build.sh
new file mode 100755
index 00000000..f29a16fd
--- /dev/null
+++ b/kokoro/linux/benchmark/build.sh
@@ -0,0 +1,88 @@
+#!/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" ./python-cpp-reflection-benchmark --json --behavior_prefix="cpp-reflection-benchmark" $datasets >> tmp/python_result.json
+echo "," >> "tmp/python_result.json"
+echo "benchmarking python cpp generated code..."
+env LD_PRELOAD="$oldpwd/gperftools/.libs/libtcmalloc.so" ./python-cpp-generated-code-benchmark --json --behavior_prefix="cpp-generated-code-benchmark" $datasets >> tmp/python_result.json
+echo "]" >> "tmp/python_result.json"
+cd $oldpwd
+
+# build CPP protobuf
+./configure
+make clean && make -j8
+
+# 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
+cat $(find /tmp -name "trail-1.log")
+
+# upload result to bq
+make python_add_init
+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/benchmark/continuous.cfg b/kokoro/linux/benchmark/continuous.cfg
new file mode 100755
index 00000000..a3558c65
--- /dev/null
+++ b/kokoro/linux/benchmark/continuous.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/benchmark/build.sh"
+timeout_mins: 240
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/jenkins/build_and_run_docker.sh b/kokoro/linux/build_and_run_docker.sh
index 50e1e8c6..6a1f327a 100755
--- a/jenkins/build_and_run_docker.sh
+++ b/kokoro/linux/build_and_run_docker.sh
@@ -11,15 +11,16 @@
set -ex
-cd $(dirname $0)/..
+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\ )
+# Use image name based on Dockerfile sha1
+DOCKERHUB_ORGANIZATION=grpctesting/protobuf
+DOCKER_IMAGE_NAME=${DOCKERHUB_ORGANIZATION}_$(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
+# Pull dockerimage from Dockerhub
+docker pull $DOCKER_IMAGE_NAME
# Ensure existence of ccache directory
CCACHE_DIR=/tmp/protobuf-ccache
@@ -28,24 +29,26 @@ mkdir -p $CCACHE_DIR
# Choose random name for docker container
CONTAINER_NAME="build_and_run_docker_$(uuidgen)"
+echo $git_root
+
# Run command inside docker
docker run \
"$@" \
-e CCACHE_DIR=$CCACHE_DIR \
- -e EXTERNAL_GIT_ROOT="/var/local/jenkins/protobuf" \
+ -e EXTERNAL_GIT_ROOT="/var/local/kokoro/protobuf" \
-e TEST_SET="$TEST_SET" \
-e THIS_IS_REALLY_NEEDED='see https://github.com/docker/docker/issues/14203 for why docker is awful' \
- -v "$git_root:/var/local/jenkins/protobuf:ro" \
+ -v "$git_root:/var/local/kokoro/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"
+ bash -l "/var/local/kokoro/protobuf/$DOCKER_RUN_SCRIPT" || FAILED="true"
# Copy output artifacts
if [ "$OUTPUT_DIR" != "" ]
then
- docker cp "$CONTAINER_NAME:/var/local/git/protobuf/$OUTPUT_DIR" "$git_root" || FAILED="true"
+ docker cp "$CONTAINER_NAME:/var/local/git/protobuf/$OUTPUT_DIR" "${git_root}/kokoro" || FAILED="true"
fi
# remove the container, possibly killing it first
diff --git a/kokoro/linux/golang/build.sh b/kokoro/linux/golang/build.sh
new file mode 100755
index 00000000..79cddff1
--- /dev/null
+++ b/kokoro/linux/golang/build.sh
@@ -0,0 +1,17 @@
+#!/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="golang"
+./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/golang/continuous.cfg b/kokoro/linux/golang/continuous.cfg
new file mode 100644
index 00000000..2282f78f
--- /dev/null
+++ b/kokoro/linux/golang/continuous.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/golang/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/golang/presubmit.cfg b/kokoro/linux/golang/presubmit.cfg
new file mode 100644
index 00000000..2282f78f
--- /dev/null
+++ b/kokoro/linux/golang/presubmit.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/golang/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/java_jdk7/build.sh b/kokoro/linux/java_jdk7/build.sh
new file mode 100755
index 00000000..0a5604b4
--- /dev/null
+++ b/kokoro/linux/java_jdk7/build.sh
@@ -0,0 +1,17 @@
+#!/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="java_jdk7"
+./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/java_jdk7/continuous.cfg b/kokoro/linux/java_jdk7/continuous.cfg
new file mode 100644
index 00000000..07a9df5f
--- /dev/null
+++ b/kokoro/linux/java_jdk7/continuous.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/java_jdk7/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/java_jdk7/presubmit.cfg b/kokoro/linux/java_jdk7/presubmit.cfg
new file mode 100644
index 00000000..07a9df5f
--- /dev/null
+++ b/kokoro/linux/java_jdk7/presubmit.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/java_jdk7/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/java_oracle7/build.sh b/kokoro/linux/java_oracle7/build.sh
new file mode 100755
index 00000000..9ab90dad
--- /dev/null
+++ b/kokoro/linux/java_oracle7/build.sh
@@ -0,0 +1,17 @@
+#!/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="java_oracle7"
+./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/java_oracle7/continuous.cfg b/kokoro/linux/java_oracle7/continuous.cfg
new file mode 100644
index 00000000..610469b4
--- /dev/null
+++ b/kokoro/linux/java_oracle7/continuous.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/java_oracle7/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/java_oracle7/presubmit.cfg b/kokoro/linux/java_oracle7/presubmit.cfg
new file mode 100644
index 00000000..610469b4
--- /dev/null
+++ b/kokoro/linux/java_oracle7/presubmit.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/java_oracle7/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/javascript/build.sh b/kokoro/linux/javascript/build.sh
new file mode 100755
index 00000000..c2585fb7
--- /dev/null
+++ b/kokoro/linux/javascript/build.sh
@@ -0,0 +1,17 @@
+#!/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="javascript"
+./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/javascript/continuous.cfg b/kokoro/linux/javascript/continuous.cfg
new file mode 100644
index 00000000..b42f522f
--- /dev/null
+++ b/kokoro/linux/javascript/continuous.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/javascript/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/javascript/presubmit.cfg b/kokoro/linux/javascript/presubmit.cfg
new file mode 100644
index 00000000..b42f522f
--- /dev/null
+++ b/kokoro/linux/javascript/presubmit.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/javascript/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/jenkins/make_test_output.py b/kokoro/linux/make_test_output.py
index 98536853..98536853 100644
--- a/jenkins/make_test_output.py
+++ b/kokoro/linux/make_test_output.py
diff --git a/kokoro/linux/php_all/build.sh b/kokoro/linux/php_all/build.sh
new file mode 100755
index 00000000..e9ab84cb
--- /dev/null
+++ b/kokoro/linux/php_all/build.sh
@@ -0,0 +1,17 @@
+#!/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="php_all"
+./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/php_all/continuous.cfg b/kokoro/linux/php_all/continuous.cfg
new file mode 100644
index 00000000..dfa8037e
--- /dev/null
+++ b/kokoro/linux/php_all/continuous.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/php_all/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/php_all/presubmit.cfg b/kokoro/linux/php_all/presubmit.cfg
new file mode 100644
index 00000000..dfa8037e
--- /dev/null
+++ b/kokoro/linux/php_all/presubmit.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/php_all/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/prepare_build_linux_rc b/kokoro/linux/prepare_build_linux_rc
index 4c3f255d..f64ea952 100644
--- a/kokoro/linux/prepare_build_linux_rc
+++ b/kokoro/linux/prepare_build_linux_rc
@@ -3,7 +3,11 @@
# Source this rc script to prepare the environment for Linux builds
# Set up dotnet
-sudo sh -c 'echo "deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ trusty main" > /etc/apt/sources.list.d/dotnetdev.list'
-sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 417A0893
+sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-trusty-prod trusty main" > /etc/apt/sources.list.d/dotnetdev.list'
+sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EB3E94ADBE1229CF
sudo apt-get update
-sudo apt-get install -y dotnet-dev-1.0.4
+# We use the .NET Core SDK 2.x to build...
+sudo apt-get install -y dotnet-sdk-2.0.3
+# But we also need the 1.x framework to test against, as we
+# target netstandard1.x
+sudo apt-get install -y dotnet-sharedframework-microsoft.netcore.app-1.0.5
diff --git a/jenkins/pull_request_in_docker.sh b/kokoro/linux/pull_request_in_docker.sh
index 10daf0a5..df3636cc 100755
--- a/jenkins/pull_request_in_docker.sh
+++ b/kokoro/linux/pull_request_in_docker.sh
@@ -5,7 +5,7 @@
WORKSPACE_BASE=`pwd`
MY_DIR="$(dirname "$0")"
-TEST_SCRIPT=$MY_DIR/../tests.sh
+TEST_SCRIPT=$MY_DIR/../../tests.sh
BUILD_DIR=/tmp/protobuf
set -e # exit immediately on error
@@ -16,9 +16,12 @@ set -x # display all commands
rm -rf $BUILD_DIR
mkdir -p $BUILD_DIR
cd $BUILD_DIR
-git clone /var/local/jenkins/protobuf
+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
@@ -54,10 +57,10 @@ parallel --results $LOG_OUTPUT_DIR --joblog $OUTPUT_DIR/joblog $TEST_SCRIPT :::
cat $OUTPUT_DIR/joblog
-# The directory that is copied from Docker back into the Jenkins workspace.
+# The directory that is copied from Docker back into the Kokoro workspace.
COPY_FROM_DOCKER=/var/local/git/protobuf/testoutput
mkdir -p $COPY_FROM_DOCKER
-TESTOUTPUT_XML_FILE=$COPY_FROM_DOCKER/testresults.xml
+TESTOUTPUT_XML_FILE=$COPY_FROM_DOCKER/sponge_log.xml
# Process all the output files from "parallel" and package them into a single
# .xml file with detailed, broken-down test output.
diff --git a/kokoro/linux/python/build.sh b/kokoro/linux/python/build.sh
new file mode 100755
index 00000000..86964f55
--- /dev/null
+++ b/kokoro/linux/python/build.sh
@@ -0,0 +1,17 @@
+#!/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="python"
+./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/python/continuous.cfg b/kokoro/linux/python/continuous.cfg
new file mode 100644
index 00000000..e2fc4136
--- /dev/null
+++ b/kokoro/linux/python/continuous.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/python/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/python/presubmit.cfg b/kokoro/linux/python/presubmit.cfg
new file mode 100644
index 00000000..e2fc4136
--- /dev/null
+++ b/kokoro/linux/python/presubmit.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/python/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/python_cpp/build.sh b/kokoro/linux/python_cpp/build.sh
new file mode 100755
index 00000000..add64651
--- /dev/null
+++ b/kokoro/linux/python_cpp/build.sh
@@ -0,0 +1,17 @@
+#!/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="python_cpp"
+./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/python_cpp/continuous.cfg b/kokoro/linux/python_cpp/continuous.cfg
new file mode 100644
index 00000000..b1b0e550
--- /dev/null
+++ b/kokoro/linux/python_cpp/continuous.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/python_cpp/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/python_cpp/presubmit.cfg b/kokoro/linux/python_cpp/presubmit.cfg
new file mode 100644
index 00000000..b1b0e550
--- /dev/null
+++ b/kokoro/linux/python_cpp/presubmit.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/python_cpp/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/ruby_all/build.sh b/kokoro/linux/ruby_all/build.sh
new file mode 100755
index 00000000..ea758958
--- /dev/null
+++ b/kokoro/linux/ruby_all/build.sh
@@ -0,0 +1,17 @@
+#!/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="ruby_all"
+./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/ruby_all/continuous.cfg b/kokoro/linux/ruby_all/continuous.cfg
new file mode 100644
index 00000000..02d76437
--- /dev/null
+++ b/kokoro/linux/ruby_all/continuous.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/ruby_all/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/linux/ruby_all/presubmit.cfg b/kokoro/linux/ruby_all/presubmit.cfg
new file mode 100644
index 00000000..02d76437
--- /dev/null
+++ b/kokoro/linux/ruby_all/presubmit.cfg
@@ -0,0 +1,11 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/ruby_all/build.sh"
+timeout_mins: 120
+
+action {
+ define_artifacts {
+ regex: "**/sponge_log.xml"
+ }
+}
diff --git a/kokoro/macos/prepare_build_macos_rc b/kokoro/macos/prepare_build_macos_rc
index dfe66ff8..fb975523 100755
--- a/kokoro/macos/prepare_build_macos_rc
+++ b/kokoro/macos/prepare_build_macos_rc
@@ -5,7 +5,7 @@
##
# Select Xcode version
-export DEVELOPER_DIR=/Applications/Xcode_8.1.app/Contents/Developer
+export DEVELOPER_DIR=/Applications/Xcode_9.1.app/Contents/Developer
##
# Select C/C++ compilers
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 a825789f..42e4105a 100755
--- a/objectivec/DevTools/full_mac_build.sh
+++ b/objectivec/DevTools/full_mac_build.sh
@@ -253,40 +253,36 @@ if [[ "${DO_XCODE_IOS_TESTS}" == "yes" ]] ; then
XCODEBUILD_TEST_BASE_IOS+=(
-destination "platform=iOS Simulator,name=iPhone 4s,OS=9.0" # 32bit
-destination "platform=iOS Simulator,name=iPhone 7,OS=10.0" # 64bit
- -destination "platform=iOS Simulator,name=iPad 2,OS=9.0" # 32bit
- -destination "platform=iOS Simulator,name=iPad Pro (9.7 inch),OS=10.0" # 64bit
)
;;
- 8.1* )
+ 8.[1-3]* )
XCODEBUILD_TEST_BASE_IOS+=(
-destination "platform=iOS Simulator,name=iPhone 4s,OS=8.1" # 32bit
- -destination "platform=iOS Simulator,name=iPhone 7,OS=10.1" # 64bit
- -destination "platform=iOS Simulator,name=iPad 2,OS=8.1" # 32bit
- -destination "platform=iOS Simulator,name=iPad Pro (9.7 inch),OS=10.1" # 64bit
- )
- ;;
- 8.2* )
- XCODEBUILD_TEST_BASE_IOS+=(
- -destination "platform=iOS Simulator,name=iPhone 4s,OS=8.1" # 32bit
- -destination "platform=iOS Simulator,name=iPhone 7,OS=10.2" # 64bit
- -destination "platform=iOS Simulator,name=iPad 2,OS=8.1" # 32bit
- -destination "platform=iOS Simulator,name=iPad Pro (9.7 inch),OS=10.2" # 64bit
+ -destination "platform=iOS Simulator,name=iPhone 7,OS=latest" # 64bit
)
;;
- 8.3* )
+ 9.[0-2]* )
XCODEBUILD_TEST_BASE_IOS+=(
-destination "platform=iOS Simulator,name=iPhone 4s,OS=8.1" # 32bit
-destination "platform=iOS Simulator,name=iPhone 7,OS=latest" # 64bit
+ # 9.0-9.2 all seem to often fail running destinations in parallel
+ -disable-concurrent-testing
)
;;
- 9.0* )
+ 9.3* )
XCODEBUILD_TEST_BASE_IOS+=(
- -destination "platform=iOS Simulator,name=iPhone 4s,OS=8.1" # 32bit
+ # 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
@@ -299,7 +295,7 @@ if [[ "${DO_XCODE_IOS_TESTS}" == "yes" ]] ; then
"${XCODEBUILD_TEST_BASE_IOS[@]}" -configuration Release test
fi
# Don't leave the simulator in the developer's face.
- killall Simulator
+ killall Simulator 2> /dev/null || true
fi
if [[ "${DO_XCODE_OSX_TESTS}" == "yes" ]] ; then
XCODEBUILD_TEST_BASE_OSX=(
diff --git a/objectivec/DevTools/pddm_tests.py b/objectivec/DevTools/pddm_tests.py
index 8a73b842..9ac6a855 100755
--- a/objectivec/DevTools/pddm_tests.py
+++ b/objectivec/DevTools/pddm_tests.py
@@ -311,7 +311,7 @@ foo(x, y)
mc = pddm.MacroCollection(f)
try:
result = mc.Expand('foo(A,B)')
- self.fail('Should throw exception, entry %d' % idx)
+ self.fail('Should throw exception! Test failed to catch recursion.')
except pddm.PDDMError as e:
self.assertEqual(e.message,
'Found macro recusion, invoking "foo(1, A)":\n...while expanding "bar(1, A)".\n...while expanding "foo(A,B)".')
@@ -483,7 +483,7 @@ foo
sf = pddm.SourceFile(f)
try:
sf.ProcessContent()
- self.fail('Should throw exception, entry %d' % idx)
+ self.fail('Should throw exception! Test failed to catch macro parsing error.')
except pddm.PDDMError as e:
self.assertEqual(e.message,
'Attempt to redefine macro: "PDDM-DEFINE mumble(x_)"\n'
@@ -503,7 +503,7 @@ foo
sf = pddm.SourceFile(f)
try:
sf.ProcessContent()
- self.fail('Should throw exception, entry %d' % idx)
+ self.fail('Should throw exception! Test failed to catch expand error.')
except pddm.PDDMError as e:
self.assertEqual(e.message,
'No macro named "foobar".\n'
diff --git a/objectivec/GPBCodedInputStream.m b/objectivec/GPBCodedInputStream.m
index 0759640d..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) {
@@ -110,7 +110,7 @@ static int64_t ReadRawVarint64(GPBCodedInputStreamState *state) {
int64_t result = 0;
while (shift < 64) {
int8_t b = ReadRawByte(state);
- result |= (int64_t)(b & 0x7F) << shift;
+ result |= (int64_t)((uint64_t)(b & 0x7F) << shift);
if ((b & 0x80) == 0) {
return result;
}
diff --git a/objectivec/GPBCodedInputStream_PackagePrivate.h b/objectivec/GPBCodedInputStream_PackagePrivate.h
index 90bd0c92..43ec6e79 100644
--- a/objectivec/GPBCodedInputStream_PackagePrivate.h
+++ b/objectivec/GPBCodedInputStream_PackagePrivate.h
@@ -34,8 +34,6 @@
#import "GPBCodedInputStream.h"
-#import <libkern/OSAtomic.h>
-
@class GPBUnknownFieldSet;
@class GPBFieldDescriptor;
diff --git a/objectivec/GPBCodedOutputStream.m b/objectivec/GPBCodedOutputStream.m
index c299040f..b846c2fc 100644
--- a/objectivec/GPBCodedOutputStream.m
+++ b/objectivec/GPBCodedOutputStream.m
@@ -174,10 +174,10 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state,
data:(NSMutableData *)data {
if ((self = [super init])) {
buffer_ = [data retain];
- [output open];
state_.bytes = [data mutableBytes];
state_.size = [data length];
state_.output = [output retain];
+ [state_.output open];
}
return self;
}
@@ -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.m b/objectivec/GPBDescriptor.m
index 3c3844da..615d2234 100644
--- a/objectivec/GPBDescriptor.m
+++ b/objectivec/GPBDescriptor.m
@@ -548,7 +548,8 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
// descriptor structure.
const uint8_t *bytes = (const uint8_t *)defaultValue_.valueData;
if (bytes) {
- uint32_t length = *((uint32_t *)bytes);
+ uint32_t length;
+ memcpy(&length, bytes, sizeof(length));
length = ntohl(length);
bytes += sizeof(length);
defaultValue_.valueData =
@@ -963,7 +964,8 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
const uint8_t *bytes =
(const uint8_t *)description->defaultValue.valueData;
if (bytes) {
- uint32_t length = *((uint32_t *)bytes);
+ uint32_t length;
+ memcpy(&length, bytes, sizeof(length));
// The length is stored in network byte order.
length = ntohl(length);
bytes += sizeof(length);
diff --git a/objectivec/GPBDictionary.h b/objectivec/GPBDictionary.h
index 9d674150..a81165e8 100644
--- a/objectivec/GPBDictionary.h
+++ b/objectivec/GPBDictionary.h
@@ -60,55 +60,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [__nullable])values
- forKeys:(const uint32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32UInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -204,55 +155,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt32s:(const int32_t [__nullable])values
- forKeys:(const uint32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32Int32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -348,55 +250,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [__nullable])values
- forKeys:(const uint32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32UInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -492,55 +345,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt64s:(const int64_t [__nullable])values
- forKeys:(const uint32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32Int64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -636,55 +440,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithBools:(const BOOL [__nullable])values
- forKeys:(const uint32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32BoolDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -780,55 +535,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithFloats:(const float [__nullable])values
- forKeys:(const uint32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32FloatDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -924,55 +630,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithDoubles:(const double [__nullable])values
- forKeys:(const uint32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32DoubleDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -1070,70 +727,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given validation function.
- *
- * @param func The enum validation function for the dictionary.
- *
- * @return A newly instanced dictionary.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param func The enum validation function for the dictionary.
- * @param rawValue The raw enum value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param func The enum validation function for the dictionary.
- * @param values The raw enum values values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [__nullable])values
- forKeys:(const uint32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32EnumDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param func The enum validation function for the dictionary.
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems;
-
-/**
* Initializes a dictionary with the given validation function.
*
* @param func The enum validation function for the dictionary.
@@ -1294,55 +887,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param object The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithObject:(ObjectType)object
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param objects The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithObjects:(const ObjectType __nonnull GPB_UNSAFE_UNRETAINED [__nullable])objects
- forKeys:(const uint32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32ObjectDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param objects The values to be placed in this dictionary.
@@ -1437,55 +981,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [__nullable])values
- forKeys:(const int32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32UInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -1581,55 +1076,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt32s:(const int32_t [__nullable])values
- forKeys:(const int32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32Int32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -1725,55 +1171,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [__nullable])values
- forKeys:(const int32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32UInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -1869,55 +1266,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt64s:(const int64_t [__nullable])values
- forKeys:(const int32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32Int64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -2013,55 +1361,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithBools:(const BOOL [__nullable])values
- forKeys:(const int32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32BoolDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -2157,55 +1456,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithFloats:(const float [__nullable])values
- forKeys:(const int32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32FloatDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -2301,55 +1551,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithDoubles:(const double [__nullable])values
- forKeys:(const int32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32DoubleDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -2447,70 +1648,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given validation function.
- *
- * @param func The enum validation function for the dictionary.
- *
- * @return A newly instanced dictionary.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param func The enum validation function for the dictionary.
- * @param rawValue The raw enum value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param func The enum validation function for the dictionary.
- * @param values The raw enum values values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [__nullable])values
- forKeys:(const int32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32EnumDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param func The enum validation function for the dictionary.
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems;
-
-/**
* Initializes a dictionary with the given validation function.
*
* @param func The enum validation function for the dictionary.
@@ -2671,55 +1808,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param object The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithObject:(ObjectType)object
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param objects The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithObjects:(const ObjectType __nonnull GPB_UNSAFE_UNRETAINED [__nullable])objects
- forKeys:(const int32_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32ObjectDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param objects The values to be placed in this dictionary.
@@ -2814,55 +1902,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [__nullable])values
- forKeys:(const uint64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64UInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -2958,55 +1997,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt32s:(const int32_t [__nullable])values
- forKeys:(const uint64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64Int32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -3102,55 +2092,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [__nullable])values
- forKeys:(const uint64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64UInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -3246,55 +2187,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt64s:(const int64_t [__nullable])values
- forKeys:(const uint64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64Int64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -3390,55 +2282,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithBools:(const BOOL [__nullable])values
- forKeys:(const uint64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64BoolDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -3534,55 +2377,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithFloats:(const float [__nullable])values
- forKeys:(const uint64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64FloatDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -3678,55 +2472,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithDoubles:(const double [__nullable])values
- forKeys:(const uint64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64DoubleDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -3824,70 +2569,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given validation function.
- *
- * @param func The enum validation function for the dictionary.
- *
- * @return A newly instanced dictionary.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param func The enum validation function for the dictionary.
- * @param rawValue The raw enum value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param func The enum validation function for the dictionary.
- * @param values The raw enum values values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [__nullable])values
- forKeys:(const uint64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64EnumDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param func The enum validation function for the dictionary.
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems;
-
-/**
* Initializes a dictionary with the given validation function.
*
* @param func The enum validation function for the dictionary.
@@ -4048,55 +2729,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param object The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithObject:(ObjectType)object
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param objects The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithObjects:(const ObjectType __nonnull GPB_UNSAFE_UNRETAINED [__nullable])objects
- forKeys:(const uint64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64ObjectDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param objects The values to be placed in this dictionary.
@@ -4191,55 +2823,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [__nullable])values
- forKeys:(const int64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64UInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -4335,55 +2918,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt32s:(const int32_t [__nullable])values
- forKeys:(const int64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64Int32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -4479,55 +3013,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [__nullable])values
- forKeys:(const int64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64UInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -4623,55 +3108,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt64s:(const int64_t [__nullable])values
- forKeys:(const int64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64Int64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -4767,55 +3203,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithBools:(const BOOL [__nullable])values
- forKeys:(const int64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64BoolDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -4911,55 +3298,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithFloats:(const float [__nullable])values
- forKeys:(const int64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64FloatDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -5055,55 +3393,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithDoubles:(const double [__nullable])values
- forKeys:(const int64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64DoubleDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -5201,70 +3490,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given validation function.
- *
- * @param func The enum validation function for the dictionary.
- *
- * @return A newly instanced dictionary.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param func The enum validation function for the dictionary.
- * @param rawValue The raw enum value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param func The enum validation function for the dictionary.
- * @param values The raw enum values values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [__nullable])values
- forKeys:(const int64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64EnumDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param func The enum validation function for the dictionary.
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems;
-
-/**
* Initializes a dictionary with the given validation function.
*
* @param func The enum validation function for the dictionary.
@@ -5425,55 +3650,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param object The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithObject:(ObjectType)object
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param objects The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithObjects:(const ObjectType __nonnull GPB_UNSAFE_UNRETAINED [__nullable])objects
- forKeys:(const int64_t [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64ObjectDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param objects The values to be placed in this dictionary.
@@ -5568,55 +3744,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [__nullable])values
- forKeys:(const BOOL [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolUInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -5712,55 +3839,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt32s:(const int32_t [__nullable])values
- forKeys:(const BOOL [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -5856,55 +3934,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [__nullable])values
- forKeys:(const BOOL [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolUInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -6000,55 +4029,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt64s:(const int64_t [__nullable])values
- forKeys:(const BOOL [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -6144,55 +4124,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithBools:(const BOOL [__nullable])values
- forKeys:(const BOOL [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolBoolDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -6288,55 +4219,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithFloats:(const float [__nullable])values
- forKeys:(const BOOL [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolFloatDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -6432,55 +4314,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithDoubles:(const double [__nullable])values
- forKeys:(const BOOL [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolDoubleDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -6578,70 +4411,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given validation function.
- *
- * @param func The enum validation function for the dictionary.
- *
- * @return A newly instanced dictionary.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param func The enum validation function for the dictionary.
- * @param rawValue The raw enum value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param func The enum validation function for the dictionary.
- * @param values The raw enum values values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [__nullable])values
- forKeys:(const BOOL [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolEnumDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param func The enum validation function for the dictionary.
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems;
-
-/**
* Initializes a dictionary with the given validation function.
*
* @param func The enum validation function for the dictionary.
@@ -6802,55 +4571,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param object The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithObject:(ObjectType)object
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param objects The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithObjects:(const ObjectType __nonnull GPB_UNSAFE_UNRETAINED [__nullable])objects
- forKeys:(const BOOL [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolObjectDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param objects The values to be placed in this dictionary.
@@ -6945,55 +4665,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [__nullable])values
- forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringUInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -7089,55 +4760,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt32s:(const int32_t [__nullable])values
- forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -7233,55 +4855,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [__nullable])values
- forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringUInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -7377,55 +4950,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt64s:(const int64_t [__nullable])values
- forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -7521,55 +5045,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithBools:(const BOOL [__nullable])values
- forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringBoolDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -7665,55 +5140,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithFloats:(const float [__nullable])values
- forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringFloatDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -7809,55 +5235,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithDoubles:(const double [__nullable])values
- forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringDoubleDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -7955,70 +5332,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given validation function.
- *
- * @param func The enum validation function for the dictionary.
- *
- * @return A newly instanced dictionary.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param func The enum validation function for the dictionary.
- * @param rawValue The raw enum value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param func The enum validation function for the dictionary.
- * @param values The raw enum values values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [__nullable])values
- forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringEnumDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param func The enum validation function for the dictionary.
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems;
-
-/**
* Initializes a dictionary with the given validation function.
*
* @param func The enum validation function for the dictionary.
@@ -8240,55 +5553,6 @@ NS_ASSUME_NONNULL_END
//%@property(nonatomic, readonly) NSUInteger count;
//%
//%/**
-//% * @return A newly instanced and empty dictionary.
-//% **/
-//%+ (instancetype)dictionary;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the single entry given.
-//% *
-//% * @param ##VNAME_VAR The value to be placed in the dictionary.
-//% * @param key ##VNAME_VAR$S## The key under which to store the value.
-//% *
-//% * @return A newly instanced dictionary with the key and value in it.
-//% **/
-//%+ (instancetype)dictionaryWith##VNAME##:(VALUE_TYPE)##VNAME_VAR
-//% ##VNAME$S## forKey:(KEY_TYPE##KisP$S##KisP)key;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the entries given.
-//% *
-//% * @param ##VNAME_VAR##s The values to be placed in the dictionary.
-//% * @param keys ##VNAME_VAR$S## The keys under which to store the values.
-//% * @param count ##VNAME_VAR$S## The number of entries to store in the dictionary.
-//% *
-//% * @return A newly instanced dictionary with the keys and values in it.
-//% **/
-//%+ (instancetype)dictionaryWith##VNAME##s:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[__nullable])##VNAME_VAR##s
-//% ##VNAME$S## forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[__nullable])keys
-//% ##VNAME$S## count:(NSUInteger)count;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the entries from the given.
-//% * dictionary.
-//% *
-//% * @param dictionary Dictionary containing the entries to add to the dictionary.
-//% *
-//% * @return A newly instanced dictionary with the entries from the given
-//% * dictionary in it.
-//% **/
-//%+ (instancetype)dictionaryWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the given capacity.
-//% *
-//% * @param numItems Capacity needed for the dictionary.
-//% *
-//% * @return A newly instanced dictionary with the given capacity.
-//% **/
-//%+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-//%
-//%/**
//% * Initializes this dictionary, copying the given values and keys.
//% *
//% * @param ##VNAME_VAR##s The values to be placed in this dictionary.
@@ -8353,70 +5617,6 @@ NS_ASSUME_NONNULL_END
//%@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
//%
//%/**
-//% * @return A newly instanced and empty dictionary.
-//% **/
-//%+ (instancetype)dictionary;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the given validation function.
-//% *
-//% * @param func The enum validation function for the dictionary.
-//% *
-//% * @return A newly instanced dictionary.
-//% **/
-//%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the single entry given.
-//% *
-//% * @param func The enum validation function for the dictionary.
-//% * @param rawValue The raw enum value to be placed in the dictionary.
-//% * @param key The key under which to store the value.
-//% *
-//% * @return A newly instanced dictionary with the key and value in it.
-//% **/
-//%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
-//% rawValue:(VALUE_TYPE)rawValue
-//% forKey:(KEY_TYPE##KisP$S##KisP)key;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the entries given.
-//% *
-//% * @param func The enum validation function for the dictionary.
-//% * @param values The raw enum values values to be placed in the dictionary.
-//% * @param keys The keys under which to store the values.
-//% * @param count The number of entries to store in the dictionary.
-//% *
-//% * @return A newly instanced dictionary with the keys and values in it.
-//% **/
-//%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
-//% rawValues:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[__nullable])values
-//% forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[__nullable])keys
-//% count:(NSUInteger)count;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the entries from the given.
-//% * dictionary.
-//% *
-//% * @param dictionary Dictionary containing the entries to add to the dictionary.
-//% *
-//% * @return A newly instanced dictionary with the entries from the given
-//% * dictionary in it.
-//% **/
-//%+ (instancetype)dictionaryWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the given capacity.
-//% *
-//% * @param func The enum validation function for the dictionary.
-//% * @param numItems Capacity needed for the dictionary.
-//% *
-//% * @return A newly instanced dictionary with the given capacity.
-//% **/
-//%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
-//% capacity:(NSUInteger)numItems;
-//%
-//%/**
//% * Initializes a dictionary with the given validation function.
//% *
//% * @param func The enum validation function for the dictionary.
diff --git a/objectivec/GPBDictionary.m b/objectivec/GPBDictionary.m
index 7713376e..aa21670a 100644
--- a/objectivec/GPBDictionary.m
+++ b/objectivec/GPBDictionary.m
@@ -596,39 +596,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
//% NSMutableDictionary *_dictionary;
//%}
//%
-//%+ (instancetype)dictionary {
-//% return [[[self alloc] initWith##VNAME##s:NULL forKeys:NULL count:0] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWith##VNAME##:(VALUE_TYPE)##VNAME_VAR
-//% ##VNAME$S## forKey:(KEY_TYPE##KisP$S##KisP)key {
-//% // Cast is needed so the compiler knows what class we are invoking initWith##VNAME##s:forKeys:count:
-//% // on to get the type correct.
-//% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWith##VNAME##s:&##VNAME_VAR
-//% KEY_NAME$S VALUE_NAME$S ##VNAME$S## forKeys:&key
-//% KEY_NAME$S VALUE_NAME$S ##VNAME$S## count:1] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWith##VNAME##s:(const VALUE_TYPE [])##VNAME_VAR##s
-//% ##VNAME$S## forKeys:(const KEY_TYPE##KisP$S##KisP [])keys
-//% ##VNAME$S## count:(NSUInteger)count {
-//% // Cast is needed so the compiler knows what class we are invoking initWith##VNAME##s:forKeys:count:
-//% // on to get the type correct.
-//% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWith##VNAME##s:##VNAME_VAR##s
-//% KEY_NAME$S VALUE_NAME$S forKeys:keys
-//% KEY_NAME$S VALUE_NAME$S count:count] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary {
-//% // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
-//% // on to get the type correct.
-//% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
-//% return [[[self alloc] initWithCapacity:numItems] autorelease];
-//%}
-//%
//%- (instancetype)init {
//% return [self initWith##VNAME##s:NULL forKeys:NULL count:0];
//%}
@@ -685,54 +652,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
//%
//%@synthesize validationFunc = _validationFunc;
//%
-//%+ (instancetype)dictionary {
-//% return [[[self alloc] initWithValidationFunction:NULL
-//% rawValues:NULL
-//% forKeys:NULL
-//% count:0] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func {
-//% return [[[self alloc] initWithValidationFunction:func
-//% rawValues:NULL
-//% forKeys:NULL
-//% count:0] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
-//% rawValue:(VALUE_TYPE)rawValue
-//% forKey:(KEY_TYPE##KisP$S##KisP)key {
-//% // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
-//% // on to get the type correct.
-//% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWithValidationFunction:func
-//% KEY_NAME$S VALUE_NAME$S rawValues:&rawValue
-//% KEY_NAME$S VALUE_NAME$S forKeys:&key
-//% KEY_NAME$S VALUE_NAME$S count:1] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
-//% rawValues:(const VALUE_TYPE [])rawValues
-//% forKeys:(const KEY_TYPE##KisP$S##KisP [])keys
-//% count:(NSUInteger)count {
-//% // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
-//% // on to get the type correct.
-//% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWithValidationFunction:func
-//% KEY_NAME$S VALUE_NAME$S rawValues:rawValues
-//% KEY_NAME$S VALUE_NAME$S forKeys:keys
-//% KEY_NAME$S VALUE_NAME$S count:count] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary {
-//% // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
-//% // on to get the type correct.
-//% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
-//% capacity:(NSUInteger)numItems {
-//% return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease];
-//%}
-//%
//%- (instancetype)init {
//% return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0];
//%}
@@ -988,39 +907,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
//% VALUE_TYPE _values[2];
//%BOOL_DICT_HAS_STORAGE_##HELPER()}
//%
-//%+ (instancetype)dictionary {
-//% return [[[self alloc] initWith##VNAME##s:NULL forKeys:NULL count:0] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWith##VNAME##:(VALUE_TYPE)VNAME_VAR
-//% ##VNAME$S## forKey:(BOOL)key {
-//% // Cast is needed so the compiler knows what class we are invoking initWith##VNAME##s:forKeys:count:
-//% // on to get the type correct.
-//% return [[(GPBBool##VALUE_NAME##Dictionary*)[self alloc] initWith##VNAME##s:&##VNAME_VAR
-//% VALUE_NAME$S ##VNAME$S## forKeys:&key
-//% VALUE_NAME$S ##VNAME$S## count:1] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWith##VNAME##s:(const VALUE_TYPE [])##VNAME_VAR##s
-//% ##VNAME$S## forKeys:(const BOOL [])keys
-//% ##VNAME$S## count:(NSUInteger)count {
-//% // Cast is needed so the compiler knows what class we are invoking initWith##VNAME##s:forKeys:count:
-//% // on to get the type correct.
-//% return [[(GPBBool##VALUE_NAME##Dictionary*)[self alloc] initWith##VNAME##s:##VNAME_VAR##s
-//% VALUE_NAME$S ##VNAME$S## forKeys:keys
-//% VALUE_NAME$S ##VNAME$S## count:count] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithDictionary:(GPBBool##VALUE_NAME##Dictionary *)dictionary {
-//% // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
-//% // on to get the type correct.
-//% return [[(GPBBool##VALUE_NAME##Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
-//% return [[[self alloc] initWithCapacity:numItems] autorelease];
-//%}
-//%
//%- (instancetype)init {
//% return [self initWith##VNAME##s:NULL forKeys:NULL count:0];
//%}
@@ -1549,39 +1435,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32UInt32Dictionary*)[self alloc] initWithUInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32UInt32Dictionary*)[self alloc] initWithUInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32UInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32UInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt32s:NULL forKeys:NULL count:0];
}
@@ -1765,39 +1618,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32Int32Dictionary*)[self alloc] initWithInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32Int32Dictionary*)[self alloc] initWithInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32Int32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32Int32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt32s:NULL forKeys:NULL count:0];
}
@@ -1981,39 +1801,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32UInt64Dictionary*)[self alloc] initWithUInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32UInt64Dictionary*)[self alloc] initWithUInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32UInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32UInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt64s:NULL forKeys:NULL count:0];
}
@@ -2197,39 +1984,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32Int64Dictionary*)[self alloc] initWithInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32Int64Dictionary*)[self alloc] initWithInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32Int64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32Int64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt64s:NULL forKeys:NULL count:0];
}
@@ -2413,39 +2167,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32BoolDictionary*)[self alloc] initWithBools:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32BoolDictionary*)[self alloc] initWithBools:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32BoolDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32BoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithBools:NULL forKeys:NULL count:0];
}
@@ -2629,39 +2350,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32FloatDictionary*)[self alloc] initWithFloats:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32FloatDictionary*)[self alloc] initWithFloats:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32FloatDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32FloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithFloats:NULL forKeys:NULL count:0];
}
@@ -2845,39 +2533,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32DoubleDictionary*)[self alloc] initWithDoubles:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32DoubleDictionary*)[self alloc] initWithDoubles:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32DoubleDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32DoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithDoubles:NULL forKeys:NULL count:0];
}
@@ -3064,54 +2719,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
@synthesize validationFunc = _validationFunc;
-+ (instancetype)dictionary {
- return [[[self alloc] initWithValidationFunction:NULL
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func {
- return [[[self alloc] initWithValidationFunction:func
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:&rawValue
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValues:(const int32_t [])rawValues
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:rawValues
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32EnumDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32EnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems {
- return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0];
}
@@ -3361,39 +2968,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithObjects:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithObject:(id)object
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32ObjectDictionary*)[self alloc] initWithObjects:&object
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithObjects:(const id [])objects
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32ObjectDictionary*)[self alloc] initWithObjects:objects
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32ObjectDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32ObjectDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithObjects:NULL forKeys:NULL count:0];
}
@@ -3609,39 +3183,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32UInt32Dictionary*)[self alloc] initWithUInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32UInt32Dictionary*)[self alloc] initWithUInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32UInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32UInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt32s:NULL forKeys:NULL count:0];
}
@@ -3825,39 +3366,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32Int32Dictionary*)[self alloc] initWithInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32Int32Dictionary*)[self alloc] initWithInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32Int32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32Int32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt32s:NULL forKeys:NULL count:0];
}
@@ -4041,39 +3549,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32UInt64Dictionary*)[self alloc] initWithUInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32UInt64Dictionary*)[self alloc] initWithUInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32UInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32UInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt64s:NULL forKeys:NULL count:0];
}
@@ -4257,39 +3732,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32Int64Dictionary*)[self alloc] initWithInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32Int64Dictionary*)[self alloc] initWithInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32Int64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32Int64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt64s:NULL forKeys:NULL count:0];
}
@@ -4473,39 +3915,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32BoolDictionary*)[self alloc] initWithBools:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32BoolDictionary*)[self alloc] initWithBools:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32BoolDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32BoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithBools:NULL forKeys:NULL count:0];
}
@@ -4689,39 +4098,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32FloatDictionary*)[self alloc] initWithFloats:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32FloatDictionary*)[self alloc] initWithFloats:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32FloatDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32FloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithFloats:NULL forKeys:NULL count:0];
}
@@ -4905,39 +4281,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32DoubleDictionary*)[self alloc] initWithDoubles:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32DoubleDictionary*)[self alloc] initWithDoubles:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32DoubleDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32DoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithDoubles:NULL forKeys:NULL count:0];
}
@@ -5124,54 +4467,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
@synthesize validationFunc = _validationFunc;
-+ (instancetype)dictionary {
- return [[[self alloc] initWithValidationFunction:NULL
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func {
- return [[[self alloc] initWithValidationFunction:func
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:&rawValue
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValues:(const int32_t [])rawValues
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:rawValues
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32EnumDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32EnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems {
- return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0];
}
@@ -5421,39 +4716,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithObjects:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithObject:(id)object
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32ObjectDictionary*)[self alloc] initWithObjects:&object
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithObjects:(const id [])objects
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32ObjectDictionary*)[self alloc] initWithObjects:objects
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32ObjectDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32ObjectDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithObjects:NULL forKeys:NULL count:0];
}
@@ -5669,39 +4931,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64UInt32Dictionary*)[self alloc] initWithUInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64UInt32Dictionary*)[self alloc] initWithUInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64UInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64UInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt32s:NULL forKeys:NULL count:0];
}
@@ -5885,39 +5114,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64Int32Dictionary*)[self alloc] initWithInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64Int32Dictionary*)[self alloc] initWithInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64Int32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64Int32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt32s:NULL forKeys:NULL count:0];
}
@@ -6101,39 +5297,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64UInt64Dictionary*)[self alloc] initWithUInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64UInt64Dictionary*)[self alloc] initWithUInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64UInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64UInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt64s:NULL forKeys:NULL count:0];
}
@@ -6317,39 +5480,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64Int64Dictionary*)[self alloc] initWithInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64Int64Dictionary*)[self alloc] initWithInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64Int64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64Int64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt64s:NULL forKeys:NULL count:0];
}
@@ -6533,39 +5663,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64BoolDictionary*)[self alloc] initWithBools:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64BoolDictionary*)[self alloc] initWithBools:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64BoolDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64BoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithBools:NULL forKeys:NULL count:0];
}
@@ -6749,39 +5846,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64FloatDictionary*)[self alloc] initWithFloats:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64FloatDictionary*)[self alloc] initWithFloats:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64FloatDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64FloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithFloats:NULL forKeys:NULL count:0];
}
@@ -6965,39 +6029,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64DoubleDictionary*)[self alloc] initWithDoubles:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64DoubleDictionary*)[self alloc] initWithDoubles:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64DoubleDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64DoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithDoubles:NULL forKeys:NULL count:0];
}
@@ -7184,54 +6215,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
@synthesize validationFunc = _validationFunc;
-+ (instancetype)dictionary {
- return [[[self alloc] initWithValidationFunction:NULL
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func {
- return [[[self alloc] initWithValidationFunction:func
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:&rawValue
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValues:(const int32_t [])rawValues
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:rawValues
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64EnumDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64EnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems {
- return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0];
}
@@ -7481,39 +6464,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithObjects:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithObject:(id)object
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64ObjectDictionary*)[self alloc] initWithObjects:&object
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithObjects:(const id [])objects
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64ObjectDictionary*)[self alloc] initWithObjects:objects
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64ObjectDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64ObjectDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithObjects:NULL forKeys:NULL count:0];
}
@@ -7729,39 +6679,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64UInt32Dictionary*)[self alloc] initWithUInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64UInt32Dictionary*)[self alloc] initWithUInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64UInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64UInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt32s:NULL forKeys:NULL count:0];
}
@@ -7945,39 +6862,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64Int32Dictionary*)[self alloc] initWithInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64Int32Dictionary*)[self alloc] initWithInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64Int32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64Int32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt32s:NULL forKeys:NULL count:0];
}
@@ -8161,39 +7045,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64UInt64Dictionary*)[self alloc] initWithUInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64UInt64Dictionary*)[self alloc] initWithUInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64UInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64UInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt64s:NULL forKeys:NULL count:0];
}
@@ -8377,39 +7228,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64Int64Dictionary*)[self alloc] initWithInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64Int64Dictionary*)[self alloc] initWithInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64Int64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64Int64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt64s:NULL forKeys:NULL count:0];
}
@@ -8593,39 +7411,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64BoolDictionary*)[self alloc] initWithBools:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64BoolDictionary*)[self alloc] initWithBools:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64BoolDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64BoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithBools:NULL forKeys:NULL count:0];
}
@@ -8809,39 +7594,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64FloatDictionary*)[self alloc] initWithFloats:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64FloatDictionary*)[self alloc] initWithFloats:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64FloatDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64FloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithFloats:NULL forKeys:NULL count:0];
}
@@ -9025,39 +7777,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64DoubleDictionary*)[self alloc] initWithDoubles:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64DoubleDictionary*)[self alloc] initWithDoubles:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64DoubleDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64DoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithDoubles:NULL forKeys:NULL count:0];
}
@@ -9244,54 +7963,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
@synthesize validationFunc = _validationFunc;
-+ (instancetype)dictionary {
- return [[[self alloc] initWithValidationFunction:NULL
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func {
- return [[[self alloc] initWithValidationFunction:func
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:&rawValue
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValues:(const int32_t [])rawValues
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:rawValues
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64EnumDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64EnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems {
- return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0];
}
@@ -9541,39 +8212,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithObjects:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithObject:(id)object
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64ObjectDictionary*)[self alloc] initWithObjects:&object
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithObjects:(const id [])objects
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64ObjectDictionary*)[self alloc] initWithObjects:objects
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64ObjectDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64ObjectDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithObjects:NULL forKeys:NULL count:0];
}
@@ -9789,39 +8427,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringUInt32Dictionary*)[self alloc] initWithUInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringUInt32Dictionary*)[self alloc] initWithUInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringUInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBStringUInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt32s:NULL forKeys:NULL count:0];
}
@@ -10013,39 +8618,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringInt32Dictionary*)[self alloc] initWithInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringInt32Dictionary*)[self alloc] initWithInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBStringInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt32s:NULL forKeys:NULL count:0];
}
@@ -10237,39 +8809,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringUInt64Dictionary*)[self alloc] initWithUInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringUInt64Dictionary*)[self alloc] initWithUInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringUInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBStringUInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt64s:NULL forKeys:NULL count:0];
}
@@ -10461,39 +9000,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringInt64Dictionary*)[self alloc] initWithInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringInt64Dictionary*)[self alloc] initWithInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBStringInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt64s:NULL forKeys:NULL count:0];
}
@@ -10685,39 +9191,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringBoolDictionary*)[self alloc] initWithBools:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringBoolDictionary*)[self alloc] initWithBools:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringBoolDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBStringBoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithBools:NULL forKeys:NULL count:0];
}
@@ -10909,39 +9382,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringFloatDictionary*)[self alloc] initWithFloats:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringFloatDictionary*)[self alloc] initWithFloats:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringFloatDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBStringFloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithFloats:NULL forKeys:NULL count:0];
}
@@ -11133,39 +9573,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringDoubleDictionary*)[self alloc] initWithDoubles:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringDoubleDictionary*)[self alloc] initWithDoubles:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringDoubleDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBStringDoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithDoubles:NULL forKeys:NULL count:0];
}
@@ -11360,54 +9767,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
@synthesize validationFunc = _validationFunc;
-+ (instancetype)dictionary {
- return [[[self alloc] initWithValidationFunction:NULL
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func {
- return [[[self alloc] initWithValidationFunction:func
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringEnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:&rawValue
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValues:(const int32_t [])rawValues
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringEnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:rawValues
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringEnumDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringEnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems {
- return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0];
}
@@ -11676,39 +10035,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
BOOL _valueSet[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolUInt32Dictionary*)[self alloc] initWithUInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolUInt32Dictionary*)[self alloc] initWithUInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolUInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolUInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt32s:NULL forKeys:NULL count:0];
}
@@ -11918,39 +10244,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
BOOL _valueSet[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolInt32Dictionary*)[self alloc] initWithInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolInt32Dictionary*)[self alloc] initWithInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt32s:NULL forKeys:NULL count:0];
}
@@ -12160,39 +10453,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
BOOL _valueSet[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolUInt64Dictionary*)[self alloc] initWithUInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolUInt64Dictionary*)[self alloc] initWithUInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolUInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolUInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt64s:NULL forKeys:NULL count:0];
}
@@ -12402,39 +10662,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
BOOL _valueSet[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolInt64Dictionary*)[self alloc] initWithInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolInt64Dictionary*)[self alloc] initWithInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt64s:NULL forKeys:NULL count:0];
}
@@ -12644,39 +10871,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
BOOL _valueSet[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolBoolDictionary*)[self alloc] initWithBools:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolBoolDictionary*)[self alloc] initWithBools:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolBoolDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolBoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithBools:NULL forKeys:NULL count:0];
}
@@ -12886,39 +11080,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
BOOL _valueSet[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolFloatDictionary*)[self alloc] initWithFloats:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolFloatDictionary*)[self alloc] initWithFloats:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolFloatDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolFloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithFloats:NULL forKeys:NULL count:0];
}
@@ -13128,39 +11289,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
BOOL _valueSet[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolDoubleDictionary*)[self alloc] initWithDoubles:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolDoubleDictionary*)[self alloc] initWithDoubles:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolDoubleDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolDoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithDoubles:NULL forKeys:NULL count:0];
}
@@ -13369,39 +11497,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
id _values[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithObjects:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithObject:(id)object
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolObjectDictionary*)[self alloc] initWithObjects:&object
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithObjects:(const id [])objects
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolObjectDictionary*)[self alloc] initWithObjects:objects
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolObjectDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolObjectDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithObjects:NULL forKeys:NULL count:0];
}
@@ -13635,54 +11730,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
@synthesize validationFunc = _validationFunc;
-+ (instancetype)dictionary {
- return [[[self alloc] initWithValidationFunction:NULL
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func {
- return [[[self alloc] initWithValidationFunction:func
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolEnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:&rawValue
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValues:(const int32_t [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolEnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolEnumDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolEnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems {
- return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0];
}
diff --git a/objectivec/GPBMessage.m b/objectivec/GPBMessage.m
index 37cff6ce..db5d3b60 100644
--- a/objectivec/GPBMessage.m
+++ b/objectivec/GPBMessage.m
@@ -32,6 +32,7 @@
#import <objc/runtime.h>
#import <objc/message.h>
+#import <stdatomic.h>
#import "GPBArray_PackagePrivate.h"
#import "GPBCodedInputStream_PackagePrivate.h"
@@ -77,6 +78,20 @@ static NSString *const kGPBDataCoderKey = @"GPBData";
GPBMessage *autocreator_;
GPBFieldDescriptor *autocreatorField_;
GPBExtensionDescriptor *autocreatorExtension_;
+
+ // A lock to provide mutual exclusion from internal data that can be modified
+ // by *read* operations such as getters (autocreation of message fields and
+ // message extensions, not setting of values). Used to guarantee thread safety
+ // for concurrent reads on the message.
+ // NOTE: OSSpinLock may seem like a good fit here but Apple engineers have
+ // pointed out that they are vulnerable to live locking on iOS in cases of
+ // priority inversion:
+ // http://mjtsai.com/blog/2015/12/16/osspinlock-is-unsafe/
+ // https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000372.html
+ // Use of readOnlySemaphore_ must be prefaced by a call to
+ // GPBPrepareReadOnlySemaphore to ensure it has been created. This allows
+ // readOnlySemaphore_ to be only created when actually needed.
+ _Atomic(dispatch_semaphore_t) readOnlySemaphore_;
}
@end
@@ -742,16 +757,22 @@ void GPBClearMessageAutocreator(GPBMessage *self) {
void GPBPrepareReadOnlySemaphore(GPBMessage *self) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdirect-ivar-access"
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// Create the semaphore on demand (rather than init) as developers might not cause them
// to be needed, and the heap usage can add up. The atomic swap is used to avoid needing
// another lock around creating it.
if (self->readOnlySemaphore_ == nil) {
dispatch_semaphore_t worker = dispatch_semaphore_create(1);
- if (!OSAtomicCompareAndSwapPtrBarrier(NULL, worker, (void * volatile *)&(self->readOnlySemaphore_))) {
+ dispatch_semaphore_t expected = nil;
+ if (!atomic_compare_exchange_strong(&self->readOnlySemaphore_, &expected, worker)) {
dispatch_release(worker);
}
+#if defined(__clang_analyzer__)
+ // The Xcode 9.2 (and 9.3 beta) static analyzer thinks worker is leaked
+ // (doesn't seem to know about atomic_compare_exchange_strong); so just
+ // for the analyzer, let it think worker is also released in this case.
+ else { dispatch_release(worker); }
+#endif
}
#pragma clang diagnostic pop
@@ -969,7 +990,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
newValue = [value copyWithZone:zone];
}
} else {
- if (field.mapKeyDataType == GPBDataTypeString) {
+ if ((field.mapKeyDataType == GPBDataTypeString) &&
+ GPBFieldDataTypeIsObject(field)) {
// NSDictionary
newValue = [value mutableCopyWithZone:zone];
} else {
@@ -2026,7 +2048,12 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
[newInput release];
} else {
GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self);
- [unknownFields mergeMessageSetMessage:typeId data:rawBytes];
+ // rawBytes was created via a NoCopy, so it can be reusing a
+ // subrange of another NSData that might go out of scope as things
+ // unwind, so a copy is needed to ensure what is saved in the
+ // unknown fields stays valid.
+ NSData *cloned = [NSData dataWithData:rawBytes];
+ [unknownFields mergeMessageSetMessage:typeId data:cloned];
}
}
}
@@ -2591,13 +2618,14 @@ static void MergeRepeatedNotPackedFieldFromCodedInputStream(
if (other == self) {
return YES;
}
- if (![other isKindOfClass:[self class]] &&
- ![self isKindOfClass:[other class]]) {
+ if (![other isKindOfClass:[GPBMessage class]]) {
return NO;
}
-
GPBMessage *otherMsg = other;
GPBDescriptor *descriptor = [[self class] descriptor];
+ if ([[otherMsg class] descriptor] != descriptor) {
+ return NO;
+ }
uint8_t *selfStorage = (uint8_t *)messageStorage_;
uint8_t *otherStorage = (uint8_t *)otherMsg->messageStorage_;
@@ -2997,7 +3025,10 @@ typedef struct ResolveIvarAccessorMethodResult {
SEL encodingSelector;
} ResolveIvarAccessorMethodResult;
-static void ResolveIvarGet(GPBFieldDescriptor *field,
+// |field| can be __unsafe_unretained because they are created at startup
+// and are essentially global. No need to pay for retain/release when
+// they are captured in blocks.
+static void ResolveIvarGet(__unsafe_unretained GPBFieldDescriptor *field,
ResolveIvarAccessorMethodResult *result) {
GPBDataType fieldDataType = GPBGetFieldDataType(field);
switch (fieldDataType) {
@@ -3039,7 +3070,8 @@ static void ResolveIvarGet(GPBFieldDescriptor *field,
}
}
-static void ResolveIvarSet(GPBFieldDescriptor *field,
+// See comment about __unsafe_unretained on ResolveIvarGet.
+static void ResolveIvarSet(__unsafe_unretained GPBFieldDescriptor *field,
GPBFileSyntax syntax,
ResolveIvarAccessorMethodResult *result) {
GPBDataType fieldDataType = GPBGetFieldDataType(field);
@@ -3083,9 +3115,10 @@ static void ResolveIvarSet(GPBFieldDescriptor *field,
// NOTE: hasOrCountSel_/setHasSel_ will be NULL if the field for the given
// message should not have has support (done in GPBDescriptor.m), so there is
// no need for checks here to see if has*/setHas* are allowed.
-
ResolveIvarAccessorMethodResult result = {NULL, NULL};
- for (GPBFieldDescriptor *field in descriptor->fields_) {
+
+ // See comment about __unsafe_unretained on ResolveIvarGet.
+ for (__unsafe_unretained GPBFieldDescriptor *field in descriptor->fields_) {
BOOL isMapOrArray = GPBFieldIsMapOrArray(field);
if (!isMapOrArray) {
// Single fields.
@@ -3253,4 +3286,32 @@ id GPBGetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field) {
return GetOrCreateMapIvarWithField(self, field, syntax);
}
+id GPBGetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
+ NSCAssert(!GPBFieldIsMapOrArray(field), @"Shouldn't get here");
+ if (GPBGetHasIvarField(self, field)) {
+ uint8_t *storage = (uint8_t *)self->messageStorage_;
+ id *typePtr = (id *)&storage[field->description_->offset];
+ return *typePtr;
+ }
+ // Not set...
+
+ // Non messages (string/data), get their default.
+ if (!GPBFieldDataTypeIsMessage(field)) {
+ return field.defaultValue.valueMessage;
+ }
+
+ GPBPrepareReadOnlySemaphore(self);
+ dispatch_semaphore_wait(self->readOnlySemaphore_, DISPATCH_TIME_FOREVER);
+ GPBMessage *result = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
+ if (!result) {
+ // For non repeated messages, create the object, set it and return it.
+ // This object will not initially be visible via GPBGetHasIvar, so
+ // we save its creator so it can become visible if it's mutated later.
+ result = GPBCreateMessageWithAutocreator(field.msgClass, self, field);
+ GPBSetAutocreatedRetainedObjectIvarWithField(self, field, result);
+ }
+ dispatch_semaphore_signal(self->readOnlySemaphore_);
+ return result;
+}
+
#pragma clang diagnostic pop
diff --git a/objectivec/GPBMessage_PackagePrivate.h b/objectivec/GPBMessage_PackagePrivate.h
index 90834d40..ca10983b 100644
--- a/objectivec/GPBMessage_PackagePrivate.h
+++ b/objectivec/GPBMessage_PackagePrivate.h
@@ -34,6 +34,10 @@
#import "GPBMessage.h"
+// TODO: Remove this import. Older generated code use the OSAtomic* apis,
+// so anyone that hasn't regenerated says building by having this. After
+// enough time has passed, this likely can be removed as folks should have
+// regenerated.
#import <libkern/OSAtomic.h>
#import "GPBBootstrap.h"
@@ -57,20 +61,6 @@ typedef struct GPBMessage_Storage *GPBMessage_StoragePtr;
// GPBMessage_Storage with _has_storage__ as the first field.
// Kept public because static functions need to access it.
GPBMessage_StoragePtr messageStorage_;
-
- // A lock to provide mutual exclusion from internal data that can be modified
- // by *read* operations such as getters (autocreation of message fields and
- // message extensions, not setting of values). Used to guarantee thread safety
- // for concurrent reads on the message.
- // NOTE: OSSpinLock may seem like a good fit here but Apple engineers have
- // pointed out that they are vulnerable to live locking on iOS in cases of
- // priority inversion:
- // http://mjtsai.com/blog/2015/12/16/osspinlock-is-unsafe/
- // https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000372.html
- // Use of readOnlySemaphore_ must be prefaced by a call to
- // GPBPrepareReadOnlySemaphore to ensure it has been created. This allows
- // readOnlySemaphore_ to be only created when actually needed.
- dispatch_semaphore_t readOnlySemaphore_;
}
// Gets an extension value without autocreating the result if not found. (i.e.
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/GPBRootObject.m b/objectivec/GPBRootObject.m
index 585d205a..bad2f9a7 100644
--- a/objectivec/GPBRootObject.m
+++ b/objectivec/GPBRootObject.m
@@ -43,6 +43,14 @@
- (const char *)singletonNameC;
@end
+// We need some object to conform to the MessageSignatureProtocol to make sure
+// the selectors in it are recorded in our Objective C runtime information.
+// GPBMessage is arguably the more "obvious" choice, but given that all messages
+// inherit from GPBMessage, conflicts seem likely, so we are using GPBRootObject
+// instead.
+@interface GPBRootObject () <GPBMessageSignatureProtocol>
+@end
+
@implementation GPBRootObject
// Taken from http://www.burtleburtle.net/bob/hash/doobs.html
diff --git a/objectivec/GPBUtilities.m b/objectivec/GPBUtilities.m
index 5029ec73..e2a12ca4 100644
--- a/objectivec/GPBUtilities.m
+++ b/objectivec/GPBUtilities.m
@@ -49,6 +49,19 @@ static void AppendTextFormatForMessage(GPBMessage *message,
NSMutableString *toStr,
NSString *lineIndent);
+// Are two datatypes the same basic type representation (ex Int32 and SInt32).
+// Marked unused because currently only called from asserts/debug.
+static BOOL DataTypesEquivalent(GPBDataType type1,
+ GPBDataType type2) __attribute__ ((unused));
+
+// Basic type representation for a type (ex: for SInt32 it is Int32).
+// Marked unused because currently only called from asserts/debug.
+static GPBDataType BaseDataType(GPBDataType type) __attribute__ ((unused));
+
+// String name for a data type.
+// Marked unused because currently only called from asserts/debug.
+static NSString *TypeToString(GPBDataType dataType) __attribute__ ((unused));
+
NSData *GPBEmptyNSData(void) {
static dispatch_once_t onceToken;
static NSData *defaultNSData = nil;
@@ -278,7 +291,7 @@ BOOL GPBGetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber) {
} else {
NSCAssert(idx != GPBNoHasBit, @"Invalid has bit.");
uint32_t byteIndex = idx / 32;
- uint32_t bitMask = (1 << (idx % 32));
+ uint32_t bitMask = (1U << (idx % 32));
BOOL hasIvar =
(self->messageStorage_->_has_storage_[byteIndex] & bitMask) ? YES : NO;
return hasIvar;
@@ -302,7 +315,7 @@ void GPBSetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber,
NSCAssert(idx != GPBNoHasBit, @"Invalid has bit.");
uint32_t *has_storage = self->messageStorage_->_has_storage_;
uint32_t byte = idx / 32;
- uint32_t bitMask = (1 << (idx % 32));
+ uint32_t bitMask = (1U << (idx % 32));
if (value) {
has_storage[byte] |= bitMask;
} else {
@@ -342,6 +355,14 @@ void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof,
//%PDDM-DEFINE IVAR_POD_ACCESSORS_DEFN(NAME, TYPE)
//%TYPE GPBGetMessage##NAME##Field(GPBMessage *self,
//% TYPE$S NAME$S GPBFieldDescriptor *field) {
+//%#if defined(DEBUG) && DEBUG
+//% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+//% GPBDataType##NAME),
+//% @"Attempting to get value of TYPE from field %@ "
+//% @"of %@ which is of type %@.",
+//% [self class], field.name,
+//% TypeToString(GPBGetFieldDataType(field)));
+//%#endif
//% if (GPBGetHasIvarField(self, field)) {
//% uint8_t *storage = (uint8_t *)self->messageStorage_;
//% TYPE *typePtr = (TYPE *)&storage[field->description_->offset];
@@ -364,14 +385,24 @@ void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof,
//% NAME$S GPBFieldDescriptor *field,
//% NAME$S TYPE value,
//% NAME$S GPBFileSyntax syntax) {
+//%#if defined(DEBUG) && DEBUG
+//% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+//% GPBDataType##NAME),
+//% @"Attempting to set field %@ of %@ which is of type %@ with "
+//% @"value of type TYPE.",
+//% [self class], field.name,
+//% TypeToString(GPBGetFieldDataType(field)));
+//%#endif
//% GPBOneofDescriptor *oneof = field->containingOneof_;
//% if (oneof) {
//% GPBMessageFieldDescription *fieldDesc = field->description_;
//% GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
//% }
+//%#if defined(DEBUG) && DEBUG
//% NSCAssert(self->messageStorage_ != NULL,
//% @"%@: All messages should have storage (from init)",
//% [self class]);
+//%#endif
//%#if defined(__clang_analyzer__)
//% if (self->messageStorage_ == NULL) return;
//%#endif
@@ -391,6 +422,14 @@ void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof,
//%// Only exists for public api, no core code should use this.
//%TYPE *GPBGetMessage##NAME##Field(GPBMessage *self,
//% TYPE$S NAME$S GPBFieldDescriptor *field) {
+//%#if defined(DEBUG) && DEBUG
+//% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+//% GPBDataType##NAME),
+//% @"Attempting to get value of TYPE from field %@ "
+//% @"of %@ which is of type %@.",
+//% [self class], field.name,
+//% TypeToString(GPBGetFieldDataType(field)));
+//%#endif
//% return (TYPE *)GPBGetObjectIvarWithField(self, field);
//%}
//%
@@ -398,6 +437,14 @@ void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof,
//%void GPBSetMessage##NAME##Field(GPBMessage *self,
//% NAME$S GPBFieldDescriptor *field,
//% NAME$S TYPE *value) {
+//%#if defined(DEBUG) && DEBUG
+//% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+//% GPBDataType##NAME),
+//% @"Attempting to set field %@ of %@ which is of type %@ with "
+//% @"value of type TYPE.",
+//% [self class], field.name,
+//% TypeToString(GPBGetFieldDataType(field)));
+//%#endif
//% GPBSetObjectIvarWithField(self, field, (id)value);
//%}
//%
@@ -455,7 +502,7 @@ void GPBSetRetainedObjectIvarWithFieldInternal(GPBMessage *self,
GPBDataType fieldType = GPBGetFieldDataType(field);
BOOL isMapOrArray = GPBFieldIsMapOrArray(field);
BOOL fieldIsMessage = GPBDataTypeIsMessage(fieldType);
-#ifdef DEBUG
+#if defined(DEBUG) && DEBUG
if (value == nil && !isMapOrArray && !fieldIsMessage &&
field.hasDefaultValue) {
// Setting a message to nil is an obvious way to "clear" the value
@@ -581,34 +628,6 @@ id GPBGetObjectIvarWithFieldNoAutocreate(GPBMessage *self,
return *typePtr;
}
-id GPBGetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
- NSCAssert(!GPBFieldIsMapOrArray(field), @"Shouldn't get here");
- if (GPBGetHasIvarField(self, field)) {
- uint8_t *storage = (uint8_t *)self->messageStorage_;
- id *typePtr = (id *)&storage[field->description_->offset];
- return *typePtr;
- }
- // Not set...
-
- // Non messages (string/data), get their default.
- if (!GPBFieldDataTypeIsMessage(field)) {
- return field.defaultValue.valueMessage;
- }
-
- GPBPrepareReadOnlySemaphore(self);
- dispatch_semaphore_wait(self->readOnlySemaphore_, DISPATCH_TIME_FOREVER);
- GPBMessage *result = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
- if (!result) {
- // For non repeated messages, create the object, set it and return it.
- // This object will not initially be visible via GPBGetHasIvar, so
- // we save its creator so it can become visible if it's mutated later.
- result = GPBCreateMessageWithAutocreator(field.msgClass, self, field);
- GPBSetAutocreatedRetainedObjectIvarWithField(self, field, result);
- }
- dispatch_semaphore_signal(self->readOnlySemaphore_);
- return result;
-}
-
// Only exists for public api, no core code should use this.
int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field) {
GPBFileSyntax syntax = [self descriptor].file.syntax;
@@ -618,6 +637,13 @@ int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field) {
int32_t GPBGetEnumIvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum,
+ @"Attempting to get value of type Enum from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
int32_t result = GPBGetMessageInt32Field(self, field);
// If this is presevering unknown enums, make sure the value is valid before
// returning it.
@@ -638,6 +664,13 @@ void GPBSetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field,
void GPBSetEnumIvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field, int32_t value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum,
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type Enum.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
// Don't allow in unknown values. Proto3 can use the Raw method.
if (![field isValidEnumValue:value]) {
[NSException raise:NSInvalidArgumentException
@@ -663,6 +696,13 @@ void GPBSetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field,
BOOL GPBGetMessageBoolField(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool),
+ @"Attempting to get value of type bool from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
if (GPBGetHasIvarField(self, field)) {
// Bools are stored in the has bits to avoid needing explicit space in the
// storage structure.
@@ -688,6 +728,13 @@ void GPBSetBoolIvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
BOOL value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type bool.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBMessageFieldDescription *fieldDesc = field->description_;
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
@@ -714,6 +761,14 @@ void GPBSetBoolIvarWithFieldInternal(GPBMessage *self,
int32_t GPBGetMessageInt32Field(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeInt32),
+ @"Attempting to get value of int32_t from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
if (GPBGetHasIvarField(self, field)) {
uint8_t *storage = (uint8_t *)self->messageStorage_;
int32_t *typePtr = (int32_t *)&storage[field->description_->offset];
@@ -736,14 +791,24 @@ void GPBSetInt32IvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
int32_t value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeInt32),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type int32_t.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
GPBMessageFieldDescription *fieldDesc = field->description_;
GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
+#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@"%@: All messages should have storage (from init)",
[self class]);
+#endif
#if defined(__clang_analyzer__)
if (self->messageStorage_ == NULL) return;
#endif
@@ -764,6 +829,14 @@ void GPBSetInt32IvarWithFieldInternal(GPBMessage *self,
uint32_t GPBGetMessageUInt32Field(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeUInt32),
+ @"Attempting to get value of uint32_t from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
if (GPBGetHasIvarField(self, field)) {
uint8_t *storage = (uint8_t *)self->messageStorage_;
uint32_t *typePtr = (uint32_t *)&storage[field->description_->offset];
@@ -786,14 +859,24 @@ void GPBSetUInt32IvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
uint32_t value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeUInt32),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type uint32_t.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
GPBMessageFieldDescription *fieldDesc = field->description_;
GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
+#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@"%@: All messages should have storage (from init)",
[self class]);
+#endif
#if defined(__clang_analyzer__)
if (self->messageStorage_ == NULL) return;
#endif
@@ -814,6 +897,14 @@ void GPBSetUInt32IvarWithFieldInternal(GPBMessage *self,
int64_t GPBGetMessageInt64Field(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeInt64),
+ @"Attempting to get value of int64_t from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
if (GPBGetHasIvarField(self, field)) {
uint8_t *storage = (uint8_t *)self->messageStorage_;
int64_t *typePtr = (int64_t *)&storage[field->description_->offset];
@@ -836,14 +927,24 @@ void GPBSetInt64IvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
int64_t value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeInt64),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type int64_t.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
GPBMessageFieldDescription *fieldDesc = field->description_;
GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
+#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@"%@: All messages should have storage (from init)",
[self class]);
+#endif
#if defined(__clang_analyzer__)
if (self->messageStorage_ == NULL) return;
#endif
@@ -864,6 +965,14 @@ void GPBSetInt64IvarWithFieldInternal(GPBMessage *self,
uint64_t GPBGetMessageUInt64Field(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeUInt64),
+ @"Attempting to get value of uint64_t from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
if (GPBGetHasIvarField(self, field)) {
uint8_t *storage = (uint8_t *)self->messageStorage_;
uint64_t *typePtr = (uint64_t *)&storage[field->description_->offset];
@@ -886,14 +995,24 @@ void GPBSetUInt64IvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
uint64_t value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeUInt64),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type uint64_t.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
GPBMessageFieldDescription *fieldDesc = field->description_;
GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
+#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@"%@: All messages should have storage (from init)",
[self class]);
+#endif
#if defined(__clang_analyzer__)
if (self->messageStorage_ == NULL) return;
#endif
@@ -914,6 +1033,14 @@ void GPBSetUInt64IvarWithFieldInternal(GPBMessage *self,
float GPBGetMessageFloatField(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeFloat),
+ @"Attempting to get value of float from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
if (GPBGetHasIvarField(self, field)) {
uint8_t *storage = (uint8_t *)self->messageStorage_;
float *typePtr = (float *)&storage[field->description_->offset];
@@ -936,14 +1063,24 @@ void GPBSetFloatIvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
float value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeFloat),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type float.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
GPBMessageFieldDescription *fieldDesc = field->description_;
GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
+#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@"%@: All messages should have storage (from init)",
[self class]);
+#endif
#if defined(__clang_analyzer__)
if (self->messageStorage_ == NULL) return;
#endif
@@ -964,6 +1101,14 @@ void GPBSetFloatIvarWithFieldInternal(GPBMessage *self,
double GPBGetMessageDoubleField(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeDouble),
+ @"Attempting to get value of double from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
if (GPBGetHasIvarField(self, field)) {
uint8_t *storage = (uint8_t *)self->messageStorage_;
double *typePtr = (double *)&storage[field->description_->offset];
@@ -986,14 +1131,24 @@ void GPBSetDoubleIvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
double value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeDouble),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type double.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
GPBMessageFieldDescription *fieldDesc = field->description_;
GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
+#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@"%@: All messages should have storage (from init)",
[self class]);
+#endif
#if defined(__clang_analyzer__)
if (self->messageStorage_ == NULL) return;
#endif
@@ -1019,6 +1174,14 @@ void GPBSetDoubleIvarWithFieldInternal(GPBMessage *self,
// Only exists for public api, no core code should use this.
NSString *GPBGetMessageStringField(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeString),
+ @"Attempting to get value of NSString from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
return (NSString *)GPBGetObjectIvarWithField(self, field);
}
@@ -1026,6 +1189,14 @@ NSString *GPBGetMessageStringField(GPBMessage *self,
void GPBSetMessageStringField(GPBMessage *self,
GPBFieldDescriptor *field,
NSString *value) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeString),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type NSString.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBSetObjectIvarWithField(self, field, (id)value);
}
@@ -1035,6 +1206,14 @@ void GPBSetMessageStringField(GPBMessage *self,
// Only exists for public api, no core code should use this.
NSData *GPBGetMessageBytesField(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeBytes),
+ @"Attempting to get value of NSData from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
return (NSData *)GPBGetObjectIvarWithField(self, field);
}
@@ -1042,6 +1221,14 @@ NSData *GPBGetMessageBytesField(GPBMessage *self,
void GPBSetMessageBytesField(GPBMessage *self,
GPBFieldDescriptor *field,
NSData *value) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeBytes),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type NSData.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBSetObjectIvarWithField(self, field, (id)value);
}
@@ -1051,6 +1238,14 @@ void GPBSetMessageBytesField(GPBMessage *self,
// Only exists for public api, no core code should use this.
GPBMessage *GPBGetMessageMessageField(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeMessage),
+ @"Attempting to get value of GPBMessage from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
return (GPBMessage *)GPBGetObjectIvarWithField(self, field);
}
@@ -1058,6 +1253,14 @@ GPBMessage *GPBGetMessageMessageField(GPBMessage *self,
void GPBSetMessageMessageField(GPBMessage *self,
GPBFieldDescriptor *field,
GPBMessage *value) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeMessage),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type GPBMessage.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBSetObjectIvarWithField(self, field, (id)value);
}
@@ -1067,6 +1270,14 @@ void GPBSetMessageMessageField(GPBMessage *self,
// Only exists for public api, no core code should use this.
GPBMessage *GPBGetMessageGroupField(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeGroup),
+ @"Attempting to get value of GPBMessage from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
return (GPBMessage *)GPBGetObjectIvarWithField(self, field);
}
@@ -1074,6 +1285,14 @@ GPBMessage *GPBGetMessageGroupField(GPBMessage *self,
void GPBSetMessageGroupField(GPBMessage *self,
GPBFieldDescriptor *field,
GPBMessage *value) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeGroup),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type GPBMessage.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBSetObjectIvarWithField(self, field, (id)value);
}
@@ -1137,8 +1356,40 @@ void GPBSetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field, id
GPBSetObjectIvarWithField(self, field, array);
}
-#if defined(DEBUG) && DEBUG
-static NSString *TypeToStr(GPBDataType dataType) {
+static GPBDataType BaseDataType(GPBDataType type) {
+ switch (type) {
+ case GPBDataTypeSFixed32:
+ case GPBDataTypeInt32:
+ case GPBDataTypeSInt32:
+ case GPBDataTypeEnum:
+ return GPBDataTypeInt32;
+ case GPBDataTypeFixed32:
+ case GPBDataTypeUInt32:
+ return GPBDataTypeUInt32;
+ case GPBDataTypeSFixed64:
+ case GPBDataTypeInt64:
+ case GPBDataTypeSInt64:
+ return GPBDataTypeInt64;
+ case GPBDataTypeFixed64:
+ case GPBDataTypeUInt64:
+ return GPBDataTypeUInt64;
+ case GPBDataTypeMessage:
+ case GPBDataTypeGroup:
+ return GPBDataTypeMessage;
+ case GPBDataTypeBool:
+ case GPBDataTypeFloat:
+ case GPBDataTypeDouble:
+ case GPBDataTypeBytes:
+ case GPBDataTypeString:
+ return type;
+ }
+}
+
+static BOOL DataTypesEquivalent(GPBDataType type1, GPBDataType type2) {
+ return BaseDataType(type1) == BaseDataType(type2);
+}
+
+static NSString *TypeToString(GPBDataType dataType) {
switch (dataType) {
case GPBDataTypeBool:
return @"Bool";
@@ -1166,10 +1417,9 @@ static NSString *TypeToStr(GPBDataType dataType) {
case GPBDataTypeGroup:
return @"Object";
case GPBDataTypeEnum:
- return @"Bool";
+ return @"Enum";
}
}
-#endif
// GPBGetMessageMapField is defined in GPBMessage.m
@@ -1185,8 +1435,8 @@ void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field,
if (dictionary) {
GPBDataType keyDataType = field.mapKeyDataType;
GPBDataType valueDataType = GPBGetFieldDataType(field);
- NSString *keyStr = TypeToStr(keyDataType);
- NSString *valueStr = TypeToStr(valueDataType);
+ NSString *keyStr = TypeToString(keyDataType);
+ NSString *valueStr = TypeToString(valueDataType);
if (keyDataType == GPBDataTypeString) {
keyStr = @"String";
}
@@ -1216,8 +1466,11 @@ void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field,
const char *GPBMessageEncodingForSelector(SEL selector, BOOL instanceSel) {
Protocol *protocol =
objc_getProtocol(GPBStringifySymbol(GPBMessageSignatureProtocol));
+ NSCAssert(protocol, @"Missing GPBMessageSignatureProtocol");
struct objc_method_description description =
protocol_getMethodDescription(protocol, selector, NO, instanceSel);
+ NSCAssert(description.name != Nil && description.types != nil,
+ @"Missing method for selector %@", NSStringFromSelector(selector));
return description.types;
}
@@ -1911,13 +2164,3 @@ BOOL GPBClassHasSel(Class aClass, SEL sel) {
free(methodList);
return result;
}
-
-#pragma mark - GPBMessageSignatureProtocol
-
-// A series of selectors that are used solely to get @encoding values
-// for them by the dynamic protobuf runtime code. An object using the protocol
-// needs to be declared for the protocol to be valid at runtime.
-@interface GPBMessageSignatureProtocol : NSObject<GPBMessageSignatureProtocol>
-@end
-@implementation GPBMessageSignatureProtocol
-@end
diff --git a/objectivec/GPBUtilities_PackagePrivate.h b/objectivec/GPBUtilities_PackagePrivate.h
index 16859d48..ed424ce3 100644
--- a/objectivec/GPBUtilities_PackagePrivate.h
+++ b/objectivec/GPBUtilities_PackagePrivate.h
@@ -124,7 +124,7 @@ GPB_INLINE int64_t GPBDecodeZigZag64(uint64_t n) {
// thus always taking 10 bytes on the wire.)
GPB_INLINE uint32_t GPBEncodeZigZag32(int32_t n) {
// Note: the right-shift must be arithmetic
- return (uint32_t)((n << 1) ^ (n >> 31));
+ return ((uint32_t)n << 1) ^ (uint32_t)(n >> 31);
}
// Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers
@@ -133,7 +133,7 @@ GPB_INLINE uint32_t GPBEncodeZigZag32(int32_t n) {
// thus always taking 10 bytes on the wire.)
GPB_INLINE uint64_t GPBEncodeZigZag64(int64_t n) {
// Note: the right-shift must be arithmetic
- return (uint64_t)((n << 1) ^ (n >> 63));
+ return ((uint64_t)n << 1) ^ (uint64_t)(n >> 63);
}
#pragma clang diagnostic push
@@ -309,7 +309,8 @@ NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key,
// A series of selectors that are used solely to get @encoding values
// for them by the dynamic protobuf runtime code. See
-// GPBMessageEncodingForSelector for details.
+// GPBMessageEncodingForSelector for details. GPBRootObject conforms to
+// the protocol so that it is encoded in the Objective C runtime.
@protocol GPBMessageSignatureProtocol
@optional
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 1f1172b2..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,48 +835,19 @@
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 = (
- "\"$(SDKROOT)/Developer/Library/Frameworks\"",
"\"$(DEVELOPER_LIBRARY_DIR)/Frameworks\"",
"$(inherited)",
);
@@ -901,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",
@@ -915,8 +881,8 @@
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_WEAK = YES;
FRAMEWORK_SEARCH_PATHS = (
- "\"$(SDKROOT)/Developer/Library/Frameworks\"",
"\"$(DEVELOPER_LIBRARY_DIR)/Frameworks\"",
"$(inherited)",
);
@@ -936,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",
@@ -1089,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";
@@ -1098,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";
@@ -1107,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;
};
@@ -1128,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 7226f0b9..469a61fb 100644
--- a/objectivec/README.md
+++ b/objectivec/README.md
@@ -33,19 +33,21 @@ Building
There are two ways to include the Runtime sources in your project:
-Add `objectivec/\*.h` & `objectivec/GPBProtocolBuffers.m` to your project.
+Add `objectivec/*.h`, `objectivec/google/protobuf/*.pbobjc.h`, and
+`objectivec/GPBProtocolBuffers.m` to your project.
*or*
-Add `objectivec/\*.h` & `objectivec/\*.m` except for
+Add `objectivec/*.h`, `objectivec/google/protobuf/*.pbobjc.h`,
+`objectivec/google/protobuf/*.pbobjc.m`, and `objectivec/*.m` except for
`objectivec/GPBProtocolBuffers.m` to your project.
If the target is using ARC, remember to turn off ARC (`-fno-objc-arc`) for the
`.m` files.
-The files generated by `protoc` for the `*.proto` files (`\*.pbobjc.h` and
-`\*.pbobjc.m`) are then also added to the target.
+The files generated by `protoc` for the `*.proto` files (`*.pbobjc.h` and
+`*.pbobjc.m`) are then also added to the target.
Usage
-----
diff --git a/objectivec/Tests/GPBCodedInputStreamTests.m b/objectivec/Tests/GPBCodedInputStreamTests.m
index d8e128f7..f5aa6903 100644
--- a/objectivec/Tests/GPBCodedInputStreamTests.m
+++ b/objectivec/Tests/GPBCodedInputStreamTests.m
@@ -220,7 +220,7 @@
0xa6, 0x01)
value:(0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
(0x3bLL << 28) | (0x56LL << 35) | (0x00LL << 42) |
- (0x05LL << 49) | (0x26LL << 56) | (0x01LL << 63)];
+ (0x05LL << 49) | (0x26LL << 56) | (0x01ULL << 63)];
// Failures
[self assertReadVarintFailure:bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
@@ -261,7 +261,7 @@
GPBCodedInputStream* input32 = [GPBCodedInputStream streamWithData:data];
XCTAssertEqual(value32, [input32 readInt32]);
- int64_t value64 = INT64_MIN | (0x01L << 31);
+ int64_t value64 = INT64_MIN | (0x01LL << 31);
GPBCodedInputStream* input64 = [GPBCodedInputStream streamWithData:data];
XCTAssertEqual(value64, [input64 readInt64]);
}
diff --git a/objectivec/Tests/GPBCodedOuputStreamTests.m b/objectivec/Tests/GPBCodedOuputStreamTests.m
index 2ad326be..109239d5 100644
--- a/objectivec/Tests/GPBCodedOuputStreamTests.m
+++ b/objectivec/Tests/GPBCodedOuputStreamTests.m
@@ -266,7 +266,7 @@
value:(0x1b << 0) | (0x28 << 7) | (0x79 << 14) |
(0x42 << 21) | (0x3bLL << 28) | (0x56LL << 35) |
(0x00LL << 42) | (0x05LL << 49) | (0x26LL << 56) |
- (0x01LL << 63)];
+ (0x01ULL << 63)];
}
- (void)testWriteLittleEndian {
@@ -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/src/google/protobuf/unittest_import_public_proto3.proto b/objectivec/Tests/GPBCompileTest01.m
index d6f11e28..c8bc433a 100644
--- a/src/google/protobuf/unittest_import_public_proto3.proto
+++ b/objectivec/Tests/GPBCompileTest01.m
@@ -28,15 +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: liujisi@google.com (Pherl Liu)
-syntax = "proto3";
+// This is a test including a single public header to ensure things build.
+// It helps test that imports are complete/ordered correctly.
-package protobuf_unittest_import;
+#import "GPBArray.h"
-option java_package = "com.google.protobuf.test";
-option csharp_namespace = "Google.Protobuf.TestProtos";
-message PublicImportMessage {
- int32 e = 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_1 = 0;
diff --git a/objectivec/Tests/GPBCompileTest02.m b/objectivec/Tests/GPBCompileTest02.m
new file mode 100644
index 00000000..c44e201a
--- /dev/null
+++ b/objectivec/Tests/GPBCompileTest02.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 "GPBCodedInputStream.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_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/javanano/src/test/java/com/google/protobuf/nano/unittest_single_nano.proto b/objectivec/Tests/GPBCompileTest04.m
index 7de30c87..c31498f1 100644
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_single_nano.proto
+++ b/objectivec/Tests/GPBCompileTest04.m
@@ -28,11 +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_import;
+// 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";
+#import "GPBDescriptor.h"
-message SingleMessageNano {
-}
+
+// 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/javanano/src/test/java/com/google/protobuf/nano/unittest_stringutf8_nano.proto b/objectivec/Tests/GPBCompileTest05.m
index bbd677cf..adb72252 100644
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_stringutf8_nano.proto
+++ b/objectivec/Tests/GPBCompileTest05.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 "GPBDictionary.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_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/javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nameclash_nano.proto b/objectivec/Tests/GPBCompileTest07.m
index b31c4399..939bb709 100644
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nameclash_nano.proto
+++ b/objectivec/Tests/GPBCompileTest07.m
@@ -28,14 +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_import;
+// 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 = "MultipleNameClashNano";
-option java_multiple_files = true;
+#import "GPBMessage.h"
-message MultipleNameClashNano {
- optional int32 field = 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_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_enum_class_multiple_nano.proto b/objectivec/Tests/GPBCompileTest24.m
index 958e1f17..c81ea732 100644
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_multiple_nano.proto
+++ b/objectivec/Tests/GPBCompileTest24.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
+// proto2 syntax messages that are extendable, 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/Descriptor.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_24 = 0;
diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_merge_nano.proto b/objectivec/Tests/GPBCompileTest25.m
index ef4e2d2f..7a482b51 100644
--- a/javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_merge_nano.proto
+++ b/objectivec/Tests/GPBCompileTest25.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
+// extensions to proto2 syntax messages, 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/UnittestCustomOptions.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_25 = 0;
diff --git a/objectivec/Tests/GPBDictionaryTests+Bool.m b/objectivec/Tests/GPBDictionaryTests+Bool.m
index 0dbe07b6..0af0c815 100644
--- a/objectivec/Tests/GPBDictionaryTests+Bool.m
+++ b/objectivec/Tests/GPBDictionaryTests+Bool.m
@@ -63,7 +63,8 @@
}
- (void)testOne {
- GPBBoolUInt32Dictionary *dict = [GPBBoolUInt32Dictionary dictionaryWithUInt32:100U forKey:YES];
+ GPBBoolUInt32Dictionary *dict = [[GPBBoolUInt32Dictionary alloc] init];
+ [dict setUInt32:100U forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint32_t value;
@@ -76,6 +77,7 @@
XCTAssertEqual(aValue, 100U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -214,17 +216,18 @@
XCTAssertNotNil(dict);
GPBBoolUInt32Dictionary *dict2 =
- [GPBBoolUInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBBoolUInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolUInt32Dictionary *dict = [GPBBoolUInt32Dictionary dictionary];
+ GPBBoolUInt32Dictionary *dict = [[GPBBoolUInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -249,6 +252,7 @@
XCTAssertTrue([dict getUInt32:&value forKey:NO]);
XCTAssertEqual(value, 101U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -364,7 +368,8 @@
}
- (void)testOne {
- GPBBoolInt32Dictionary *dict = [GPBBoolInt32Dictionary dictionaryWithInt32:200 forKey:YES];
+ GPBBoolInt32Dictionary *dict = [[GPBBoolInt32Dictionary alloc] init];
+ [dict setInt32:200 forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -377,6 +382,7 @@
XCTAssertEqual(aValue, 200);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -515,17 +521,18 @@
XCTAssertNotNil(dict);
GPBBoolInt32Dictionary *dict2 =
- [GPBBoolInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBBoolInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolInt32Dictionary *dict = [GPBBoolInt32Dictionary dictionary];
+ GPBBoolInt32Dictionary *dict = [[GPBBoolInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -550,6 +557,7 @@
XCTAssertTrue([dict getInt32:&value forKey:NO]);
XCTAssertEqual(value, 201);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -665,7 +673,8 @@
}
- (void)testOne {
- GPBBoolUInt64Dictionary *dict = [GPBBoolUInt64Dictionary dictionaryWithUInt64:300U forKey:YES];
+ GPBBoolUInt64Dictionary *dict = [[GPBBoolUInt64Dictionary alloc] init];
+ [dict setUInt64:300U forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint64_t value;
@@ -678,6 +687,7 @@
XCTAssertEqual(aValue, 300U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -816,17 +826,18 @@
XCTAssertNotNil(dict);
GPBBoolUInt64Dictionary *dict2 =
- [GPBBoolUInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBBoolUInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolUInt64Dictionary *dict = [GPBBoolUInt64Dictionary dictionary];
+ GPBBoolUInt64Dictionary *dict = [[GPBBoolUInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -851,6 +862,7 @@
XCTAssertTrue([dict getUInt64:&value forKey:NO]);
XCTAssertEqual(value, 301U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -966,7 +978,8 @@
}
- (void)testOne {
- GPBBoolInt64Dictionary *dict = [GPBBoolInt64Dictionary dictionaryWithInt64:400 forKey:YES];
+ GPBBoolInt64Dictionary *dict = [[GPBBoolInt64Dictionary alloc] init];
+ [dict setInt64:400 forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int64_t value;
@@ -979,6 +992,7 @@
XCTAssertEqual(aValue, 400);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1117,17 +1131,18 @@
XCTAssertNotNil(dict);
GPBBoolInt64Dictionary *dict2 =
- [GPBBoolInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBBoolInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolInt64Dictionary *dict = [GPBBoolInt64Dictionary dictionary];
+ GPBBoolInt64Dictionary *dict = [[GPBBoolInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1152,6 +1167,7 @@
XCTAssertTrue([dict getInt64:&value forKey:NO]);
XCTAssertEqual(value, 401);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1267,7 +1283,8 @@
}
- (void)testOne {
- GPBBoolBoolDictionary *dict = [GPBBoolBoolDictionary dictionaryWithBool:NO forKey:YES];
+ GPBBoolBoolDictionary *dict = [[GPBBoolBoolDictionary alloc] init];
+ [dict setBool:NO forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
BOOL value;
@@ -1280,6 +1297,7 @@
XCTAssertEqual(aValue, NO);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1418,17 +1436,18 @@
XCTAssertNotNil(dict);
GPBBoolBoolDictionary *dict2 =
- [GPBBoolBoolDictionary dictionaryWithDictionary:dict];
+ [[GPBBoolBoolDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolBoolDictionary *dict = [GPBBoolBoolDictionary dictionary];
+ GPBBoolBoolDictionary *dict = [[GPBBoolBoolDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1453,6 +1472,7 @@
XCTAssertTrue([dict getBool:&value forKey:NO]);
XCTAssertEqual(value, YES);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1568,7 +1588,8 @@
}
- (void)testOne {
- GPBBoolFloatDictionary *dict = [GPBBoolFloatDictionary dictionaryWithFloat:500.f forKey:YES];
+ GPBBoolFloatDictionary *dict = [[GPBBoolFloatDictionary alloc] init];
+ [dict setFloat:500.f forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
float value;
@@ -1581,6 +1602,7 @@
XCTAssertEqual(aValue, 500.f);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1719,17 +1741,18 @@
XCTAssertNotNil(dict);
GPBBoolFloatDictionary *dict2 =
- [GPBBoolFloatDictionary dictionaryWithDictionary:dict];
+ [[GPBBoolFloatDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolFloatDictionary *dict = [GPBBoolFloatDictionary dictionary];
+ GPBBoolFloatDictionary *dict = [[GPBBoolFloatDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1754,6 +1777,7 @@
XCTAssertTrue([dict getFloat:&value forKey:NO]);
XCTAssertEqual(value, 501.f);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1869,7 +1893,8 @@
}
- (void)testOne {
- GPBBoolDoubleDictionary *dict = [GPBBoolDoubleDictionary dictionaryWithDouble:600. forKey:YES];
+ GPBBoolDoubleDictionary *dict = [[GPBBoolDoubleDictionary alloc] init];
+ [dict setDouble:600. forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
double value;
@@ -1882,6 +1907,7 @@
XCTAssertEqual(aValue, 600.);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2020,17 +2046,18 @@
XCTAssertNotNil(dict);
GPBBoolDoubleDictionary *dict2 =
- [GPBBoolDoubleDictionary dictionaryWithDictionary:dict];
+ [[GPBBoolDoubleDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolDoubleDictionary *dict = [GPBBoolDoubleDictionary dictionary];
+ GPBBoolDoubleDictionary *dict = [[GPBBoolDoubleDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2055,6 +2082,7 @@
XCTAssertTrue([dict getDouble:&value forKey:NO]);
XCTAssertEqual(value, 601.);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2170,7 +2198,8 @@
}
- (void)testOne {
- GPBBoolObjectDictionary<NSString*> *dict = [GPBBoolObjectDictionary dictionaryWithObject:@"abc" forKey:YES];
+ GPBBoolObjectDictionary<NSString*> *dict = [[GPBBoolObjectDictionary alloc] init];
+ [dict setObject:@"abc" forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
XCTAssertEqualObjects([dict objectForKey:YES], @"abc");
@@ -2180,6 +2209,7 @@
XCTAssertEqualObjects(aObject, @"abc");
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2313,17 +2343,18 @@
XCTAssertNotNil(dict);
GPBBoolObjectDictionary<NSString*> *dict2 =
- [GPBBoolObjectDictionary dictionaryWithDictionary:dict];
+ [[GPBBoolObjectDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolObjectDictionary<NSString*> *dict = [GPBBoolObjectDictionary dictionary];
+ GPBBoolObjectDictionary<NSString*> *dict = [[GPBBoolObjectDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2343,6 +2374,7 @@
XCTAssertEqualObjects([dict objectForKey:YES], @"abc");
XCTAssertEqualObjects([dict objectForKey:NO], @"def");
[dict2 release];
+ [dict release];
}
- (void)testRemove {
diff --git a/objectivec/Tests/GPBDictionaryTests+Int32.m b/objectivec/Tests/GPBDictionaryTests+Int32.m
index c539bdc2..4ba30203 100644
--- a/objectivec/Tests/GPBDictionaryTests+Int32.m
+++ b/objectivec/Tests/GPBDictionaryTests+Int32.m
@@ -45,7 +45,6 @@
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBInt32EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(int32_t)key;
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count;
@@ -64,14 +63,6 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
@implementation GPBInt32EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(int32_t)key {
- // Cast is needed to compiler knows what class we are invoking initWithValues: on to get the
- // type correct.
- return [[(GPBInt32EnumDictionary*)[self alloc] initWithValidationFunction:TestingEnum_IsValidValue
- rawValues:&value
- forKeys:&key
- count:1] autorelease];
-}
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count {
@@ -103,7 +94,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32UInt32Dictionary *dict = [GPBInt32UInt32Dictionary dictionaryWithUInt32:100U forKey:11];
+ GPBInt32UInt32Dictionary *dict = [[GPBInt32UInt32Dictionary alloc] init];
+ [dict setUInt32:100U forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint32_t value;
@@ -116,6 +108,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 100U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -258,17 +251,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32UInt32Dictionary *dict2 =
- [GPBInt32UInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt32UInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32UInt32Dictionary *dict = [GPBInt32UInt32Dictionary dictionary];
+ GPBInt32UInt32Dictionary *dict = [[GPBInt32UInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -299,6 +293,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt32:&value forKey:14]);
XCTAssertEqual(value, 103U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -460,7 +455,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32Int32Dictionary *dict = [GPBInt32Int32Dictionary dictionaryWithInt32:200 forKey:11];
+ GPBInt32Int32Dictionary *dict = [[GPBInt32Int32Dictionary alloc] init];
+ [dict setInt32:200 forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -473,6 +469,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 200);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -615,17 +612,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32Int32Dictionary *dict2 =
- [GPBInt32Int32Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt32Int32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32Int32Dictionary *dict = [GPBInt32Int32Dictionary dictionary];
+ GPBInt32Int32Dictionary *dict = [[GPBInt32Int32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -656,6 +654,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt32:&value forKey:14]);
XCTAssertEqual(value, 203);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -817,7 +816,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32UInt64Dictionary *dict = [GPBInt32UInt64Dictionary dictionaryWithUInt64:300U forKey:11];
+ GPBInt32UInt64Dictionary *dict = [[GPBInt32UInt64Dictionary alloc] init];
+ [dict setUInt64:300U forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint64_t value;
@@ -830,6 +830,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 300U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -972,17 +973,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32UInt64Dictionary *dict2 =
- [GPBInt32UInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt32UInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32UInt64Dictionary *dict = [GPBInt32UInt64Dictionary dictionary];
+ GPBInt32UInt64Dictionary *dict = [[GPBInt32UInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1013,6 +1015,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt64:&value forKey:14]);
XCTAssertEqual(value, 303U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1174,7 +1177,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32Int64Dictionary *dict = [GPBInt32Int64Dictionary dictionaryWithInt64:400 forKey:11];
+ GPBInt32Int64Dictionary *dict = [[GPBInt32Int64Dictionary alloc] init];
+ [dict setInt64:400 forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int64_t value;
@@ -1187,6 +1191,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 400);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1329,17 +1334,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32Int64Dictionary *dict2 =
- [GPBInt32Int64Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt32Int64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32Int64Dictionary *dict = [GPBInt32Int64Dictionary dictionary];
+ GPBInt32Int64Dictionary *dict = [[GPBInt32Int64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1370,6 +1376,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt64:&value forKey:14]);
XCTAssertEqual(value, 403);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1531,7 +1538,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32BoolDictionary *dict = [GPBInt32BoolDictionary dictionaryWithBool:YES forKey:11];
+ GPBInt32BoolDictionary *dict = [[GPBInt32BoolDictionary alloc] init];
+ [dict setBool:YES forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
BOOL value;
@@ -1544,6 +1552,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, YES);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1686,17 +1695,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32BoolDictionary *dict2 =
- [GPBInt32BoolDictionary dictionaryWithDictionary:dict];
+ [[GPBInt32BoolDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32BoolDictionary *dict = [GPBInt32BoolDictionary dictionary];
+ GPBInt32BoolDictionary *dict = [[GPBInt32BoolDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1727,6 +1737,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getBool:&value forKey:14]);
XCTAssertEqual(value, NO);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1888,7 +1899,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32FloatDictionary *dict = [GPBInt32FloatDictionary dictionaryWithFloat:500.f forKey:11];
+ GPBInt32FloatDictionary *dict = [[GPBInt32FloatDictionary alloc] init];
+ [dict setFloat:500.f forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
float value;
@@ -1901,6 +1913,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 500.f);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2043,17 +2056,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32FloatDictionary *dict2 =
- [GPBInt32FloatDictionary dictionaryWithDictionary:dict];
+ [[GPBInt32FloatDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32FloatDictionary *dict = [GPBInt32FloatDictionary dictionary];
+ GPBInt32FloatDictionary *dict = [[GPBInt32FloatDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2084,6 +2098,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getFloat:&value forKey:14]);
XCTAssertEqual(value, 503.f);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2245,7 +2260,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32DoubleDictionary *dict = [GPBInt32DoubleDictionary dictionaryWithDouble:600. forKey:11];
+ GPBInt32DoubleDictionary *dict = [[GPBInt32DoubleDictionary alloc] init];
+ [dict setDouble:600. forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
double value;
@@ -2258,6 +2274,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 600.);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2400,17 +2417,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32DoubleDictionary *dict2 =
- [GPBInt32DoubleDictionary dictionaryWithDictionary:dict];
+ [[GPBInt32DoubleDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32DoubleDictionary *dict = [GPBInt32DoubleDictionary dictionary];
+ GPBInt32DoubleDictionary *dict = [[GPBInt32DoubleDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2441,6 +2459,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getDouble:&value forKey:14]);
XCTAssertEqual(value, 603.);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2602,7 +2621,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32EnumDictionary *dict = [GPBInt32EnumDictionary dictionaryWithEnum:700 forKey:11];
+ GPBInt32EnumDictionary *dict = [[GPBInt32EnumDictionary alloc] init];
+ [dict setEnum:700 forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -2615,6 +2635,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 700);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2757,17 +2778,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32EnumDictionary *dict2 =
- [GPBInt32EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBInt32EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32EnumDictionary *dict = [GPBInt32EnumDictionary dictionary];
+ GPBInt32EnumDictionary *dict = [[GPBInt32EnumDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2798,6 +2820,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getEnum:&value forKey:14]);
XCTAssertEqual(value, 703);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -3120,19 +3143,20 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32EnumDictionary *dict2 =
- [GPBInt32EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBInt32EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison
+ [dict2 release];
[dict release];
}
- (void)testUnknownAdds {
GPBInt32EnumDictionary *dict =
- [GPBInt32EnumDictionary dictionaryWithValidationFunction:TestingEnum_IsValidValue];
+ [[GPBInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3172,6 +3196,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getRawValue:&value forKey:14]);
XCTAssertEqual(value, 803);
[dict2 release];
+ [dict release];
}
- (void)testUnknownRemove {
@@ -3375,7 +3400,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32ObjectDictionary<NSString*> *dict = [GPBInt32ObjectDictionary dictionaryWithObject:@"abc" forKey:11];
+ GPBInt32ObjectDictionary<NSString*> *dict = [[GPBInt32ObjectDictionary alloc] init];
+ [dict setObject:@"abc" forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
XCTAssertEqualObjects([dict objectForKey:11], @"abc");
@@ -3385,6 +3411,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects(aObject, @"abc");
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -3520,17 +3547,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32ObjectDictionary<NSString*> *dict2 =
- [GPBInt32ObjectDictionary dictionaryWithDictionary:dict];
+ [[GPBInt32ObjectDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32ObjectDictionary<NSString*> *dict = [GPBInt32ObjectDictionary dictionary];
+ GPBInt32ObjectDictionary<NSString*> *dict = [[GPBInt32ObjectDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3552,6 +3580,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects([dict objectForKey:13], @"ghi");
XCTAssertEqualObjects([dict objectForKey:14], @"jkl");
[dict2 release];
+ [dict release];
}
- (void)testRemove {
diff --git a/objectivec/Tests/GPBDictionaryTests+Int64.m b/objectivec/Tests/GPBDictionaryTests+Int64.m
index b90cdf8c..966024b7 100644
--- a/objectivec/Tests/GPBDictionaryTests+Int64.m
+++ b/objectivec/Tests/GPBDictionaryTests+Int64.m
@@ -45,7 +45,6 @@
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBInt64EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(int64_t)key;
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count;
@@ -64,14 +63,6 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
@implementation GPBInt64EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(int64_t)key {
- // Cast is needed to compiler knows what class we are invoking initWithValues: on to get the
- // type correct.
- return [[(GPBInt64EnumDictionary*)[self alloc] initWithValidationFunction:TestingEnum_IsValidValue
- rawValues:&value
- forKeys:&key
- count:1] autorelease];
-}
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count {
@@ -103,7 +94,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64UInt32Dictionary *dict = [GPBInt64UInt32Dictionary dictionaryWithUInt32:100U forKey:21LL];
+ GPBInt64UInt32Dictionary *dict = [[GPBInt64UInt32Dictionary alloc] init];
+ [dict setUInt32:100U forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint32_t value;
@@ -116,6 +108,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 100U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -258,17 +251,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64UInt32Dictionary *dict2 =
- [GPBInt64UInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt64UInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64UInt32Dictionary *dict = [GPBInt64UInt32Dictionary dictionary];
+ GPBInt64UInt32Dictionary *dict = [[GPBInt64UInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -299,6 +293,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt32:&value forKey:24LL]);
XCTAssertEqual(value, 103U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -460,7 +455,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64Int32Dictionary *dict = [GPBInt64Int32Dictionary dictionaryWithInt32:200 forKey:21LL];
+ GPBInt64Int32Dictionary *dict = [[GPBInt64Int32Dictionary alloc] init];
+ [dict setInt32:200 forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -473,6 +469,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 200);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -615,17 +612,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64Int32Dictionary *dict2 =
- [GPBInt64Int32Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt64Int32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64Int32Dictionary *dict = [GPBInt64Int32Dictionary dictionary];
+ GPBInt64Int32Dictionary *dict = [[GPBInt64Int32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -656,6 +654,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt32:&value forKey:24LL]);
XCTAssertEqual(value, 203);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -817,7 +816,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64UInt64Dictionary *dict = [GPBInt64UInt64Dictionary dictionaryWithUInt64:300U forKey:21LL];
+ GPBInt64UInt64Dictionary *dict = [[GPBInt64UInt64Dictionary alloc] init];
+ [dict setUInt64:300U forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint64_t value;
@@ -830,6 +830,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 300U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -972,17 +973,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64UInt64Dictionary *dict2 =
- [GPBInt64UInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt64UInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64UInt64Dictionary *dict = [GPBInt64UInt64Dictionary dictionary];
+ GPBInt64UInt64Dictionary *dict = [[GPBInt64UInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1013,6 +1015,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt64:&value forKey:24LL]);
XCTAssertEqual(value, 303U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1174,7 +1177,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64Int64Dictionary *dict = [GPBInt64Int64Dictionary dictionaryWithInt64:400 forKey:21LL];
+ GPBInt64Int64Dictionary *dict = [[GPBInt64Int64Dictionary alloc] init];
+ [dict setInt64:400 forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int64_t value;
@@ -1187,6 +1191,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 400);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1329,17 +1334,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64Int64Dictionary *dict2 =
- [GPBInt64Int64Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt64Int64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64Int64Dictionary *dict = [GPBInt64Int64Dictionary dictionary];
+ GPBInt64Int64Dictionary *dict = [[GPBInt64Int64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1370,6 +1376,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt64:&value forKey:24LL]);
XCTAssertEqual(value, 403);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1531,7 +1538,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64BoolDictionary *dict = [GPBInt64BoolDictionary dictionaryWithBool:YES forKey:21LL];
+ GPBInt64BoolDictionary *dict = [[GPBInt64BoolDictionary alloc] init];
+ [dict setBool:YES forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
BOOL value;
@@ -1544,6 +1552,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, YES);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1686,17 +1695,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64BoolDictionary *dict2 =
- [GPBInt64BoolDictionary dictionaryWithDictionary:dict];
+ [[GPBInt64BoolDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64BoolDictionary *dict = [GPBInt64BoolDictionary dictionary];
+ GPBInt64BoolDictionary *dict = [[GPBInt64BoolDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1727,6 +1737,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getBool:&value forKey:24LL]);
XCTAssertEqual(value, NO);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1888,7 +1899,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64FloatDictionary *dict = [GPBInt64FloatDictionary dictionaryWithFloat:500.f forKey:21LL];
+ GPBInt64FloatDictionary *dict = [[GPBInt64FloatDictionary alloc] init];
+ [dict setFloat:500.f forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
float value;
@@ -1901,6 +1913,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 500.f);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2043,17 +2056,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64FloatDictionary *dict2 =
- [GPBInt64FloatDictionary dictionaryWithDictionary:dict];
+ [[GPBInt64FloatDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64FloatDictionary *dict = [GPBInt64FloatDictionary dictionary];
+ GPBInt64FloatDictionary *dict = [[GPBInt64FloatDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2084,6 +2098,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getFloat:&value forKey:24LL]);
XCTAssertEqual(value, 503.f);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2245,7 +2260,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64DoubleDictionary *dict = [GPBInt64DoubleDictionary dictionaryWithDouble:600. forKey:21LL];
+ GPBInt64DoubleDictionary *dict = [[GPBInt64DoubleDictionary alloc] init];
+ [dict setDouble:600. forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
double value;
@@ -2258,6 +2274,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 600.);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2400,17 +2417,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64DoubleDictionary *dict2 =
- [GPBInt64DoubleDictionary dictionaryWithDictionary:dict];
+ [[GPBInt64DoubleDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64DoubleDictionary *dict = [GPBInt64DoubleDictionary dictionary];
+ GPBInt64DoubleDictionary *dict = [[GPBInt64DoubleDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2441,6 +2459,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getDouble:&value forKey:24LL]);
XCTAssertEqual(value, 603.);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2602,7 +2621,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64EnumDictionary *dict = [GPBInt64EnumDictionary dictionaryWithEnum:700 forKey:21LL];
+ GPBInt64EnumDictionary *dict = [[GPBInt64EnumDictionary alloc] init];
+ [dict setEnum:700 forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -2615,6 +2635,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 700);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2757,17 +2778,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64EnumDictionary *dict2 =
- [GPBInt64EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBInt64EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64EnumDictionary *dict = [GPBInt64EnumDictionary dictionary];
+ GPBInt64EnumDictionary *dict = [[GPBInt64EnumDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2798,6 +2820,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getEnum:&value forKey:24LL]);
XCTAssertEqual(value, 703);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -3120,19 +3143,20 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64EnumDictionary *dict2 =
- [GPBInt64EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBInt64EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison
+ [dict2 release];
[dict release];
}
- (void)testUnknownAdds {
GPBInt64EnumDictionary *dict =
- [GPBInt64EnumDictionary dictionaryWithValidationFunction:TestingEnum_IsValidValue];
+ [[GPBInt64EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3172,6 +3196,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getRawValue:&value forKey:24LL]);
XCTAssertEqual(value, 803);
[dict2 release];
+ [dict release];
}
- (void)testUnknownRemove {
@@ -3375,7 +3400,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64ObjectDictionary<NSString*> *dict = [GPBInt64ObjectDictionary dictionaryWithObject:@"abc" forKey:21LL];
+ GPBInt64ObjectDictionary<NSString*> *dict = [[GPBInt64ObjectDictionary alloc] init];
+ [dict setObject:@"abc" forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
XCTAssertEqualObjects([dict objectForKey:21LL], @"abc");
@@ -3385,6 +3411,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects(aObject, @"abc");
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -3520,17 +3547,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64ObjectDictionary<NSString*> *dict2 =
- [GPBInt64ObjectDictionary dictionaryWithDictionary:dict];
+ [[GPBInt64ObjectDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64ObjectDictionary<NSString*> *dict = [GPBInt64ObjectDictionary dictionary];
+ GPBInt64ObjectDictionary<NSString*> *dict = [[GPBInt64ObjectDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3552,6 +3580,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects([dict objectForKey:23LL], @"ghi");
XCTAssertEqualObjects([dict objectForKey:24LL], @"jkl");
[dict2 release];
+ [dict release];
}
- (void)testRemove {
diff --git a/objectivec/Tests/GPBDictionaryTests+String.m b/objectivec/Tests/GPBDictionaryTests+String.m
index 5df1d51d..82d7952b 100644
--- a/objectivec/Tests/GPBDictionaryTests+String.m
+++ b/objectivec/Tests/GPBDictionaryTests+String.m
@@ -45,7 +45,6 @@
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBStringEnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(NSString *)key;
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const NSString * [])keys
count:(NSUInteger)count;
@@ -64,14 +63,6 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
@implementation GPBStringEnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(NSString *)key {
- // Cast is needed to compiler knows what class we are invoking initWithValues: on to get the
- // type correct.
- return [[(GPBStringEnumDictionary*)[self alloc] initWithValidationFunction:TestingEnum_IsValidValue
- rawValues:&value
- forKeys:&key
- count:1] autorelease];
-}
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const NSString * [])keys
count:(NSUInteger)count {
@@ -103,7 +94,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringUInt32Dictionary *dict = [GPBStringUInt32Dictionary dictionaryWithUInt32:100U forKey:@"foo"];
+ GPBStringUInt32Dictionary *dict = [[GPBStringUInt32Dictionary alloc] init];
+ [dict setUInt32:100U forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint32_t value;
@@ -116,6 +108,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 100U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -258,17 +251,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringUInt32Dictionary *dict2 =
- [GPBStringUInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBStringUInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringUInt32Dictionary *dict = [GPBStringUInt32Dictionary dictionary];
+ GPBStringUInt32Dictionary *dict = [[GPBStringUInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -299,6 +293,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt32:&value forKey:@"mumble"]);
XCTAssertEqual(value, 103U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -460,7 +455,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringInt32Dictionary *dict = [GPBStringInt32Dictionary dictionaryWithInt32:200 forKey:@"foo"];
+ GPBStringInt32Dictionary *dict = [[GPBStringInt32Dictionary alloc] init];
+ [dict setInt32:200 forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -473,6 +469,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 200);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -615,17 +612,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringInt32Dictionary *dict2 =
- [GPBStringInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBStringInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringInt32Dictionary *dict = [GPBStringInt32Dictionary dictionary];
+ GPBStringInt32Dictionary *dict = [[GPBStringInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -656,6 +654,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt32:&value forKey:@"mumble"]);
XCTAssertEqual(value, 203);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -817,7 +816,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringUInt64Dictionary *dict = [GPBStringUInt64Dictionary dictionaryWithUInt64:300U forKey:@"foo"];
+ GPBStringUInt64Dictionary *dict = [[GPBStringUInt64Dictionary alloc] init];
+ [dict setUInt64:300U forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint64_t value;
@@ -830,6 +830,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 300U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -972,17 +973,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringUInt64Dictionary *dict2 =
- [GPBStringUInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBStringUInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringUInt64Dictionary *dict = [GPBStringUInt64Dictionary dictionary];
+ GPBStringUInt64Dictionary *dict = [[GPBStringUInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1013,6 +1015,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt64:&value forKey:@"mumble"]);
XCTAssertEqual(value, 303U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1174,7 +1177,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringInt64Dictionary *dict = [GPBStringInt64Dictionary dictionaryWithInt64:400 forKey:@"foo"];
+ GPBStringInt64Dictionary *dict = [[GPBStringInt64Dictionary alloc] init];
+ [dict setInt64:400 forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int64_t value;
@@ -1187,6 +1191,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 400);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1329,17 +1334,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringInt64Dictionary *dict2 =
- [GPBStringInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBStringInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringInt64Dictionary *dict = [GPBStringInt64Dictionary dictionary];
+ GPBStringInt64Dictionary *dict = [[GPBStringInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1370,6 +1376,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt64:&value forKey:@"mumble"]);
XCTAssertEqual(value, 403);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1531,7 +1538,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringBoolDictionary *dict = [GPBStringBoolDictionary dictionaryWithBool:YES forKey:@"foo"];
+ GPBStringBoolDictionary *dict = [[GPBStringBoolDictionary alloc] init];
+ [dict setBool:YES forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
BOOL value;
@@ -1544,6 +1552,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, YES);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1686,17 +1695,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringBoolDictionary *dict2 =
- [GPBStringBoolDictionary dictionaryWithDictionary:dict];
+ [[GPBStringBoolDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringBoolDictionary *dict = [GPBStringBoolDictionary dictionary];
+ GPBStringBoolDictionary *dict = [[GPBStringBoolDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1727,6 +1737,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getBool:&value forKey:@"mumble"]);
XCTAssertEqual(value, NO);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1888,7 +1899,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringFloatDictionary *dict = [GPBStringFloatDictionary dictionaryWithFloat:500.f forKey:@"foo"];
+ GPBStringFloatDictionary *dict = [[GPBStringFloatDictionary alloc] init];
+ [dict setFloat:500.f forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
float value;
@@ -1901,6 +1913,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 500.f);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2043,17 +2056,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringFloatDictionary *dict2 =
- [GPBStringFloatDictionary dictionaryWithDictionary:dict];
+ [[GPBStringFloatDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringFloatDictionary *dict = [GPBStringFloatDictionary dictionary];
+ GPBStringFloatDictionary *dict = [[GPBStringFloatDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2084,6 +2098,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getFloat:&value forKey:@"mumble"]);
XCTAssertEqual(value, 503.f);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2245,7 +2260,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringDoubleDictionary *dict = [GPBStringDoubleDictionary dictionaryWithDouble:600. forKey:@"foo"];
+ GPBStringDoubleDictionary *dict = [[GPBStringDoubleDictionary alloc] init];
+ [dict setDouble:600. forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
double value;
@@ -2258,6 +2274,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 600.);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2400,17 +2417,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringDoubleDictionary *dict2 =
- [GPBStringDoubleDictionary dictionaryWithDictionary:dict];
+ [[GPBStringDoubleDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringDoubleDictionary *dict = [GPBStringDoubleDictionary dictionary];
+ GPBStringDoubleDictionary *dict = [[GPBStringDoubleDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2441,6 +2459,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getDouble:&value forKey:@"mumble"]);
XCTAssertEqual(value, 603.);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2602,7 +2621,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringEnumDictionary *dict = [GPBStringEnumDictionary dictionaryWithEnum:700 forKey:@"foo"];
+ GPBStringEnumDictionary *dict = [[GPBStringEnumDictionary alloc] init];
+ [dict setEnum:700 forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -2615,6 +2635,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 700);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2757,17 +2778,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringEnumDictionary *dict2 =
- [GPBStringEnumDictionary dictionaryWithDictionary:dict];
+ [[GPBStringEnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringEnumDictionary *dict = [GPBStringEnumDictionary dictionary];
+ GPBStringEnumDictionary *dict = [[GPBStringEnumDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2798,6 +2820,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getEnum:&value forKey:@"mumble"]);
XCTAssertEqual(value, 703);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -3120,19 +3143,20 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringEnumDictionary *dict2 =
- [GPBStringEnumDictionary dictionaryWithDictionary:dict];
+ [[GPBStringEnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison
+ [dict2 release];
[dict release];
}
- (void)testUnknownAdds {
GPBStringEnumDictionary *dict =
- [GPBStringEnumDictionary dictionaryWithValidationFunction:TestingEnum_IsValidValue];
+ [[GPBStringEnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3172,6 +3196,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getRawValue:&value forKey:@"mumble"]);
XCTAssertEqual(value, 803);
[dict2 release];
+ [dict release];
}
- (void)testUnknownRemove {
diff --git a/objectivec/Tests/GPBDictionaryTests+UInt32.m b/objectivec/Tests/GPBDictionaryTests+UInt32.m
index 1d3f6f78..5314c58a 100644
--- a/objectivec/Tests/GPBDictionaryTests+UInt32.m
+++ b/objectivec/Tests/GPBDictionaryTests+UInt32.m
@@ -45,7 +45,6 @@
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBUInt32EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(uint32_t)key;
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count;
@@ -64,14 +63,6 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
@implementation GPBUInt32EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(uint32_t)key {
- // Cast is needed to compiler knows what class we are invoking initWithValues: on to get the
- // type correct.
- return [[(GPBUInt32EnumDictionary*)[self alloc] initWithValidationFunction:TestingEnum_IsValidValue
- rawValues:&value
- forKeys:&key
- count:1] autorelease];
-}
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count {
@@ -103,7 +94,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32UInt32Dictionary *dict = [GPBUInt32UInt32Dictionary dictionaryWithUInt32:100U forKey:1U];
+ GPBUInt32UInt32Dictionary *dict = [[GPBUInt32UInt32Dictionary alloc] init];
+ [dict setUInt32:100U forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint32_t value;
@@ -116,6 +108,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 100U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -258,17 +251,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32UInt32Dictionary *dict2 =
- [GPBUInt32UInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32UInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32UInt32Dictionary *dict = [GPBUInt32UInt32Dictionary dictionary];
+ GPBUInt32UInt32Dictionary *dict = [[GPBUInt32UInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -299,6 +293,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt32:&value forKey:4U]);
XCTAssertEqual(value, 103U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -460,7 +455,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32Int32Dictionary *dict = [GPBUInt32Int32Dictionary dictionaryWithInt32:200 forKey:1U];
+ GPBUInt32Int32Dictionary *dict = [[GPBUInt32Int32Dictionary alloc] init];
+ [dict setInt32:200 forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -473,6 +469,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 200);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -615,17 +612,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32Int32Dictionary *dict2 =
- [GPBUInt32Int32Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32Int32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32Int32Dictionary *dict = [GPBUInt32Int32Dictionary dictionary];
+ GPBUInt32Int32Dictionary *dict = [[GPBUInt32Int32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -656,6 +654,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt32:&value forKey:4U]);
XCTAssertEqual(value, 203);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -817,7 +816,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32UInt64Dictionary *dict = [GPBUInt32UInt64Dictionary dictionaryWithUInt64:300U forKey:1U];
+ GPBUInt32UInt64Dictionary *dict = [[GPBUInt32UInt64Dictionary alloc] init];
+ [dict setUInt64:300U forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint64_t value;
@@ -830,6 +830,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 300U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -972,17 +973,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32UInt64Dictionary *dict2 =
- [GPBUInt32UInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32UInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32UInt64Dictionary *dict = [GPBUInt32UInt64Dictionary dictionary];
+ GPBUInt32UInt64Dictionary *dict = [[GPBUInt32UInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1013,6 +1015,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt64:&value forKey:4U]);
XCTAssertEqual(value, 303U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1174,7 +1177,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32Int64Dictionary *dict = [GPBUInt32Int64Dictionary dictionaryWithInt64:400 forKey:1U];
+ GPBUInt32Int64Dictionary *dict = [[GPBUInt32Int64Dictionary alloc] init];
+ [dict setInt64:400 forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int64_t value;
@@ -1187,6 +1191,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 400);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1329,17 +1334,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32Int64Dictionary *dict2 =
- [GPBUInt32Int64Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32Int64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32Int64Dictionary *dict = [GPBUInt32Int64Dictionary dictionary];
+ GPBUInt32Int64Dictionary *dict = [[GPBUInt32Int64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1370,6 +1376,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt64:&value forKey:4U]);
XCTAssertEqual(value, 403);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1531,7 +1538,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32BoolDictionary *dict = [GPBUInt32BoolDictionary dictionaryWithBool:YES forKey:1U];
+ GPBUInt32BoolDictionary *dict = [[GPBUInt32BoolDictionary alloc] init];
+ [dict setBool:YES forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
BOOL value;
@@ -1544,6 +1552,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, YES);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1686,17 +1695,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32BoolDictionary *dict2 =
- [GPBUInt32BoolDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32BoolDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32BoolDictionary *dict = [GPBUInt32BoolDictionary dictionary];
+ GPBUInt32BoolDictionary *dict = [[GPBUInt32BoolDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1727,6 +1737,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getBool:&value forKey:4U]);
XCTAssertEqual(value, NO);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1888,7 +1899,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32FloatDictionary *dict = [GPBUInt32FloatDictionary dictionaryWithFloat:500.f forKey:1U];
+ GPBUInt32FloatDictionary *dict = [[GPBUInt32FloatDictionary alloc] init];
+ [dict setFloat:500.f forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
float value;
@@ -1901,6 +1913,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 500.f);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2043,17 +2056,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32FloatDictionary *dict2 =
- [GPBUInt32FloatDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32FloatDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32FloatDictionary *dict = [GPBUInt32FloatDictionary dictionary];
+ GPBUInt32FloatDictionary *dict = [[GPBUInt32FloatDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2084,6 +2098,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getFloat:&value forKey:4U]);
XCTAssertEqual(value, 503.f);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2245,7 +2260,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32DoubleDictionary *dict = [GPBUInt32DoubleDictionary dictionaryWithDouble:600. forKey:1U];
+ GPBUInt32DoubleDictionary *dict = [[GPBUInt32DoubleDictionary alloc] init];
+ [dict setDouble:600. forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
double value;
@@ -2258,6 +2274,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 600.);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2400,17 +2417,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32DoubleDictionary *dict2 =
- [GPBUInt32DoubleDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32DoubleDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32DoubleDictionary *dict = [GPBUInt32DoubleDictionary dictionary];
+ GPBUInt32DoubleDictionary *dict = [[GPBUInt32DoubleDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2441,6 +2459,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getDouble:&value forKey:4U]);
XCTAssertEqual(value, 603.);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2602,7 +2621,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32EnumDictionary *dict = [GPBUInt32EnumDictionary dictionaryWithEnum:700 forKey:1U];
+ GPBUInt32EnumDictionary *dict = [[GPBUInt32EnumDictionary alloc] init];
+ [dict setEnum:700 forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -2615,6 +2635,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 700);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2757,17 +2778,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32EnumDictionary *dict2 =
- [GPBUInt32EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32EnumDictionary *dict = [GPBUInt32EnumDictionary dictionary];
+ GPBUInt32EnumDictionary *dict = [[GPBUInt32EnumDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2798,6 +2820,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getEnum:&value forKey:4U]);
XCTAssertEqual(value, 703);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -3120,19 +3143,20 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32EnumDictionary *dict2 =
- [GPBUInt32EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison
+ [dict2 release];
[dict release];
}
- (void)testUnknownAdds {
GPBUInt32EnumDictionary *dict =
- [GPBUInt32EnumDictionary dictionaryWithValidationFunction:TestingEnum_IsValidValue];
+ [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3172,6 +3196,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getRawValue:&value forKey:4U]);
XCTAssertEqual(value, 803);
[dict2 release];
+ [dict release];
}
- (void)testUnknownRemove {
@@ -3375,7 +3400,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32ObjectDictionary<NSString*> *dict = [GPBUInt32ObjectDictionary dictionaryWithObject:@"abc" forKey:1U];
+ GPBUInt32ObjectDictionary<NSString*> *dict = [[GPBUInt32ObjectDictionary alloc] init];
+ [dict setObject:@"abc" forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
XCTAssertEqualObjects([dict objectForKey:1U], @"abc");
@@ -3385,6 +3411,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects(aObject, @"abc");
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -3520,17 +3547,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32ObjectDictionary<NSString*> *dict2 =
- [GPBUInt32ObjectDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32ObjectDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32ObjectDictionary<NSString*> *dict = [GPBUInt32ObjectDictionary dictionary];
+ GPBUInt32ObjectDictionary<NSString*> *dict = [[GPBUInt32ObjectDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3552,6 +3580,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects([dict objectForKey:3U], @"ghi");
XCTAssertEqualObjects([dict objectForKey:4U], @"jkl");
[dict2 release];
+ [dict release];
}
- (void)testRemove {
diff --git a/objectivec/Tests/GPBDictionaryTests+UInt64.m b/objectivec/Tests/GPBDictionaryTests+UInt64.m
index 94c116f6..ccd063f5 100644
--- a/objectivec/Tests/GPBDictionaryTests+UInt64.m
+++ b/objectivec/Tests/GPBDictionaryTests+UInt64.m
@@ -45,7 +45,6 @@
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBUInt64EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(uint64_t)key;
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count;
@@ -64,14 +63,6 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
@implementation GPBUInt64EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(uint64_t)key {
- // Cast is needed to compiler knows what class we are invoking initWithValues: on to get the
- // type correct.
- return [[(GPBUInt64EnumDictionary*)[self alloc] initWithValidationFunction:TestingEnum_IsValidValue
- rawValues:&value
- forKeys:&key
- count:1] autorelease];
-}
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count {
@@ -103,7 +94,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64UInt32Dictionary *dict = [GPBUInt64UInt32Dictionary dictionaryWithUInt32:100U forKey:31ULL];
+ GPBUInt64UInt32Dictionary *dict = [[GPBUInt64UInt32Dictionary alloc] init];
+ [dict setUInt32:100U forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint32_t value;
@@ -116,6 +108,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 100U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -258,17 +251,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64UInt32Dictionary *dict2 =
- [GPBUInt64UInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64UInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64UInt32Dictionary *dict = [GPBUInt64UInt32Dictionary dictionary];
+ GPBUInt64UInt32Dictionary *dict = [[GPBUInt64UInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -299,6 +293,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt32:&value forKey:34ULL]);
XCTAssertEqual(value, 103U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -460,7 +455,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64Int32Dictionary *dict = [GPBUInt64Int32Dictionary dictionaryWithInt32:200 forKey:31ULL];
+ GPBUInt64Int32Dictionary *dict = [[GPBUInt64Int32Dictionary alloc] init];
+ [dict setInt32:200 forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -473,6 +469,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 200);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -615,17 +612,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64Int32Dictionary *dict2 =
- [GPBUInt64Int32Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64Int32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64Int32Dictionary *dict = [GPBUInt64Int32Dictionary dictionary];
+ GPBUInt64Int32Dictionary *dict = [[GPBUInt64Int32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -656,6 +654,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt32:&value forKey:34ULL]);
XCTAssertEqual(value, 203);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -817,7 +816,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64UInt64Dictionary *dict = [GPBUInt64UInt64Dictionary dictionaryWithUInt64:300U forKey:31ULL];
+ GPBUInt64UInt64Dictionary *dict = [[GPBUInt64UInt64Dictionary alloc] init];
+ [dict setUInt64:300U forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint64_t value;
@@ -830,6 +830,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 300U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -972,17 +973,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64UInt64Dictionary *dict2 =
- [GPBUInt64UInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64UInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64UInt64Dictionary *dict = [GPBUInt64UInt64Dictionary dictionary];
+ GPBUInt64UInt64Dictionary *dict = [[GPBUInt64UInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1013,6 +1015,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt64:&value forKey:34ULL]);
XCTAssertEqual(value, 303U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1174,7 +1177,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64Int64Dictionary *dict = [GPBUInt64Int64Dictionary dictionaryWithInt64:400 forKey:31ULL];
+ GPBUInt64Int64Dictionary *dict = [[GPBUInt64Int64Dictionary alloc] init];
+ [dict setInt64:400 forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int64_t value;
@@ -1187,6 +1191,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 400);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1329,17 +1334,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64Int64Dictionary *dict2 =
- [GPBUInt64Int64Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64Int64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64Int64Dictionary *dict = [GPBUInt64Int64Dictionary dictionary];
+ GPBUInt64Int64Dictionary *dict = [[GPBUInt64Int64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1370,6 +1376,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt64:&value forKey:34ULL]);
XCTAssertEqual(value, 403);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1531,7 +1538,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64BoolDictionary *dict = [GPBUInt64BoolDictionary dictionaryWithBool:YES forKey:31ULL];
+ GPBUInt64BoolDictionary *dict = [[GPBUInt64BoolDictionary alloc] init];
+ [dict setBool:YES forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
BOOL value;
@@ -1544,6 +1552,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, YES);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1686,17 +1695,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64BoolDictionary *dict2 =
- [GPBUInt64BoolDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64BoolDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64BoolDictionary *dict = [GPBUInt64BoolDictionary dictionary];
+ GPBUInt64BoolDictionary *dict = [[GPBUInt64BoolDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1727,6 +1737,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getBool:&value forKey:34ULL]);
XCTAssertEqual(value, NO);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1888,7 +1899,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64FloatDictionary *dict = [GPBUInt64FloatDictionary dictionaryWithFloat:500.f forKey:31ULL];
+ GPBUInt64FloatDictionary *dict = [[GPBUInt64FloatDictionary alloc] init];
+ [dict setFloat:500.f forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
float value;
@@ -1901,6 +1913,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 500.f);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2043,17 +2056,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64FloatDictionary *dict2 =
- [GPBUInt64FloatDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64FloatDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64FloatDictionary *dict = [GPBUInt64FloatDictionary dictionary];
+ GPBUInt64FloatDictionary *dict = [[GPBUInt64FloatDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2084,6 +2098,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getFloat:&value forKey:34ULL]);
XCTAssertEqual(value, 503.f);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2245,7 +2260,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64DoubleDictionary *dict = [GPBUInt64DoubleDictionary dictionaryWithDouble:600. forKey:31ULL];
+ GPBUInt64DoubleDictionary *dict = [[GPBUInt64DoubleDictionary alloc] init];
+ [dict setDouble:600. forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
double value;
@@ -2258,6 +2274,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 600.);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2400,17 +2417,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64DoubleDictionary *dict2 =
- [GPBUInt64DoubleDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64DoubleDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64DoubleDictionary *dict = [GPBUInt64DoubleDictionary dictionary];
+ GPBUInt64DoubleDictionary *dict = [[GPBUInt64DoubleDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2441,6 +2459,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getDouble:&value forKey:34ULL]);
XCTAssertEqual(value, 603.);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2602,7 +2621,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64EnumDictionary *dict = [GPBUInt64EnumDictionary dictionaryWithEnum:700 forKey:31ULL];
+ GPBUInt64EnumDictionary *dict = [[GPBUInt64EnumDictionary alloc] init];
+ [dict setEnum:700 forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -2615,6 +2635,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 700);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2757,17 +2778,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64EnumDictionary *dict2 =
- [GPBUInt64EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64EnumDictionary *dict = [GPBUInt64EnumDictionary dictionary];
+ GPBUInt64EnumDictionary *dict = [[GPBUInt64EnumDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2798,6 +2820,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getEnum:&value forKey:34ULL]);
XCTAssertEqual(value, 703);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -3120,19 +3143,20 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64EnumDictionary *dict2 =
- [GPBUInt64EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison
+ [dict2 release];
[dict release];
}
- (void)testUnknownAdds {
GPBUInt64EnumDictionary *dict =
- [GPBUInt64EnumDictionary dictionaryWithValidationFunction:TestingEnum_IsValidValue];
+ [[GPBUInt64EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3172,6 +3196,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getRawValue:&value forKey:34ULL]);
XCTAssertEqual(value, 803);
[dict2 release];
+ [dict release];
}
- (void)testUnknownRemove {
@@ -3375,7 +3400,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64ObjectDictionary<NSString*> *dict = [GPBUInt64ObjectDictionary dictionaryWithObject:@"abc" forKey:31ULL];
+ GPBUInt64ObjectDictionary<NSString*> *dict = [[GPBUInt64ObjectDictionary alloc] init];
+ [dict setObject:@"abc" forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
XCTAssertEqualObjects([dict objectForKey:31ULL], @"abc");
@@ -3385,6 +3411,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects(aObject, @"abc");
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -3520,17 +3547,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64ObjectDictionary<NSString*> *dict2 =
- [GPBUInt64ObjectDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64ObjectDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64ObjectDictionary<NSString*> *dict = [GPBUInt64ObjectDictionary dictionary];
+ GPBUInt64ObjectDictionary<NSString*> *dict = [[GPBUInt64ObjectDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3552,6 +3580,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects([dict objectForKey:33ULL], @"ghi");
XCTAssertEqualObjects([dict objectForKey:34ULL], @"jkl");
[dict2 release];
+ [dict release];
}
- (void)testRemove {
diff --git a/objectivec/Tests/GPBDictionaryTests.pddm b/objectivec/Tests/GPBDictionaryTests.pddm
index d6aa7211..17f12c28 100644
--- a/objectivec/Tests/GPBDictionaryTests.pddm
+++ b/objectivec/Tests/GPBDictionaryTests.pddm
@@ -78,7 +78,8 @@
//%}
//%
//%- (void)testOne {
-//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionaryWith##VALUE_NAME$u##:VAL1 forKey:KEY1];
+//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init];
+//% [dict set##VALUE_NAME$u##:VAL1 forKey:KEY1];
//% XCTAssertNotNil(dict);
//% XCTAssertEqual(dict.count, 1U);
//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1)
@@ -88,6 +89,7 @@
//% XCTAssertEqual##VSUFFIX(a##VNAME$u, VAL1);
//% XCTAssertNotEqual(stop, NULL);
//% }];
+//% [dict release];
//%}
//%
//%- (void)testBasics {
@@ -223,17 +225,18 @@
//% XCTAssertNotNil(dict);
//%
//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 =
-//% [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionaryWithDictionary:dict];
+//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithDictionary:dict];
//% XCTAssertNotNil(dict2);
//%
//% // Should be new pointer, but equal objects.
//% XCTAssertNotEqual(dict, dict2);
//% XCTAssertEqualObjects(dict, dict2);
+//% [dict2 release];
//% [dict release];
//%}
//%
//%- (void)testAdds {
-//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionary];
+//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init];
//% XCTAssertNotNil(dict);
//%
//% XCTAssertEqual(dict.count, 0U);
@@ -255,6 +258,7 @@
//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY3, VAL3)
//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY4, VAL4)
//% [dict2 release];
+//% [dict release];
//%}
//%
//%- (void)testRemove {
@@ -522,19 +526,20 @@
//% XCTAssertNotNil(dict);
//%
//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 =
-//% [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionaryWithDictionary:dict];
+//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithDictionary:dict];
//% XCTAssertNotNil(dict2);
//%
//% // Should be new pointer, but equal objects.
//% XCTAssertNotEqual(dict, dict2);
//% XCTAssertEqualObjects(dict, dict2);
//% XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison
+//% [dict2 release];
//% [dict release];
//%}
//%
//%- (void)testUnknownAdds {
//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict =
-//% [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionaryWithValidationFunction:TestingEnum_IsValidValue];
+//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue];
//% XCTAssertNotNil(dict);
//%
//% XCTAssertEqual(dict.count, 0U);
@@ -561,6 +566,7 @@
//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY4, kGPBUnrecognizedEnumeratorValue)
//%TEST_RAW_VALUE##VHELPER(dict, value, KEY4, VAL4)
//% [dict2 release];
+//% [dict release];
//%}
//%
//%- (void)testUnknownRemove {
@@ -729,7 +735,6 @@
//%PDDM-DEFINE TEST_HELPERS(KEY_NAME, KEY_TYPE, KisP)
//%// To let the testing macros work, add some extra methods to simplify things.
//%@interface GPB##KEY_NAME##EnumDictionary (TestingTweak)
-//%+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(KEY_TYPE##KisP$S##KisP)key;
//%- (instancetype)initWithEnums:(const int32_t [])values
//% forKeys:(const KEY_TYPE##KisP$S##KisP [])keys
//% count:(NSUInteger)count;
@@ -748,14 +753,6 @@
//%}
//%
//%@implementation GPB##KEY_NAME##EnumDictionary (TestingTweak)
-//%+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(KEY_TYPE##KisP$S##KisP)key {
-//% // Cast is needed to compiler knows what class we are invoking initWithValues: on to get the
-//% // type correct.
-//% return [[(GPB##KEY_NAME##EnumDictionary*)[self alloc] initWithValidationFunction:TestingEnum_IsValidValue
-//% KEY_NAME$S rawValues:&value
-//% KEY_NAME$S forKeys:&key
-//% KEY_NAME$S count:1] autorelease];
-//%}
//%- (instancetype)initWithEnums:(const int32_t [])values
//% forKeys:(const KEY_TYPE##KisP$S##KisP [])keys
//% count:(NSUInteger)count {
@@ -801,7 +798,8 @@
//%}
//%
//%- (void)testOne {
-//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionaryWith##VALUE_NAME$u##:VAL1 forKey:KEY1];
+//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init];
+//% [dict set##VALUE_NAME$u##:VAL1 forKey:KEY1];
//% XCTAssertNotNil(dict);
//% XCTAssertEqual(dict.count, 1U);
//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1)
@@ -811,6 +809,7 @@
//% XCTAssertEqual##VSUFFIX(a##VNAME$u, VAL1);
//% XCTAssertNotEqual(stop, NULL);
//% }];
+//% [dict release];
//%}
//%
//%- (void)testBasics {
@@ -944,17 +943,18 @@
//% XCTAssertNotNil(dict);
//%
//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 =
-//% [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionaryWithDictionary:dict];
+//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithDictionary:dict];
//% XCTAssertNotNil(dict2);
//%
//% // Should be new pointer, but equal objects.
//% XCTAssertNotEqual(dict, dict2);
//% XCTAssertEqualObjects(dict, dict2);
+//% [dict2 release];
//% [dict release];
//%}
//%
//%- (void)testAdds {
-//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionary];
+//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init];
//% XCTAssertNotNil(dict);
//%
//% XCTAssertEqual(dict.count, 0U);
@@ -974,6 +974,7 @@
//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1)
//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY2, VAL2)
//% [dict2 release];
+//% [dict release];
//%}
//%
//%- (void)testRemove {
diff --git a/objectivec/Tests/GPBMessageTests+Serialization.m b/objectivec/Tests/GPBMessageTests+Serialization.m
index 55d77a1f..921feab7 100644
--- a/objectivec/Tests/GPBMessageTests+Serialization.m
+++ b/objectivec/Tests/GPBMessageTests+Serialization.m
@@ -1114,10 +1114,10 @@
- (void)testMap_Proto2UnknownEnum {
TestEnumMapPlusExtra *orig = [[TestEnumMapPlusExtra alloc] init];
- orig.knownMapField = [GPBInt32EnumDictionary
- dictionaryWithValidationFunction:Proto2MapEnumPlusExtra_IsValidValue];
- orig.unknownMapField = [GPBInt32EnumDictionary
- dictionaryWithValidationFunction:Proto2MapEnumPlusExtra_IsValidValue];
+ orig.knownMapField = [[[GPBInt32EnumDictionary alloc]
+ initWithValidationFunction:Proto2MapEnumPlusExtra_IsValidValue] autorelease];
+ orig.unknownMapField = [[[GPBInt32EnumDictionary alloc]
+ initWithValidationFunction:Proto2MapEnumPlusExtra_IsValidValue] autorelease];
[orig.knownMapField setEnum:Proto2MapEnumPlusExtra_EProto2MapEnumFoo
forKey:0];
[orig.unknownMapField setEnum:Proto2MapEnumPlusExtra_EProto2MapEnumExtra
diff --git a/objectivec/Tests/GPBMessageTests.m b/objectivec/Tests/GPBMessageTests.m
index c15535c5..a3149096 100644
--- a/objectivec/Tests/GPBMessageTests.m
+++ b/objectivec/Tests/GPBMessageTests.m
@@ -1238,7 +1238,8 @@
// with different objects that are equal).
TestRecursiveMessageWithRepeatedField *message3 =
[TestRecursiveMessageWithRepeatedField message];
- message3.iToI = [GPBInt32Int32Dictionary dictionaryWithInt32:10 forKey:20];
+ message3.iToI = [[[GPBInt32Int32Dictionary alloc] init] autorelease];
+ [message3.iToI setInt32:10 forKey:20];
message3.strToStr =
[NSMutableDictionary dictionaryWithObject:@"abc" forKey:@"123"];
XCTAssertNotNil(message.iToI);
@@ -1323,7 +1324,8 @@
XCTAssertFalse([message hasA]);
GPBInt32Int32Dictionary *iToI = [message.a.iToI retain];
XCTAssertEqual(iToI->_autocreator, message.a); // Pointer comparision
- message.a.iToI = [GPBInt32Int32Dictionary dictionaryWithInt32:6 forKey:7];
+ message.a.iToI = [[[GPBInt32Int32Dictionary alloc] init] autorelease];
+ [message.a.iToI setInt32:6 forKey:7];
XCTAssertTrue([message hasA]);
XCTAssertNotEqual(message.a.iToI, iToI); // Pointer comparision
XCTAssertNil(iToI->_autocreator);
@@ -2050,4 +2052,55 @@
XCTAssertEqual([msg1 hash], [msg1Prime hash]);
}
+- (void)testCopyingMapFileds {
+ TestMessageOfMaps *msg = [TestMessageOfMaps message];
+
+ msg.strToStr[@"foo"] = @"bar";
+
+ [msg.strToInt setInt32:1 forKey:@"mumble"];
+ [msg.intToStr setObject:@"wee" forKey:42];
+ [msg.intToInt setInt32:123 forKey:321];
+
+ [msg.strToBool setBool:YES forKey:@"one"];
+ [msg.boolToStr setObject:@"something" forKey:YES];
+ [msg.boolToBool setBool:YES forKey:NO];
+
+ [msg.intToBool setBool:YES forKey:13];
+ [msg.boolToInt setInt32:111 forKey:NO];
+
+ TestAllTypes *subMsg1 = [TestAllTypes message];
+ subMsg1.optionalInt32 = 1;
+ TestAllTypes *subMsg2 = [TestAllTypes message];
+ subMsg1.optionalInt32 = 2;
+ TestAllTypes *subMsg3 = [TestAllTypes message];
+ subMsg1.optionalInt32 = 3;
+
+ msg.strToMsg[@"baz"] = subMsg1;
+ [msg.intToMsg setObject:subMsg2 forKey:222];
+ [msg.boolToMsg setObject:subMsg3 forKey:YES];
+
+ TestMessageOfMaps *msg2 = [[msg copy] autorelease];
+ XCTAssertNotNil(msg2);
+ XCTAssertEqualObjects(msg2, msg);
+ XCTAssertTrue(msg2 != msg); // ptr compare
+ XCTAssertTrue(msg.strToStr != msg2.strToStr); // ptr compare
+ XCTAssertTrue(msg.intToStr != msg2.intToStr); // ptr compare
+ XCTAssertTrue(msg.intToInt != msg2.intToInt); // ptr compare
+ XCTAssertTrue(msg.strToBool != msg2.strToBool); // ptr compare
+ XCTAssertTrue(msg.boolToStr != msg2.boolToStr); // ptr compare
+ XCTAssertTrue(msg.boolToBool != msg2.boolToBool); // ptr compare
+ XCTAssertTrue(msg.intToBool != msg2.intToBool); // ptr compare
+ XCTAssertTrue(msg.boolToInt != msg2.boolToInt); // ptr compare
+ XCTAssertTrue(msg.strToMsg != msg2.strToMsg); // ptr compare
+ XCTAssertTrue(msg.intToMsg != msg2.intToMsg); // ptr compare
+ XCTAssertTrue(msg.boolToMsg != msg2.boolToMsg); // ptr compare
+
+ XCTAssertTrue(msg.strToMsg[@"baz"] != msg2.strToMsg[@"baz"]); // ptr compare
+ XCTAssertEqualObjects(msg.strToMsg[@"baz"], msg2.strToMsg[@"baz"]);
+ XCTAssertTrue([msg.intToMsg objectForKey:222] != [msg2.intToMsg objectForKey:222]); // ptr compare
+ XCTAssertEqualObjects([msg.intToMsg objectForKey:222], [msg2.intToMsg objectForKey:222]);
+ XCTAssertTrue([msg.boolToMsg objectForKey:YES] != [msg2.boolToMsg objectForKey:YES]); // ptr compare
+ XCTAssertEqualObjects([msg.boolToMsg objectForKey:YES], [msg2.boolToMsg objectForKey:YES]);
+}
+
@end
diff --git a/objectivec/Tests/GPBUtilitiesTests.m b/objectivec/Tests/GPBUtilitiesTests.m
index 2e206a54..8a8ba93e 100644
--- a/objectivec/Tests/GPBUtilitiesTests.m
+++ b/objectivec/Tests/GPBUtilitiesTests.m
@@ -52,12 +52,12 @@
- (void)testRightShiftFunctions {
XCTAssertEqual((1UL << 31) >> 31, 1UL);
- XCTAssertEqual((1 << 31) >> 31, -1);
+ XCTAssertEqual((int32_t)(1U << 31) >> 31, -1);
XCTAssertEqual((1ULL << 63) >> 63, 1ULL);
- XCTAssertEqual((1LL << 63) >> 63, -1LL);
+ XCTAssertEqual((int64_t)(1ULL << 63) >> 63, -1LL);
- XCTAssertEqual(GPBLogicalRightShift32((1 << 31), 31), 1);
- XCTAssertEqual(GPBLogicalRightShift64((1LL << 63), 63), 1LL);
+ XCTAssertEqual(GPBLogicalRightShift32((1U << 31), 31), 1);
+ XCTAssertEqual(GPBLogicalRightShift64((1ULL << 63), 63), 1LL);
}
- (void)testGPBDecodeTextFormatName {
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 0cbf9acc..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/Contents.json
+++ /dev/null
@@ -1,116 +0,0 @@
-{
- "images" : [
- {
- "idiom" : "iphone",
- "size" : "29x29",
- "scale" : "1x"
- },
- {
- "idiom" : "iphone",
- "size" : "29x29",
- "scale" : "2x"
- },
- {
- "idiom" : "iphone",
- "size" : "29x29",
- "scale" : "3x"
- },
- {
- "idiom" : "iphone",
- "size" : "40x40",
- "scale" : "2x"
- },
- {
- "idiom" : "iphone",
- "size" : "40x40",
- "scale" : "3x"
- },
- {
- "size" : "57x57",
- "idiom" : "iphone",
- "filename" : "iPhone6.png",
- "scale" : "1x"
- },
- {
- "size" : "57x57",
- "idiom" : "iphone",
- "filename" : "iPhone6_2x.png",
- "scale" : "2x"
- },
- {
- "size" : "60x60",
- "idiom" : "iphone",
- "filename" : "iPhone7_2x.png",
- "scale" : "2x"
- },
- {
- "size" : "60x60",
- "idiom" : "iphone",
- "filename" : "iPhone7_3x.png",
- "scale" : "3x"
- },
- {
- "idiom" : "ipad",
- "size" : "29x29",
- "scale" : "1x"
- },
- {
- "idiom" : "ipad",
- "size" : "29x29",
- "scale" : "2x"
- },
- {
- "idiom" : "ipad",
- "size" : "40x40",
- "scale" : "1x"
- },
- {
- "idiom" : "ipad",
- "size" : "40x40",
- "scale" : "2x"
- },
- {
- "idiom" : "ipad",
- "size" : "50x50",
- "scale" : "1x"
- },
- {
- "idiom" : "ipad",
- "size" : "50x50",
- "scale" : "2x"
- },
- {
- "size" : "72x72",
- "idiom" : "ipad",
- "filename" : "iPad6.png",
- "scale" : "1x"
- },
- {
- "size" : "72x72",
- "idiom" : "ipad",
- "filename" : "iPad6_2x.png",
- "scale" : "2x"
- },
- {
- "size" : "76x76",
- "idiom" : "ipad",
- "filename" : "iPad7.png",
- "scale" : "1x"
- },
- {
- "size" : "76x76",
- "idiom" : "ipad",
- "filename" : "iPad7_2x.png",
- "scale" : "2x"
- },
- {
- "idiom" : "car",
- "size" : "120x120",
- "scale" : "1x"
- }
- ],
- "info" : {
- "version" : 1,
- "author" : "xcode"
- }
-}
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6.png
deleted file mode 100644
index 43da2ee4..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6_2x.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6_2x.png
deleted file mode 100644
index 2ec93704..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6_2x.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7.png
deleted file mode 100644
index aec8bc1b..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7_2x.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7_2x.png
deleted file mode 100644
index e39cc3e7..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7_2x.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6.png
deleted file mode 100644
index 5572d79f..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6_2x.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6_2x.png
deleted file mode 100644
index 2424997f..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6_2x.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_2x.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_2x.png
deleted file mode 100644
index 10bfc3cf..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_2x.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_3x.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_3x.png
deleted file mode 100644
index 8d16f14d..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_3x.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/LaunchImage.launchimage/Contents.json b/objectivec/Tests/iOSTestHarness/Images.xcassets/LaunchImage.launchimage/Contents.json
deleted file mode 100644
index 5a296668..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/LaunchImage.launchimage/Contents.json
+++ /dev/null
@@ -1,49 +0,0 @@
-{
- "images" : [
- {
- "orientation" : "portrait",
- "idiom" : "ipad",
- "minimum-system-version" : "7.0",
- "extent" : "full-screen",
- "scale" : "2x"
- },
- {
- "orientation" : "landscape",
- "idiom" : "ipad",
- "minimum-system-version" : "7.0",
- "extent" : "full-screen",
- "scale" : "1x"
- },
- {
- "orientation" : "landscape",
- "idiom" : "ipad",
- "minimum-system-version" : "7.0",
- "extent" : "full-screen",
- "scale" : "2x"
- },
- {
- "orientation" : "portrait",
- "idiom" : "iphone",
- "minimum-system-version" : "7.0",
- "scale" : "2x"
- },
- {
- "orientation" : "portrait",
- "idiom" : "iphone",
- "minimum-system-version" : "7.0",
- "subtype" : "retina4",
- "scale" : "2x"
- },
- {
- "orientation" : "portrait",
- "idiom" : "ipad",
- "minimum-system-version" : "7.0",
- "extent" : "full-screen",
- "scale" : "1x"
- }
- ],
- "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/Tests/unittest_objc.proto b/objectivec/Tests/unittest_objc.proto
index e5577faf..b0eb4723 100644
--- a/objectivec/Tests/unittest_objc.proto
+++ b/objectivec/Tests/unittest_objc.proto
@@ -58,6 +58,27 @@ message TestRecursiveMessageWithRepeatedField {
map<string, string> str_to_str = 5;
}
+// Message with a few types of maps to cover the different custom flows
+// in the runtime.
+message TestMessageOfMaps {
+ map<string, string> str_to_str = 1;
+
+ map<string, int32> str_to_int = 2;
+ map<int32, string> int_to_str = 3;
+ map<int32, int32> int_to_int = 4;
+
+ map<string, bool> str_to_bool = 5;
+ map<bool, string> bool_to_str = 6;
+ map<bool, bool> bool_to_bool = 7;
+
+ map<int32, bool> int_to_bool = 8;
+ map<bool, int32> bool_to_int = 9;
+
+ map<string, TestAllTypes> str_to_msg = 10;
+ map<int32, TestAllTypes> int_to_msg = 11;
+ map<bool, TestAllTypes> bool_to_msg = 12;
+}
+
// Recursive message and extension to for testing autocreators at different
// depths.
message TestRecursiveExtension {
diff --git a/objectivec/google/protobuf/Any.pbobjc.h b/objectivec/google/protobuf/Any.pbobjc.h
index b17e76f0..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
@@ -135,17 +139,18 @@ typedef GPB_ENUM(GPBAny_FieldNumber) {
@interface GPBAny : GPBMessage
/**
- * A URL/resource name whose content describes the type of the
- * serialized protocol buffer message.
+ * 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).
*
- * For URLs which use the scheme `http`, `https`, or no scheme, the
- * following restrictions and interpretations apply:
+ * 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
@@ -154,6 +159,10 @@ typedef GPB_ENUM(GPBAny_FieldNumber) {
* 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.
**/
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/Struct.pbobjc.m b/objectivec/google/protobuf/Struct.pbobjc.m
index f36ec582..816fd6df 100644
--- a/objectivec/google/protobuf/Struct.pbobjc.m
+++ b/objectivec/google/protobuf/Struct.pbobjc.m
@@ -13,6 +13,8 @@
#import "GPBProtocolBuffers_RuntimeSupport.h"
#endif
+#import <stdatomic.h>
+
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
#import <Protobuf/Struct.pbobjc.h>
#else
@@ -51,7 +53,7 @@ static GPBFileDescriptor *GPBStructRoot_FileDescriptor(void) {
#pragma mark - Enum GPBNullValue
GPBEnumDescriptor *GPBNullValue_EnumDescriptor(void) {
- static GPBEnumDescriptor *descriptor = NULL;
+ static _Atomic(GPBEnumDescriptor*) descriptor = nil;
if (!descriptor) {
static const char *valueNames =
"NullValue\000";
@@ -64,7 +66,8 @@ GPBEnumDescriptor *GPBNullValue_EnumDescriptor(void) {
values:values
count:(uint32_t)(sizeof(values) / sizeof(int32_t))
enumVerifier:GPBNullValue_IsValidValue];
- if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) {
+ GPBEnumDescriptor *expected = nil;
+ if (!atomic_compare_exchange_strong(&descriptor, &expected, worker)) {
[worker release];
}
}
diff --git a/objectivec/google/protobuf/Timestamp.pbobjc.h b/objectivec/google/protobuf/Timestamp.pbobjc.h
index 0b670c35..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
@@ -115,7 +119,9 @@ typedef GPB_ENUM(GPBTimestamp_FieldNumber) {
* {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.
@@ -126,8 +132,8 @@ typedef GPB_ENUM(GPBTimestamp_FieldNumber) {
* to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
* with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
* can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
- * http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--)
- * 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.
**/
@interface GPBTimestamp : GPBMessage
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/Type.pbobjc.m b/objectivec/google/protobuf/Type.pbobjc.m
index 7a949388..bb64d876 100644
--- a/objectivec/google/protobuf/Type.pbobjc.m
+++ b/objectivec/google/protobuf/Type.pbobjc.m
@@ -13,6 +13,8 @@
#import "GPBProtocolBuffers_RuntimeSupport.h"
#endif
+#import <stdatomic.h>
+
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
#import <Protobuf/Type.pbobjc.h>
#import <Protobuf/Any.pbobjc.h>
@@ -54,7 +56,7 @@ static GPBFileDescriptor *GPBTypeRoot_FileDescriptor(void) {
#pragma mark - Enum GPBSyntax
GPBEnumDescriptor *GPBSyntax_EnumDescriptor(void) {
- static GPBEnumDescriptor *descriptor = NULL;
+ static _Atomic(GPBEnumDescriptor*) descriptor = nil;
if (!descriptor) {
static const char *valueNames =
"SyntaxProto2\000SyntaxProto3\000";
@@ -68,7 +70,8 @@ GPBEnumDescriptor *GPBSyntax_EnumDescriptor(void) {
values:values
count:(uint32_t)(sizeof(values) / sizeof(int32_t))
enumVerifier:GPBSyntax_IsValidValue];
- if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) {
+ GPBEnumDescriptor *expected = nil;
+ if (!atomic_compare_exchange_strong(&descriptor, &expected, worker)) {
[worker release];
}
}
@@ -368,7 +371,7 @@ void SetGPBField_Cardinality_RawValue(GPBField *message, int32_t value) {
#pragma mark - Enum GPBField_Kind
GPBEnumDescriptor *GPBField_Kind_EnumDescriptor(void) {
- static GPBEnumDescriptor *descriptor = NULL;
+ static _Atomic(GPBEnumDescriptor*) descriptor = nil;
if (!descriptor) {
static const char *valueNames =
"TypeUnknown\000TypeDouble\000TypeFloat\000TypeInt"
@@ -404,7 +407,8 @@ GPBEnumDescriptor *GPBField_Kind_EnumDescriptor(void) {
values:values
count:(uint32_t)(sizeof(values) / sizeof(int32_t))
enumVerifier:GPBField_Kind_IsValidValue];
- if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) {
+ GPBEnumDescriptor *expected = nil;
+ if (!atomic_compare_exchange_strong(&descriptor, &expected, worker)) {
[worker release];
}
}
@@ -441,7 +445,7 @@ BOOL GPBField_Kind_IsValidValue(int32_t value__) {
#pragma mark - Enum GPBField_Cardinality
GPBEnumDescriptor *GPBField_Cardinality_EnumDescriptor(void) {
- static GPBEnumDescriptor *descriptor = NULL;
+ static _Atomic(GPBEnumDescriptor*) descriptor = nil;
if (!descriptor) {
static const char *valueNames =
"CardinalityUnknown\000CardinalityOptional\000C"
@@ -458,7 +462,8 @@ GPBEnumDescriptor *GPBField_Cardinality_EnumDescriptor(void) {
values:values
count:(uint32_t)(sizeof(values) / sizeof(int32_t))
enumVerifier:GPBField_Cardinality_IsValidValue];
- if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) {
+ GPBEnumDescriptor *expected = nil;
+ if (!atomic_compare_exchange_strong(&descriptor, &expected, worker)) {
[worker release];
}
}
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 cebeb3e5..da7884ea 100644
--- a/php/README.md
+++ b/php/README.md
@@ -16,7 +16,7 @@ generation functionality.
To use PHP runtime library requires:
-- C extension: PHP 5.5.x or 5.6.x.
+- C extension: PHP 5.5, 5.6, or 7.
- PHP package: PHP 5.5, 5.6 or 7.
## Installation
diff --git a/php/ext/google/protobuf/message.c b/php/ext/google/protobuf/message.c
index e801f4a0..c8f4d62b 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,
@@ -931,7 +937,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;
}
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..7057384b 100644
--- a/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php
+++ b/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php
@@ -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();
diff --git a/php/src/Google/Protobuf/Internal/FileOptions.php b/php/src/Google/Protobuf/Internal/FileOptions.php
index f3bacad6..18e9455c 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.
*
@@ -828,6 +846,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/GPBUtil.php b/php/src/Google/Protobuf/Internal/GPBUtil.php
index 76f84cbd..05d5c393 100644
--- a/php/src/Google/Protobuf/Internal/GPBUtil.php
+++ b/php/src/Google/Protobuf/Internal/GPBUtil.php
@@ -194,7 +194,7 @@ class GPBUtil
public static function checkMessage(&$var, $klass)
{
if (!$var instanceof $klass && !is_null($var)) {
- throw new \Exception("Expect message.");
+ throw new \Exception("Expect $klass.");
}
}
diff --git a/php/src/Google/Protobuf/Internal/Message.php b/php/src/Google/Protobuf/Internal/Message.php
index b7f83c57..3aff7bd6 100644
--- a/php/src/Google/Protobuf/Internal/Message.php
+++ b/php/src/Google/Protobuf/Internal/Message.php
@@ -82,7 +82,7 @@ class Message
$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();
@@ -1104,7 +1104,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/Timestamp.php b/php/src/Google/Protobuf/Timestamp.php
index 7da8e956..f2286ab4 100644
--- a/php/src/Google/Protobuf/Timestamp.php
+++ b/php/src/Google/Protobuf/Timestamp.php
@@ -159,14 +159,10 @@ class Timestamp extends \Google\Protobuf\Internal\Message
/**
* 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 +170,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/tests/proto/test_empty_php_namespace.proto b/php/tests/proto/test_empty_php_namespace.proto
index 7b4bc74d..1d02f760 100644
--- a/php/tests/proto/test_empty_php_namespace.proto
+++ b/php/tests/proto/test_empty_php_namespace.proto
@@ -2,6 +2,7 @@ syntax = "proto3";
package foo;
option php_namespace = "";
+option php_metadata_namespace = "";
message TestEmptyNamespace {
int32 a = 1;
diff --git a/php/tests/proto/test_no_namespace.proto b/php/tests/proto/test_no_namespace.proto
index 58f13d47..03f89270 100644
--- a/php/tests/proto/test_no_namespace.proto
+++ b/php/tests/proto/test_no_namespace.proto
@@ -1,5 +1,7 @@
syntax = "proto3";
+option php_metadata_namespace = "\\";
+
message NoNamespaceMessage {
int32 a = 1;
diff --git a/php/tests/proto/test_php_namespace.proto b/php/tests/proto/test_php_namespace.proto
index 713187b9..bb57d617 100644
--- a/php/tests/proto/test_php_namespace.proto
+++ b/php/tests/proto/test_php_namespace.proto
@@ -2,6 +2,7 @@ syntax = "proto3";
package foo;
option php_namespace = "Php\\Test";
+option php_metadata_namespace = "Metadata\\Php\\Test";
message TestNamespace {
int32 a = 1;
diff --git a/php/tests/test.sh b/php/tests/test.sh
index 2983fe99..6e70eb2a 100755
--- a/php/tests/test.sh
+++ b/php/tests/test.sh
@@ -21,7 +21,7 @@ do
echo "****************************"
echo "* $t"
echo "****************************"
- # php -dextension=../ext/google/protobuf/modules/protobuf.so `which phpunit` --bootstrap autoload.php $t
+ php -dextension=../ext/google/protobuf/modules/protobuf.so `which phpunit` --bootstrap autoload.php $t
echo ""
done
diff --git a/protobuf.bzl b/protobuf.bzl
index 23380bab..78f19c62 100644
--- a/protobuf.bzl
+++ b/protobuf.bzl
@@ -45,8 +45,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 +174,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
@@ -317,8 +320,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 +347,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:
@@ -400,3 +403,15 @@ def internal_protobuf_py_tests(
srcs=[s],
main=s,
**kargs)
+
+
+def check_protobuf_required_bazel_version():
+ """For WORKSPACE files, to check the installed version of bazel.
+
+ 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")
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 fc8ef586..dcaec987 100644
--- a/protoc-artifacts/README.md
+++ b/protoc-artifacts/README.md
@@ -68,7 +68,7 @@ configure GPG and Sonatype account.
You need to perform the deployment for every platform that you want to
support. DO NOT close the staging repository until you have done the
deployment for all platforms. Currently the following platforms are supported:
-- Linux (x86_32 and x86_64)
+- Linux (x86_32, x86_64 and cross compiled aarch_64)
- Windows (x86_32 and x86_64) with
- Cygwin64 with MinGW compilers (x86_64)
- MSYS with MinGW32 (x86_32)
@@ -99,6 +99,9 @@ $ mvn clean deploy -P release -Dstaging.repository=comgoogle-123
A 32-bit artifact can be deployed from a 64-bit host with
``-Dos.detected.arch=x86_32``
+An arm64 artifact can be deployed from x86 host with
+``-Dos.detected.arch=aarch_64``
+
A windows artifact can be deployed from a linux machine with
``-Dos.detected.name=windows``
@@ -137,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 72f28d1d..298730a6 100644
--- a/protoc-artifacts/pom.xml
+++ b/protoc-artifacts/pom.xml
@@ -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/MANIFEST.in b/python/MANIFEST.in
index 26088826..5fb01922 100644
--- a/python/MANIFEST.in
+++ b/python/MANIFEST.in
@@ -4,6 +4,9 @@ exclude google/protobuf/internal/*_test.py
exclude google/protobuf/internal/*.proto
exclude google/protobuf/internal/test_util.py
+recursive-include google *.cc
+recursive-include google *.h
+
recursive-exclude google *_test.py
recursive-exclude google *_test.proto
recursive-exclude google unittest*_pb2.py
diff --git a/python/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 b1f3ca38..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
@@ -41,8 +42,8 @@ from google.protobuf.internal import api_implementation
_USE_C_DESCRIPTORS = False
if api_implementation.Type() == 'cpp':
# Used by MakeDescriptor in cpp mode
+ import binascii
import os
- import uuid
from google.protobuf.pyext import _message
_USE_C_DESCRIPTORS = getattr(_message, '_USE_C_DESCRIPTORS', False)
@@ -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
@@ -952,7 +1003,7 @@ def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,
# imported ones. We need to specify a file name so the descriptor pool
# accepts our FileDescriptorProto, but it is not important what that file
# name is actually set to.
- proto_name = str(uuid.uuid4())
+ proto_name = binascii.hexlify(os.urandom(16)).decode('ascii')
if package:
file_descriptor_proto.name = os.path.join(package.replace('.', '/'),
diff --git a/python/google/protobuf/descriptor_database.py b/python/google/protobuf/descriptor_database.py
index b8f5140b..8b7715cd 100644
--- a/python/google/protobuf/descriptor_database.py
+++ b/python/google/protobuf/descriptor_database.py
@@ -32,6 +32,8 @@
__author__ = 'matthewtoia@google.com (Matt Toia)'
+import warnings
+
class Error(Exception):
pass
@@ -64,21 +66,20 @@ class DescriptorDatabase(object):
elif self._file_desc_protos_by_file[proto_name] != file_desc_proto:
raise DescriptorDatabaseConflictingDefinitionError(
'%s already added, but with different descriptor.' % proto_name)
+ else:
+ return
# Add all the top-level descriptors to the index.
package = file_desc_proto.package
for message in file_desc_proto.message_type:
- self._file_desc_protos_by_symbol.update(
- (name, file_desc_proto) for name in _ExtractSymbols(message, package))
+ for name in _ExtractSymbols(message, package):
+ self._AddSymbol(name, file_desc_proto)
for enum in file_desc_proto.enum_type:
- self._file_desc_protos_by_symbol[
- '.'.join((package, enum.name))] = file_desc_proto
+ self._AddSymbol(('.'.join((package, enum.name))), file_desc_proto)
for extension in file_desc_proto.extension:
- self._file_desc_protos_by_symbol[
- '.'.join((package, extension.name))] = file_desc_proto
+ self._AddSymbol(('.'.join((package, extension.name))), file_desc_proto)
for service in file_desc_proto.service:
- self._file_desc_protos_by_symbol[
- '.'.join((package, service.name))] = file_desc_proto
+ self._AddSymbol(('.'.join((package, service.name))), file_desc_proto)
def FindFileByName(self, name):
"""Finds the file descriptor proto by file name.
@@ -132,6 +133,15 @@ class DescriptorDatabase(object):
top_level, _, _ = symbol.rpartition('.')
return self._file_desc_protos_by_symbol[top_level]
+ def _AddSymbol(self, name, file_desc_proto):
+ if name in self._file_desc_protos_by_symbol:
+ warn_msg = ('Conflict register for file "' + file_desc_proto.name +
+ '": ' + name +
+ ' is already defined in file "' +
+ self._file_desc_protos_by_symbol[name].name + '"')
+ warnings.warn(warn_msg, RuntimeWarning)
+ self._file_desc_protos_by_symbol[name] = file_desc_proto
+
def _ExtractSymbols(desc_proto, package):
"""Pulls out all the symbols from a descriptor proto.
diff --git a/python/google/protobuf/descriptor_pool.py b/python/google/protobuf/descriptor_pool.py
index f4c533a4..8983f76f 100644
--- a/python/google/protobuf/descriptor_pool.py
+++ b/python/google/protobuf/descriptor_pool.py
@@ -58,6 +58,7 @@ directly instead of this class.
__author__ = 'matthewtoia@google.com (Matt Toia)'
import collections
+import warnings
from google.protobuf import descriptor
from google.protobuf import descriptor_database
@@ -136,6 +137,29 @@ class DescriptorPool(object):
self._extensions_by_name = collections.defaultdict(dict)
self._extensions_by_number = collections.defaultdict(dict)
+ def _CheckConflictRegister(self, desc):
+ """Check if the descriptor name conflicts with another of the same name.
+
+ Args:
+ desc: Descriptor of a message, enum, service or extension.
+ """
+ desc_name = desc.full_name
+ for register, descriptor_type in [
+ (self._descriptors, descriptor.Descriptor),
+ (self._enum_descriptors, descriptor.EnumDescriptor),
+ (self._service_descriptors, descriptor.ServiceDescriptor),
+ (self._toplevel_extensions, descriptor.FieldDescriptor)]:
+ if desc_name in register:
+ file_name = register[desc_name].file.name
+ if not isinstance(desc, descriptor_type) or (
+ file_name != desc.file.name):
+ warn_msg = ('Conflict register for file "' + desc.file.name +
+ '": ' + desc_name +
+ ' is already defined in file "' +
+ file_name + '"')
+ warnings.warn(warn_msg, RuntimeWarning)
+ return
+
def Add(self, file_desc_proto):
"""Adds the FileDescriptorProto and its types to this pool.
@@ -172,6 +196,8 @@ class DescriptorPool(object):
if not isinstance(desc, descriptor.Descriptor):
raise TypeError('Expected instance of descriptor.Descriptor.')
+ self._CheckConflictRegister(desc)
+
self._descriptors[desc.full_name] = desc
self._AddFileDescriptor(desc.file)
@@ -187,6 +213,7 @@ class DescriptorPool(object):
if not isinstance(enum_desc, descriptor.EnumDescriptor):
raise TypeError('Expected instance of descriptor.EnumDescriptor.')
+ self._CheckConflictRegister(enum_desc)
self._enum_descriptors[enum_desc.full_name] = enum_desc
self._AddFileDescriptor(enum_desc.file)
@@ -200,6 +227,7 @@ class DescriptorPool(object):
if not isinstance(service_desc, descriptor.ServiceDescriptor):
raise TypeError('Expected instance of descriptor.ServiceDescriptor.')
+ self._CheckConflictRegister(service_desc)
self._service_descriptors[service_desc.full_name] = service_desc
def AddExtensionDescriptor(self, extension):
@@ -219,6 +247,7 @@ class DescriptorPool(object):
raise TypeError('Expected an extension descriptor.')
if extension.extension_scope is None:
+ self._CheckConflictRegister(extension)
self._toplevel_extensions[extension.full_name] = extension
try:
@@ -689,6 +718,7 @@ class DescriptorPool(object):
fields[field_index].containing_oneof = oneofs[oneof_index]
scope[_PrefixWithDot(desc_name)] = desc
+ self._CheckConflictRegister(desc)
self._descriptors[desc_name] = desc
return desc
@@ -727,6 +757,7 @@ class DescriptorPool(object):
containing_type=containing_type,
options=_OptionsOrNone(enum_proto))
scope['.%s' % enum_name] = desc
+ self._CheckConflictRegister(desc)
self._enum_descriptors[enum_name] = desc
return desc
@@ -923,6 +954,7 @@ class DescriptorPool(object):
methods=methods,
options=_OptionsOrNone(service_proto),
file=file_desc)
+ self._CheckConflictRegister(desc)
self._service_descriptors[service_name] = desc
return desc
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/containers.py b/python/google/protobuf/internal/containers.py
index 68be9e54..c6a3692a 100755
--- a/python/google/protobuf/internal/containers.py
+++ b/python/google/protobuf/internal/containers.py
@@ -549,10 +549,10 @@ class MessageMap(MutableMapping):
self._values = {}
def __getitem__(self, key):
+ key = self._key_checker.CheckValue(key)
try:
return self._values[key]
except KeyError:
- key = self._key_checker.CheckValue(key)
new_element = self._message_descriptor._concrete_class()
new_element._SetListener(self._message_listener)
self._values[key] = new_element
@@ -584,12 +584,14 @@ class MessageMap(MutableMapping):
return default
def __contains__(self, item):
+ item = self._key_checker.CheckValue(item)
return item in self._values
def __setitem__(self, key, value):
raise ValueError('May not set values directly, call my_map[key].foo = 5')
def __delitem__(self, key):
+ key = self._key_checker.CheckValue(key)
del self._values[key]
self._message_listener.Modified()
diff --git a/python/google/protobuf/internal/descriptor_database_test.py b/python/google/protobuf/internal/descriptor_database_test.py
index 1f1a3db9..f97477b3 100644
--- a/python/google/protobuf/internal/descriptor_database_test.py
+++ b/python/google/protobuf/internal/descriptor_database_test.py
@@ -38,6 +38,7 @@ try:
import unittest2 as unittest #PY26
except ImportError:
import unittest
+import warnings
from google.protobuf import unittest_pb2
from google.protobuf import descriptor_pb2
@@ -98,6 +99,26 @@ class DescriptorDatabaseTest(unittest.TestCase):
db.FindFileContainingSymbol,
'protobuf_unittest.NoneMessage')
+ def testConflictRegister(self):
+ db = descriptor_database.DescriptorDatabase()
+ unittest_fd = descriptor_pb2.FileDescriptorProto.FromString(
+ unittest_pb2.DESCRIPTOR.serialized_pb)
+ db.Add(unittest_fd)
+ conflict_fd = descriptor_pb2.FileDescriptorProto.FromString(
+ unittest_pb2.DESCRIPTOR.serialized_pb)
+ conflict_fd.name = 'other_file'
+ with warnings.catch_warnings(record=True) as w:
+ # Cause all warnings to always be triggered.
+ warnings.simplefilter('always')
+ db.Add(conflict_fd)
+ self.assertTrue(len(w))
+ self.assertIs(w[0].category, RuntimeWarning)
+ self.assertIn('Conflict register for file "other_file": ',
+ str(w[0].message))
+ self.assertIn('already defined in file '
+ '"google/protobuf/unittest.proto"',
+ str(w[0].message))
+
if __name__ == '__main__':
unittest.main()
diff --git a/python/google/protobuf/internal/descriptor_pool_test.py b/python/google/protobuf/internal/descriptor_pool_test.py
index 15c857bb..2cbf7813 100644
--- a/python/google/protobuf/internal/descriptor_pool_test.py
+++ b/python/google/protobuf/internal/descriptor_pool_test.py
@@ -34,8 +34,10 @@
__author__ = 'matthewtoia@google.com (Matt Toia)'
+import copy
import os
import sys
+import warnings
try:
import unittest2 as unittest #PY26
@@ -119,6 +121,14 @@ class DescriptorPoolTestBase(object):
self.assertEqual('google/protobuf/unittest.proto',
file_desc5.name)
+ # Tests the generated pool.
+ assert descriptor_pool.Default().FindFileContainingSymbol(
+ 'google.protobuf.python.internal.Factory2Message.one_more_field')
+ assert descriptor_pool.Default().FindFileContainingSymbol(
+ 'google.protobuf.python.internal.another_field')
+ assert descriptor_pool.Default().FindFileContainingSymbol(
+ 'protobuf_unittest.TestService')
+
def testFindFileContainingSymbolFailure(self):
with self.assertRaises(KeyError):
self.pool.FindFileContainingSymbol('Does not exist')
@@ -492,6 +502,52 @@ class DescriptorPoolTestBase(object):
TEST1_FILE.CheckFile(self, self.pool)
TEST2_FILE.CheckFile(self, self.pool)
+ def testConflictRegister(self):
+ if isinstance(self, SecondaryDescriptorFromDescriptorDB):
+ if api_implementation.Type() == 'cpp':
+ # Cpp extension cannot call Add on a DescriptorPool
+ # that uses a DescriptorDatabase.
+ # TODO(jieluo): Fix python and cpp extension diff.
+ return
+ unittest_fd = descriptor_pb2.FileDescriptorProto.FromString(
+ unittest_pb2.DESCRIPTOR.serialized_pb)
+ conflict_fd = copy.deepcopy(unittest_fd)
+ conflict_fd.name = 'other_file'
+ if api_implementation.Type() == 'cpp':
+ try:
+ self.pool.Add(unittest_fd)
+ self.pool.Add(conflict_fd)
+ except TypeError:
+ pass
+ else:
+ with warnings.catch_warnings(record=True) as w:
+ # Cause all warnings to always be triggered.
+ warnings.simplefilter('always')
+ pool = copy.deepcopy(self.pool)
+ # No warnings to add the same descriptors.
+ file_descriptor = unittest_pb2.DESCRIPTOR
+ pool.AddDescriptor(
+ file_descriptor.message_types_by_name['TestAllTypes'])
+ pool.AddEnumDescriptor(
+ file_descriptor.enum_types_by_name['ForeignEnum'])
+ pool.AddServiceDescriptor(
+ file_descriptor.services_by_name['TestService'])
+ pool.AddExtensionDescriptor(
+ file_descriptor.extensions_by_name['optional_int32_extension'])
+ self.assertEqual(len(w), 0)
+ # Check warnings for conflict descriptors with the same name.
+ pool.Add(unittest_fd)
+ pool.Add(conflict_fd)
+ pool.FindFileByName(unittest_fd.name)
+ pool.FindFileByName(conflict_fd.name)
+ self.assertTrue(len(w))
+ self.assertIs(w[0].category, RuntimeWarning)
+ self.assertIn('Conflict register for file "other_file": ',
+ str(w[0].message))
+ self.assertIn('already defined in file '
+ '"google/protobuf/unittest.proto"',
+ str(w[0].message))
+
class DefaultDescriptorPoolTest(DescriptorPoolTestBase, unittest.TestCase):
diff --git a/python/google/protobuf/internal/descriptor_test.py b/python/google/protobuf/internal/descriptor_test.py
index f1d5934e..02a43d15 100755
--- a/python/google/protobuf/internal/descriptor_test.py
+++ b/python/google/protobuf/internal/descriptor_test.py
@@ -742,6 +742,19 @@ class DescriptorCopyToProtoTest(unittest.TestCase):
deprecated: true
>
>
+ field {
+ name: "deprecated_int32_in_oneof"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_INT32
+ options {
+ deprecated: true
+ }
+ oneof_index: 0
+ }
+ oneof_decl {
+ name: "oneof_fields"
+ }
"""
self._InternalTestCopyToProto(
diff --git a/python/google/protobuf/internal/encoder.py b/python/google/protobuf/internal/encoder.py
index 40c62d67..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
@@ -418,7 +418,8 @@ def _VarintBytes(value):
def TagBytes(field_number, wire_type):
"""Encode the given tag and return the bytes. Only called at startup."""
- return six.binary_type( _VarintBytes(wire_format.PackTag(field_number, wire_type)) )
+ return six.binary_type(
+ _VarintBytes(wire_format.PackTag(field_number, wire_type)))
# --------------------------------------------------------------------
# As with sizers (see above), we have a number of common encoder
@@ -523,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
@@ -594,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:
@@ -604,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))
@@ -661,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:
@@ -671,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..d891dce1 100644
--- a/python/google/protobuf/internal/json_format_test.py
+++ b/python/google/protobuf/internal/json_format_test.py
@@ -983,6 +983,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 a303b1aa..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):
@@ -1480,12 +1480,8 @@ class Proto3Test(BaseTestCase):
submsg = msg.map_int32_foreign_message[5]
self.assertIs(submsg, msg.map_int32_foreign_message.get(5))
- # TODO(jieluo): Fix python and cpp extension diff.
- if api_implementation.Type() == 'cpp':
- with self.assertRaises(TypeError):
- msg.map_int32_foreign_message.get('')
- else:
- self.assertEqual(None, msg.map_int32_foreign_message.get(''))
+ with self.assertRaises(TypeError):
+ msg.map_int32_foreign_message.get('')
def testScalarMap(self):
msg = map_unittest_pb2.TestMap()
@@ -1695,12 +1691,35 @@ class Proto3Test(BaseTestCase):
del msg2.map_int32_foreign_message[222]
self.assertFalse(222 in msg2.map_int32_foreign_message)
- if api_implementation.Type() == 'cpp':
- with self.assertRaises(TypeError):
- del msg2.map_int32_foreign_message['']
- else:
- with self.assertRaises(KeyError):
- del msg2.map_int32_foreign_message['']
+ 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()
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 a52f133f..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')
@@ -828,6 +878,10 @@ class Proto2Tests(TextFormatBase):
' }\n'
' }\n'
' [unknown_extension]: 5\n'
+ ' [unknown_extension_with_number_field] {\n'
+ ' 1: "some_field"\n'
+ ' 2: -0.451\n'
+ ' }\n'
'}\n')
text_format.Parse(text, message, allow_unknown_extension=True)
golden = 'message_set {\n}\n'
@@ -894,7 +948,6 @@ class Proto2Tests(TextFormatBase):
message = unittest_mset_pb2.TestMessageSetContainer()
malformed = ('message_set {\n'
' unknown_field: true\n'
- ' \n' # Missing '>' here.
'}\n')
six.assertRaisesRegex(self,
text_format.ParseError,
@@ -906,7 +959,7 @@ class Proto2Tests(TextFormatBase):
message,
allow_unknown_extension=True)
- # Parse known extension correcty.
+ # Parse known extension correctly.
message = unittest_mset_pb2.TestMessageSetContainer()
text = ('message_set {\n'
' [protobuf_unittest.TestMessageSetExtension1] {\n'
@@ -967,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')
@@ -1062,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()
@@ -1486,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 291fe4e8..965940b2 100644
--- a/python/google/protobuf/internal/well_known_types_test.py
+++ b/python/google/protobuf/internal/well_known_types_test.py
@@ -101,7 +101,7 @@ class TimeUtilTest(TimeUtilTestBase):
message.FromJsonString('1970-01-01T00:00:00.1Z')
self.assertEqual(0, message.seconds)
self.assertEqual(100000000, message.nanos)
- # Parsing accpets offsets.
+ # Parsing accepts offsets.
message.FromJsonString('1970-01-01T00:00:00-08:00')
self.assertEqual(8 * 3600, message.seconds)
self.assertEqual(0, message.nanos)
@@ -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..8d338d3e 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
diff --git a/python/google/protobuf/pyext/descriptor.cc b/python/google/protobuf/pyext/descriptor.cc
index 9634ea05..8af0cb12 100644
--- a/python/google/protobuf/pyext/descriptor.cc
+++ b/python/google/protobuf/pyext/descriptor.cc
@@ -107,10 +107,6 @@ bool _CalledFromGeneratedFile(int stacklevel) {
return false;
}
}
- if (frame->f_globals != frame->f_locals) {
- // Not at global module scope
- return false;
- }
if (frame->f_code->co_filename == NULL) {
return false;
@@ -123,6 +119,10 @@ bool _CalledFromGeneratedFile(int stacklevel) {
PyErr_Clear();
return false;
}
+ if ((filename_size < 3) || (strcmp(&filename[filename_size - 3], ".py") != 0)) {
+ // Cython's stack does not have .py file name and is not at global module scope.
+ return true;
+ }
if (filename_size < 7) {
// filename is too short.
return false;
@@ -131,6 +131,11 @@ bool _CalledFromGeneratedFile(int stacklevel) {
// Filename is not ending with _pb2.
return false;
}
+
+ if (frame->f_globals != frame->f_locals) {
+ // Not at global module scope
+ return false;
+ }
#endif
return true;
}
@@ -188,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;
@@ -248,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");
@@ -564,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);
}
@@ -623,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}
};
@@ -785,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;
}
@@ -897,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"},
@@ -926,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}
};
@@ -1055,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);
}
@@ -1079,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}
};
@@ -1179,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"},
@@ -1188,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}
};
@@ -1330,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()));
@@ -1355,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}
};
@@ -1500,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"},
@@ -1508,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_containers.cc b/python/google/protobuf/pyext/descriptor_containers.cc
index d0aae9c9..bc007f7e 100644
--- a/python/google/protobuf/pyext/descriptor_containers.cc
+++ b/python/google/protobuf/pyext/descriptor_containers.cc
@@ -957,55 +957,55 @@ static int Count(PyContainer* self) {
return GetDescriptor(self)->field_count();
}
-static ItemDescriptor GetByName(PyContainer* self, const string& name) {
+static const void* GetByName(PyContainer* self, const string& name) {
return GetDescriptor(self)->FindFieldByName(name);
}
-static ItemDescriptor GetByCamelcaseName(PyContainer* self,
+static const void* GetByCamelcaseName(PyContainer* self,
const string& name) {
return GetDescriptor(self)->FindFieldByCamelcaseName(name);
}
-static ItemDescriptor GetByNumber(PyContainer* self, int number) {
+static const void* GetByNumber(PyContainer* self, int number) {
return GetDescriptor(self)->FindFieldByNumber(number);
}
-static ItemDescriptor GetByIndex(PyContainer* self, int index) {
+static const void* GetByIndex(PyContainer* self, int index) {
return GetDescriptor(self)->field(index);
}
-static PyObject* NewObjectFromItem(ItemDescriptor item) {
- return PyFieldDescriptor_FromDescriptor(item);
+static PyObject* NewObjectFromItem(const void* item) {
+ return PyFieldDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}
-static const string& GetItemName(ItemDescriptor item) {
- return item->name();
+static const string& GetItemName(const void* item) {
+ return static_cast<ItemDescriptor>(item)->name();
}
-static const string& GetItemCamelcaseName(ItemDescriptor item) {
- return item->camelcase_name();
+static const string& GetItemCamelcaseName(const void* item) {
+ return static_cast<ItemDescriptor>(item)->camelcase_name();
}
-static int GetItemNumber(ItemDescriptor item) {
- return item->number();
+static int GetItemNumber(const void* item) {
+ return static_cast<ItemDescriptor>(item)->number();
}
-static int GetItemIndex(ItemDescriptor item) {
- return item->index();
+static int GetItemIndex(const void* item) {
+ return static_cast<ItemDescriptor>(item)->index();
}
static DescriptorContainerDef ContainerDef = {
"MessageFields",
- (CountMethod)Count,
- (GetByIndexMethod)GetByIndex,
- (GetByNameMethod)GetByName,
- (GetByCamelcaseNameMethod)GetByCamelcaseName,
- (GetByNumberMethod)GetByNumber,
- (NewObjectFromItemMethod)NewObjectFromItem,
- (GetItemNameMethod)GetItemName,
- (GetItemCamelcaseNameMethod)GetItemCamelcaseName,
- (GetItemNumberMethod)GetItemNumber,
- (GetItemIndexMethod)GetItemIndex,
+ Count,
+ GetByIndex,
+ GetByName,
+ GetByCamelcaseName,
+ GetByNumber,
+ NewObjectFromItem,
+ GetItemName,
+ GetItemCamelcaseName,
+ GetItemNumber,
+ GetItemIndex,
};
} // namespace fields
@@ -1035,38 +1035,38 @@ static int Count(PyContainer* self) {
return GetDescriptor(self)->nested_type_count();
}
-static ItemDescriptor GetByName(PyContainer* self, const string& name) {
+static const void* GetByName(PyContainer* self, const string& name) {
return GetDescriptor(self)->FindNestedTypeByName(name);
}
-static ItemDescriptor GetByIndex(PyContainer* self, int index) {
+static const void* GetByIndex(PyContainer* self, int index) {
return GetDescriptor(self)->nested_type(index);
}
-static PyObject* NewObjectFromItem(ItemDescriptor item) {
- return PyMessageDescriptor_FromDescriptor(item);
+static PyObject* NewObjectFromItem(const void* item) {
+ return PyMessageDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}
-static const string& GetItemName(ItemDescriptor item) {
- return item->name();
+static const string& GetItemName(const void* item) {
+ return static_cast<ItemDescriptor>(item)->name();
}
-static int GetItemIndex(ItemDescriptor item) {
- return item->index();
+static int GetItemIndex(const void* item) {
+ return static_cast<ItemDescriptor>(item)->index();
}
static DescriptorContainerDef ContainerDef = {
"MessageNestedTypes",
- (CountMethod)Count,
- (GetByIndexMethod)GetByIndex,
- (GetByNameMethod)GetByName,
- (GetByCamelcaseNameMethod)NULL,
- (GetByNumberMethod)NULL,
- (NewObjectFromItemMethod)NewObjectFromItem,
- (GetItemNameMethod)GetItemName,
- (GetItemCamelcaseNameMethod)NULL,
- (GetItemNumberMethod)NULL,
- (GetItemIndexMethod)GetItemIndex,
+ Count,
+ GetByIndex,
+ GetByName,
+ NULL,
+ NULL,
+ NewObjectFromItem,
+ GetItemName,
+ NULL,
+ NULL,
+ GetItemIndex,
};
} // namespace nested_types
@@ -1087,38 +1087,38 @@ static int Count(PyContainer* self) {
return GetDescriptor(self)->enum_type_count();
}
-static ItemDescriptor GetByName(PyContainer* self, const string& name) {
+static const void* GetByName(PyContainer* self, const string& name) {
return GetDescriptor(self)->FindEnumTypeByName(name);
}
-static ItemDescriptor GetByIndex(PyContainer* self, int index) {
+static const void* GetByIndex(PyContainer* self, int index) {
return GetDescriptor(self)->enum_type(index);
}
-static PyObject* NewObjectFromItem(ItemDescriptor item) {
- return PyEnumDescriptor_FromDescriptor(item);
+static PyObject* NewObjectFromItem(const void* item) {
+ return PyEnumDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}
-static const string& GetItemName(ItemDescriptor item) {
- return item->name();
+static const string& GetItemName(const void* item) {
+ return static_cast<ItemDescriptor>(item)->name();
}
-static int GetItemIndex(ItemDescriptor item) {
- return item->index();
+static int GetItemIndex(const void* item) {
+ return static_cast<ItemDescriptor>(item)->index();
}
static DescriptorContainerDef ContainerDef = {
"MessageNestedEnums",
- (CountMethod)Count,
- (GetByIndexMethod)GetByIndex,
- (GetByNameMethod)GetByName,
- (GetByCamelcaseNameMethod)NULL,
- (GetByNumberMethod)NULL,
- (NewObjectFromItemMethod)NewObjectFromItem,
- (GetItemNameMethod)GetItemName,
- (GetItemCamelcaseNameMethod)NULL,
- (GetItemNumberMethod)NULL,
- (GetItemIndexMethod)GetItemIndex,
+ Count,
+ GetByIndex,
+ GetByName,
+ NULL,
+ NULL,
+ NewObjectFromItem,
+ GetItemName,
+ NULL,
+ NULL,
+ GetItemIndex,
};
} // namespace enums
@@ -1150,11 +1150,11 @@ static int Count(PyContainer* self) {
return count;
}
-static ItemDescriptor GetByName(PyContainer* self, const string& name) {
+static const void* GetByName(PyContainer* self, const string& name) {
return GetDescriptor(self)->FindEnumValueByName(name);
}
-static ItemDescriptor GetByIndex(PyContainer* self, int index) {
+static const void* GetByIndex(PyContainer* self, int index) {
// This is not optimal, but the number of enums *types* in a given message
// is small. This function is only used when iterating over the mapping.
const EnumDescriptor* enum_type = NULL;
@@ -1173,26 +1173,27 @@ static ItemDescriptor GetByIndex(PyContainer* self, int index) {
return enum_type->value(index);
}
-static PyObject* NewObjectFromItem(ItemDescriptor item) {
- return PyEnumValueDescriptor_FromDescriptor(item);
+static PyObject* NewObjectFromItem(const void* item) {
+ return PyEnumValueDescriptor_FromDescriptor(
+ static_cast<ItemDescriptor>(item));
}
-static const string& GetItemName(ItemDescriptor item) {
- return item->name();
+static const string& GetItemName(const void* item) {
+ return static_cast<ItemDescriptor>(item)->name();
}
static DescriptorContainerDef ContainerDef = {
"MessageEnumValues",
- (CountMethod)Count,
- (GetByIndexMethod)GetByIndex,
- (GetByNameMethod)GetByName,
- (GetByCamelcaseNameMethod)NULL,
- (GetByNumberMethod)NULL,
- (NewObjectFromItemMethod)NewObjectFromItem,
- (GetItemNameMethod)GetItemName,
- (GetItemCamelcaseNameMethod)NULL,
- (GetItemNumberMethod)NULL,
- (GetItemIndexMethod)NULL,
+ Count,
+ GetByIndex,
+ GetByName,
+ NULL,
+ NULL,
+ NewObjectFromItem,
+ GetItemName,
+ NULL,
+ NULL,
+ NULL,
};
} // namespace enumvalues
@@ -1209,38 +1210,38 @@ static int Count(PyContainer* self) {
return GetDescriptor(self)->extension_count();
}
-static ItemDescriptor GetByName(PyContainer* self, const string& name) {
+static const void* GetByName(PyContainer* self, const string& name) {
return GetDescriptor(self)->FindExtensionByName(name);
}
-static ItemDescriptor GetByIndex(PyContainer* self, int index) {
+static const void* GetByIndex(PyContainer* self, int index) {
return GetDescriptor(self)->extension(index);
}
-static PyObject* NewObjectFromItem(ItemDescriptor item) {
- return PyFieldDescriptor_FromDescriptor(item);
+static PyObject* NewObjectFromItem(const void* item) {
+ return PyFieldDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}
-static const string& GetItemName(ItemDescriptor item) {
- return item->name();
+static const string& GetItemName(const void* item) {
+ return static_cast<ItemDescriptor>(item)->name();
}
-static int GetItemIndex(ItemDescriptor item) {
- return item->index();
+static int GetItemIndex(const void* item) {
+ return static_cast<ItemDescriptor>(item)->index();
}
static DescriptorContainerDef ContainerDef = {
"MessageExtensions",
- (CountMethod)Count,
- (GetByIndexMethod)GetByIndex,
- (GetByNameMethod)GetByName,
- (GetByCamelcaseNameMethod)NULL,
- (GetByNumberMethod)NULL,
- (NewObjectFromItemMethod)NewObjectFromItem,
- (GetItemNameMethod)GetItemName,
- (GetItemCamelcaseNameMethod)NULL,
- (GetItemNumberMethod)NULL,
- (GetItemIndexMethod)GetItemIndex,
+ Count,
+ GetByIndex,
+ GetByName,
+ NULL,
+ NULL,
+ NewObjectFromItem,
+ GetItemName,
+ NULL,
+ NULL,
+ GetItemIndex,
};
} // namespace extensions
@@ -1261,38 +1262,38 @@ static int Count(PyContainer* self) {
return GetDescriptor(self)->oneof_decl_count();
}
-static ItemDescriptor GetByName(PyContainer* self, const string& name) {
+static const void* GetByName(PyContainer* self, const string& name) {
return GetDescriptor(self)->FindOneofByName(name);
}
-static ItemDescriptor GetByIndex(PyContainer* self, int index) {
+static const void* GetByIndex(PyContainer* self, int index) {
return GetDescriptor(self)->oneof_decl(index);
}
-static PyObject* NewObjectFromItem(ItemDescriptor item) {
- return PyOneofDescriptor_FromDescriptor(item);
+static PyObject* NewObjectFromItem(const void* item) {
+ return PyOneofDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}
-static const string& GetItemName(ItemDescriptor item) {
- return item->name();
+static const string& GetItemName(const void* item) {
+ return static_cast<ItemDescriptor>(item)->name();
}
-static int GetItemIndex(ItemDescriptor item) {
- return item->index();
+static int GetItemIndex(const void* item) {
+ return static_cast<ItemDescriptor>(item)->index();
}
static DescriptorContainerDef ContainerDef = {
"MessageOneofs",
- (CountMethod)Count,
- (GetByIndexMethod)GetByIndex,
- (GetByNameMethod)GetByName,
- (GetByCamelcaseNameMethod)NULL,
- (GetByNumberMethod)NULL,
- (NewObjectFromItemMethod)NewObjectFromItem,
- (GetItemNameMethod)GetItemName,
- (GetItemCamelcaseNameMethod)NULL,
- (GetItemNumberMethod)NULL,
- (GetItemIndexMethod)GetItemIndex,
+ Count,
+ GetByIndex,
+ GetByName,
+ NULL,
+ NULL,
+ NewObjectFromItem,
+ GetItemName,
+ NULL,
+ NULL,
+ GetItemIndex,
};
} // namespace oneofs
@@ -1323,46 +1324,47 @@ static int Count(PyContainer* self) {
return GetDescriptor(self)->value_count();
}
-static ItemDescriptor GetByIndex(PyContainer* self, int index) {
+static const void* GetByIndex(PyContainer* self, int index) {
return GetDescriptor(self)->value(index);
}
-static ItemDescriptor GetByName(PyContainer* self, const string& name) {
+static const void* GetByName(PyContainer* self, const string& name) {
return GetDescriptor(self)->FindValueByName(name);
}
-static ItemDescriptor GetByNumber(PyContainer* self, int number) {
+static const void* GetByNumber(PyContainer* self, int number) {
return GetDescriptor(self)->FindValueByNumber(number);
}
-static PyObject* NewObjectFromItem(ItemDescriptor item) {
- return PyEnumValueDescriptor_FromDescriptor(item);
+static PyObject* NewObjectFromItem(const void* item) {
+ return PyEnumValueDescriptor_FromDescriptor(
+ static_cast<ItemDescriptor>(item));
}
-static const string& GetItemName(ItemDescriptor item) {
- return item->name();
+static const string& GetItemName(const void* item) {
+ return static_cast<ItemDescriptor>(item)->name();
}
-static int GetItemNumber(ItemDescriptor item) {
- return item->number();
+static int GetItemNumber(const void* item) {
+ return static_cast<ItemDescriptor>(item)->number();
}
-static int GetItemIndex(ItemDescriptor item) {
- return item->index();
+static int GetItemIndex(const void* item) {
+ return static_cast<ItemDescriptor>(item)->index();
}
static DescriptorContainerDef ContainerDef = {
"EnumValues",
- (CountMethod)Count,
- (GetByIndexMethod)GetByIndex,
- (GetByNameMethod)GetByName,
- (GetByCamelcaseNameMethod)NULL,
- (GetByNumberMethod)GetByNumber,
- (NewObjectFromItemMethod)NewObjectFromItem,
- (GetItemNameMethod)GetItemName,
- (GetItemCamelcaseNameMethod)NULL,
- (GetItemNumberMethod)GetItemNumber,
- (GetItemIndexMethod)GetItemIndex,
+ Count,
+ GetByIndex,
+ GetByName,
+ NULL,
+ GetByNumber,
+ NewObjectFromItem,
+ GetItemName,
+ NULL,
+ GetItemNumber,
+ GetItemIndex,
};
} // namespace enumvalues
@@ -1397,30 +1399,30 @@ static int Count(PyContainer* self) {
return GetDescriptor(self)->field_count();
}
-static ItemDescriptor GetByIndex(PyContainer* self, int index) {
+static const void* GetByIndex(PyContainer* self, int index) {
return GetDescriptor(self)->field(index);
}
-static PyObject* NewObjectFromItem(ItemDescriptor item) {
- return PyFieldDescriptor_FromDescriptor(item);
+static PyObject* NewObjectFromItem(const void* item) {
+ return PyFieldDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}
-static int GetItemIndex(ItemDescriptor item) {
- return item->index_in_oneof();
+static int GetItemIndex(const void* item) {
+ return static_cast<ItemDescriptor>(item)->index_in_oneof();
}
static DescriptorContainerDef ContainerDef = {
"OneofFields",
- (CountMethod)Count,
- (GetByIndexMethod)GetByIndex,
- (GetByNameMethod)NULL,
- (GetByCamelcaseNameMethod)NULL,
- (GetByNumberMethod)NULL,
- (NewObjectFromItemMethod)NewObjectFromItem,
- (GetItemNameMethod)NULL,
- (GetItemCamelcaseNameMethod)NULL,
- (GetItemNumberMethod)NULL,
- (GetItemIndexMethod)GetItemIndex,
+ Count,
+ GetByIndex,
+ NULL,
+ NULL,
+ NULL,
+ NewObjectFromItem,
+ NULL,
+ NULL,
+ NULL,
+ GetItemIndex,
};
} // namespace fields
@@ -1447,38 +1449,38 @@ static int Count(PyContainer* self) {
return GetDescriptor(self)->method_count();
}
-static ItemDescriptor GetByName(PyContainer* self, const string& name) {
+static const void* GetByName(PyContainer* self, const string& name) {
return GetDescriptor(self)->FindMethodByName(name);
}
-static ItemDescriptor GetByIndex(PyContainer* self, int index) {
+static const void* GetByIndex(PyContainer* self, int index) {
return GetDescriptor(self)->method(index);
}
-static PyObject* NewObjectFromItem(ItemDescriptor item) {
- return PyMethodDescriptor_FromDescriptor(item);
+static PyObject* NewObjectFromItem(const void* item) {
+ return PyMethodDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}
-static const string& GetItemName(ItemDescriptor item) {
- return item->name();
+static const string& GetItemName(const void* item) {
+ return static_cast<ItemDescriptor>(item)->name();
}
-static int GetItemIndex(ItemDescriptor item) {
- return item->index();
+static int GetItemIndex(const void* item) {
+ return static_cast<ItemDescriptor>(item)->index();
}
static DescriptorContainerDef ContainerDef = {
"ServiceMethods",
- (CountMethod)Count,
- (GetByIndexMethod)GetByIndex,
- (GetByNameMethod)GetByName,
- (GetByCamelcaseNameMethod)NULL,
- (GetByNumberMethod)NULL,
- (NewObjectFromItemMethod)NewObjectFromItem,
- (GetItemNameMethod)GetItemName,
- (GetItemCamelcaseNameMethod)NULL,
- (GetItemNumberMethod)NULL,
- (GetItemIndexMethod)GetItemIndex,
+ Count,
+ GetByIndex,
+ GetByName,
+ NULL,
+ NULL,
+ NewObjectFromItem,
+ GetItemName,
+ NULL,
+ NULL,
+ GetItemIndex,
};
} // namespace methods
@@ -1509,38 +1511,38 @@ static int Count(PyContainer* self) {
return GetDescriptor(self)->message_type_count();
}
-static ItemDescriptor GetByName(PyContainer* self, const string& name) {
+static const void* GetByName(PyContainer* self, const string& name) {
return GetDescriptor(self)->FindMessageTypeByName(name);
}
-static ItemDescriptor GetByIndex(PyContainer* self, int index) {
+static const void* GetByIndex(PyContainer* self, int index) {
return GetDescriptor(self)->message_type(index);
}
-static PyObject* NewObjectFromItem(ItemDescriptor item) {
- return PyMessageDescriptor_FromDescriptor(item);
+static PyObject* NewObjectFromItem(const void* item) {
+ return PyMessageDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}
-static const string& GetItemName(ItemDescriptor item) {
- return item->name();
+static const string& GetItemName(const void* item) {
+ return static_cast<ItemDescriptor>(item)->name();
}
-static int GetItemIndex(ItemDescriptor item) {
- return item->index();
+static int GetItemIndex(const void* item) {
+ return static_cast<ItemDescriptor>(item)->index();
}
static DescriptorContainerDef ContainerDef = {
"FileMessages",
- (CountMethod)Count,
- (GetByIndexMethod)GetByIndex,
- (GetByNameMethod)GetByName,
- (GetByCamelcaseNameMethod)NULL,
- (GetByNumberMethod)NULL,
- (NewObjectFromItemMethod)NewObjectFromItem,
- (GetItemNameMethod)GetItemName,
- (GetItemCamelcaseNameMethod)NULL,
- (GetItemNumberMethod)NULL,
- (GetItemIndexMethod)GetItemIndex,
+ Count,
+ GetByIndex,
+ GetByName,
+ NULL,
+ NULL,
+ NewObjectFromItem,
+ GetItemName,
+ NULL,
+ NULL,
+ GetItemIndex,
};
} // namespace messages
@@ -1557,38 +1559,38 @@ static int Count(PyContainer* self) {
return GetDescriptor(self)->enum_type_count();
}
-static ItemDescriptor GetByName(PyContainer* self, const string& name) {
+static const void* GetByName(PyContainer* self, const string& name) {
return GetDescriptor(self)->FindEnumTypeByName(name);
}
-static ItemDescriptor GetByIndex(PyContainer* self, int index) {
+static const void* GetByIndex(PyContainer* self, int index) {
return GetDescriptor(self)->enum_type(index);
}
-static PyObject* NewObjectFromItem(ItemDescriptor item) {
- return PyEnumDescriptor_FromDescriptor(item);
+static PyObject* NewObjectFromItem(const void* item) {
+ return PyEnumDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}
-static const string& GetItemName(ItemDescriptor item) {
- return item->name();
+static const string& GetItemName(const void* item) {
+ return static_cast<ItemDescriptor>(item)->name();
}
-static int GetItemIndex(ItemDescriptor item) {
- return item->index();
+static int GetItemIndex(const void* item) {
+ return static_cast<ItemDescriptor>(item)->index();
}
static DescriptorContainerDef ContainerDef = {
"FileEnums",
- (CountMethod)Count,
- (GetByIndexMethod)GetByIndex,
- (GetByNameMethod)GetByName,
- (GetByCamelcaseNameMethod)NULL,
- (GetByNumberMethod)NULL,
- (NewObjectFromItemMethod)NewObjectFromItem,
- (GetItemNameMethod)GetItemName,
- (GetItemCamelcaseNameMethod)NULL,
- (GetItemNumberMethod)NULL,
- (GetItemIndexMethod)GetItemIndex,
+ Count,
+ GetByIndex,
+ GetByName,
+ NULL,
+ NULL,
+ NewObjectFromItem,
+ GetItemName,
+ NULL,
+ NULL,
+ GetItemIndex,
};
} // namespace enums
@@ -1605,38 +1607,38 @@ static int Count(PyContainer* self) {
return GetDescriptor(self)->extension_count();
}
-static ItemDescriptor GetByName(PyContainer* self, const string& name) {
+static const void* GetByName(PyContainer* self, const string& name) {
return GetDescriptor(self)->FindExtensionByName(name);
}
-static ItemDescriptor GetByIndex(PyContainer* self, int index) {
+static const void* GetByIndex(PyContainer* self, int index) {
return GetDescriptor(self)->extension(index);
}
-static PyObject* NewObjectFromItem(ItemDescriptor item) {
- return PyFieldDescriptor_FromDescriptor(item);
+static PyObject* NewObjectFromItem(const void* item) {
+ return PyFieldDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}
-static const string& GetItemName(ItemDescriptor item) {
- return item->name();
+static const string& GetItemName(const void* item) {
+ return static_cast<ItemDescriptor>(item)->name();
}
-static int GetItemIndex(ItemDescriptor item) {
- return item->index();
+static int GetItemIndex(const void* item) {
+ return static_cast<ItemDescriptor>(item)->index();
}
static DescriptorContainerDef ContainerDef = {
"FileExtensions",
- (CountMethod)Count,
- (GetByIndexMethod)GetByIndex,
- (GetByNameMethod)GetByName,
- (GetByCamelcaseNameMethod)NULL,
- (GetByNumberMethod)NULL,
- (NewObjectFromItemMethod)NewObjectFromItem,
- (GetItemNameMethod)GetItemName,
- (GetItemCamelcaseNameMethod)NULL,
- (GetItemNumberMethod)NULL,
- (GetItemIndexMethod)GetItemIndex,
+ Count,
+ GetByIndex,
+ GetByName,
+ NULL,
+ NULL,
+ NewObjectFromItem,
+ GetItemName,
+ NULL,
+ NULL,
+ GetItemIndex,
};
} // namespace extensions
@@ -1653,38 +1655,38 @@ static int Count(PyContainer* self) {
return GetDescriptor(self)->service_count();
}
-static ItemDescriptor GetByName(PyContainer* self, const string& name) {
+static const void* GetByName(PyContainer* self, const string& name) {
return GetDescriptor(self)->FindServiceByName(name);
}
-static ItemDescriptor GetByIndex(PyContainer* self, int index) {
+static const void* GetByIndex(PyContainer* self, int index) {
return GetDescriptor(self)->service(index);
}
-static PyObject* NewObjectFromItem(ItemDescriptor item) {
- return PyServiceDescriptor_FromDescriptor(item);
+static PyObject* NewObjectFromItem(const void* item) {
+ return PyServiceDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}
-static const string& GetItemName(ItemDescriptor item) {
- return item->name();
+static const string& GetItemName(const void* item) {
+ return static_cast<ItemDescriptor>(item)->name();
}
-static int GetItemIndex(ItemDescriptor item) {
- return item->index();
+static int GetItemIndex(const void* item) {
+ return static_cast<ItemDescriptor>(item)->index();
}
static DescriptorContainerDef ContainerDef = {
"FileServices",
- (CountMethod)Count,
- (GetByIndexMethod)GetByIndex,
- (GetByNameMethod)GetByName,
- (GetByCamelcaseNameMethod)NULL,
- (GetByNumberMethod)NULL,
- (NewObjectFromItemMethod)NewObjectFromItem,
- (GetItemNameMethod)GetItemName,
- (GetItemCamelcaseNameMethod)NULL,
- (GetItemNumberMethod)NULL,
- (GetItemIndexMethod)GetItemIndex,
+ Count,
+ GetByIndex,
+ GetByName,
+ NULL,
+ NULL,
+ NewObjectFromItem,
+ GetItemName,
+ NULL,
+ NULL,
+ GetItemIndex,
};
} // namespace services
@@ -1701,26 +1703,26 @@ static int Count(PyContainer* self) {
return GetDescriptor(self)->dependency_count();
}
-static ItemDescriptor GetByIndex(PyContainer* self, int index) {
+static const void* GetByIndex(PyContainer* self, int index) {
return GetDescriptor(self)->dependency(index);
}
-static PyObject* NewObjectFromItem(ItemDescriptor item) {
- return PyFileDescriptor_FromDescriptor(item);
+static PyObject* NewObjectFromItem(const void* item) {
+ return PyFileDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}
static DescriptorContainerDef ContainerDef = {
"FileDependencies",
- (CountMethod)Count,
- (GetByIndexMethod)GetByIndex,
- (GetByNameMethod)NULL,
- (GetByCamelcaseNameMethod)NULL,
- (GetByNumberMethod)NULL,
- (NewObjectFromItemMethod)NewObjectFromItem,
- (GetItemNameMethod)NULL,
- (GetItemCamelcaseNameMethod)NULL,
- (GetItemNumberMethod)NULL,
- (GetItemIndexMethod)NULL,
+ Count,
+ GetByIndex,
+ NULL,
+ NULL,
+ NULL,
+ NewObjectFromItem,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
};
} // namespace dependencies
@@ -1737,26 +1739,26 @@ static int Count(PyContainer* self) {
return GetDescriptor(self)->public_dependency_count();
}
-static ItemDescriptor GetByIndex(PyContainer* self, int index) {
+static const void* GetByIndex(PyContainer* self, int index) {
return GetDescriptor(self)->public_dependency(index);
}
-static PyObject* NewObjectFromItem(ItemDescriptor item) {
- return PyFileDescriptor_FromDescriptor(item);
+static PyObject* NewObjectFromItem(const void* item) {
+ return PyFileDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}
static DescriptorContainerDef ContainerDef = {
"FilePublicDependencies",
- (CountMethod)Count,
- (GetByIndexMethod)GetByIndex,
- (GetByNameMethod)NULL,
- (GetByCamelcaseNameMethod)NULL,
- (GetByNumberMethod)NULL,
- (NewObjectFromItemMethod)NewObjectFromItem,
- (GetItemNameMethod)NULL,
- (GetItemCamelcaseNameMethod)NULL,
- (GetItemNumberMethod)NULL,
- (GetItemIndexMethod)NULL,
+ Count,
+ GetByIndex,
+ NULL,
+ NULL,
+ NULL,
+ NewObjectFromItem,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
};
} // namespace public_dependencies
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 ef75acab..5893533a 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.
@@ -605,18 +602,16 @@ void OutOfRangeError(PyObject* arg) {
template<class RangeType, class ValueType>
bool VerifyIntegerCastAndRange(PyObject* arg, ValueType value) {
- if
- GOOGLE_PREDICT_FALSE(value == -1 && PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
- // Replace it with the same ValueError as pure python protos instead of
- // the default one.
- PyErr_Clear();
- OutOfRangeError(arg);
- } // Otherwise propagate existing error.
- return false;
+ if (GOOGLE_PREDICT_FALSE(value == -1 && PyErr_Occurred())) {
+ if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
+ // Replace it with the same ValueError as pure python protos instead of
+ // the default one.
+ PyErr_Clear();
+ OutOfRangeError(arg);
+ } // Otherwise propagate existing error.
+ return false;
}
- if
- GOOGLE_PREDICT_FALSE(!IsValidNumericCast<RangeType>(value)) {
+ if (GOOGLE_PREDICT_FALSE(!IsValidNumericCast<RangeType>(value))) {
OutOfRangeError(arg);
return false;
}
@@ -628,26 +623,22 @@ bool CheckAndGetInteger(PyObject* arg, T* value) {
// The fast path.
#if PY_MAJOR_VERSION < 3
// For the typical case, offer a fast path.
- if
- GOOGLE_PREDICT_TRUE(PyInt_Check(arg)) {
- long int_result = PyInt_AsLong(arg);
- if
- GOOGLE_PREDICT_TRUE(IsValidNumericCast<T>(int_result)) {
- *value = static_cast<T>(int_result);
- return true;
- }
- else {
- OutOfRangeError(arg);
- return false;
- }
+ if (GOOGLE_PREDICT_TRUE(PyInt_Check(arg))) {
+ long int_result = PyInt_AsLong(arg);
+ if (GOOGLE_PREDICT_TRUE(IsValidNumericCast<T>(int_result))) {
+ *value = static_cast<T>(int_result);
+ return true;
+ } else {
+ OutOfRangeError(arg);
+ return false;
+ }
}
#endif
// This effectively defines an integer as "an object that can be cast as
// an integer and can be used as an ordinal number".
// This definition includes everything that implements numbers.Integral
// and shouldn't cast the net too wide.
- if
- GOOGLE_PREDICT_FALSE(!PyIndex_Check(arg)) {
+ if (GOOGLE_PREDICT_FALSE(!PyIndex_Check(arg))) {
FormatTypeError(arg, "int, long");
return false;
}
@@ -664,10 +655,9 @@ bool CheckAndGetInteger(PyObject* arg, T* value) {
// Unlike PyLong_AsLongLong, PyLong_AsUnsignedLongLong is very
// picky about the exact type.
PyObject* casted = PyNumber_Long(arg);
- if
- GOOGLE_PREDICT_FALSE(casted == NULL) {
- // Propagate existing error.
- return false;
+ if (GOOGLE_PREDICT_FALSE(casted == nullptr)) {
+ // Propagate existing error.
+ return false;
}
ulong_result = PyLong_AsUnsignedLongLong(casted);
Py_DECREF(casted);
@@ -690,10 +680,9 @@ bool CheckAndGetInteger(PyObject* arg, T* value) {
// Valid subclasses of numbers.Integral should have a __long__() method
// so fall back to that.
PyObject* casted = PyNumber_Long(arg);
- if
- GOOGLE_PREDICT_FALSE(casted == NULL) {
- // Propagate existing error.
- return false;
+ if (GOOGLE_PREDICT_FALSE(casted == nullptr)) {
+ // Propagate existing error.
+ return false;
}
long_result = PyLong_AsLongLong(casted);
Py_DECREF(casted);
@@ -717,10 +706,9 @@ template bool CheckAndGetInteger<uint64>(PyObject*, uint64*);
bool CheckAndGetDouble(PyObject* arg, double* value) {
*value = PyFloat_AsDouble(arg);
- if
- GOOGLE_PREDICT_FALSE(*value == -1 && PyErr_Occurred()) {
- FormatTypeError(arg, "int, long, float");
- return false;
+ if (GOOGLE_PREDICT_FALSE(*value == -1 && PyErr_Occurred())) {
+ FormatTypeError(arg, "int, long, float");
+ return false;
}
return true;
}
@@ -839,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());
}
@@ -1187,7 +1176,7 @@ int InitAttributes(CMessage* self, PyObject* args, PyObject* kwargs) {
continue;
}
if (descriptor->is_map()) {
- ScopedPyObjectPtr map(GetAttr(self, name));
+ ScopedPyObjectPtr map(GetAttr(reinterpret_cast<PyObject*>(self), name));
const FieldDescriptor* value_descriptor =
descriptor->message_type()->FindFieldByName("value");
if (value_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
@@ -1215,7 +1204,8 @@ int InitAttributes(CMessage* self, PyObject* args, PyObject* kwargs) {
}
}
} else if (descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
- ScopedPyObjectPtr container(GetAttr(self, name));
+ ScopedPyObjectPtr container(
+ GetAttr(reinterpret_cast<PyObject*>(self), name));
if (container == NULL) {
return -1;
}
@@ -1282,7 +1272,8 @@ int InitAttributes(CMessage* self, PyObject* args, PyObject* kwargs) {
}
}
} else if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- ScopedPyObjectPtr message(GetAttr(self, name));
+ ScopedPyObjectPtr message(
+ GetAttr(reinterpret_cast<PyObject*>(self), name));
if (message == NULL) {
return -1;
}
@@ -1307,8 +1298,8 @@ int InitAttributes(CMessage* self, PyObject* args, PyObject* kwargs) {
return -1;
}
}
- if (SetAttr(self, name, (new_val.get() == NULL) ? value : new_val.get()) <
- 0) {
+ if (SetAttr(reinterpret_cast<PyObject*>(self), name,
+ (new_val.get() == NULL) ? value : new_val.get()) < 0) {
return -1;
}
}
@@ -1325,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;
@@ -1421,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));
}
@@ -1623,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) {
@@ -1649,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;
@@ -1686,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);
@@ -2211,7 +2205,8 @@ static PyObject* ListFields(CMessage* self) {
return NULL;
}
- PyObject* field_value = GetAttr(self, py_field_name.get());
+ PyObject* field_value =
+ GetAttr(reinterpret_cast<PyObject*>(self), py_field_name.get());
if (field_value == NULL) {
PyErr_SetObject(PyExc_ValueError, py_field_name.get());
return NULL;
@@ -2335,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;
}
@@ -2707,7 +2704,8 @@ static bool SetCompositeField(
return PyDict_SetItem(self->composite_fields, name, value) == 0;
}
-PyObject* GetAttr(CMessage* self, PyObject* name) {
+PyObject* GetAttr(PyObject* pself, PyObject* name) {
+ CMessage* self = reinterpret_cast<CMessage*>(pself);
PyObject* value = self->composite_fields ?
PyDict_GetItem(self->composite_fields, name) : NULL;
if (value != NULL) {
@@ -2785,7 +2783,8 @@ PyObject* GetAttr(CMessage* self, PyObject* name) {
return InternalGetScalar(self->message, field_descriptor);
}
-int SetAttr(CMessage* self, PyObject* name, PyObject* value) {
+int SetAttr(PyObject* pself, PyObject* name, PyObject* value) {
+ CMessage* self = reinterpret_cast<CMessage*>(pself);
if (self->composite_fields && PyDict_Contains(self->composite_fields, name)) {
PyErr_SetString(PyExc_TypeError, "Can't set composite field");
return -1;
@@ -2837,8 +2836,8 @@ PyTypeObject CMessage_Type = {
PyObject_HashNotImplemented, // tp_hash
0, // tp_call
(reprfunc)cmessage::ToStr, // tp_str
- (getattrofunc)cmessage::GetAttr, // tp_getattro
- (setattrofunc)cmessage::SetAttr, // tp_setattro
+ cmessage::GetAttr, // tp_getattro
+ cmessage::SetAttr, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
"A ProtocolMessage", // tp_doc
diff --git a/python/google/protobuf/pyext/message.h b/python/google/protobuf/pyext/message.h
index ce80497e..72bcfa83 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
@@ -240,22 +235,22 @@ PyObject* MergeFrom(CMessage* self, PyObject* arg);
// has been registered with the same field number on this class.
PyObject* RegisterExtension(PyObject* cls, PyObject* extension_handle);
-// Retrieves an attribute named 'name' from CMessage 'self'. Returns
-// the attribute value on success, or NULL on failure.
+// Retrieves an attribute named 'name' from 'self', which is interpreted as a
+// CMessage. Returns the attribute value on success, or null on failure.
//
// Returns a new reference.
-PyObject* GetAttr(CMessage* self, PyObject* name);
+PyObject* GetAttr(PyObject* self, PyObject* name);
-// Set the value of the attribute named 'name', for CMessage 'self',
-// to the value 'value'. Returns -1 on failure.
-int SetAttr(CMessage* self, PyObject* name, PyObject* value);
+// Set the value of the attribute named 'name', for 'self', which is interpreted
+// as a CMessage, to the value 'value'. Returns -1 on failure.
+int SetAttr(PyObject* self, PyObject* name, PyObject* value);
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)
@@ -347,6 +343,15 @@ extern PyObject* PickleError_class;
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/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 6b12632e..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()
@@ -938,7 +952,7 @@ def _SkipField(tokenizer):
tokenizer.ConsumeIdentifier()
tokenizer.Consume(']')
else:
- tokenizer.ConsumeIdentifier()
+ tokenizer.ConsumeIdentifierOrNumber()
_SkipFieldContents(tokenizer)
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 3d47079c..9a328cb5 100755
--- a/python/setup.py
+++ b/python/setup.py
@@ -107,6 +107,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 +120,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,12 +142,6 @@ 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)
@@ -202,9 +195,7 @@ if __name__ == '__main__':
extra_compile_args.append('-DMS_WIN64')
# MSVS default is dymanic
- if (sys.platform == 'win32' and
- ((sys.version_info[0] == 3 and sys.version_info[1] == 5) or
- (sys.version_info[0] == 3 and sys.version_info[1] == 6))):
+ if (sys.platform == 'win32'):
extra_compile_args.append('/MT')
if "clang" in os.popen('$CC --version 2> /dev/null').read():
@@ -215,6 +206,8 @@ if __name__ == '__main__':
v = float('.'.join(v.split('.')[:2]))
if v >= 10.12:
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')
diff --git a/ruby/README.md b/ruby/README.md
index f28e05a7..78e86015 100644
--- a/ruby/README.md
+++ b/ruby/README.md
@@ -16,10 +16,6 @@ install it as you would any other gem:
$ gem install [--prerelease] google-protobuf
-The `--pre` flag is necessary if we have not yet made a non-alpha/beta release
-of the Ruby extension; it allows `gem` to consider these "pre-release"
-alpha/beta versions.
-
Once the gem is installed, you may or may not need `protoc`. If you write your
message type descriptions directly in the Ruby DSL, you do not need it.
However, if you wish to generate the Ruby DSL from a `.proto` file, you will
diff --git a/ruby/Rakefile b/ruby/Rakefile
index 7aecfe85..ff09cebb 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
diff --git a/ruby/ext/google/protobuf_c/message.c b/ruby/ext/google/protobuf_c/message.c
index bc73d48c..63a61baf 100644
--- a/ruby/ext/google/protobuf_c/message.c
+++ b/ruby/ext/google/protobuf_c/message.c
@@ -540,9 +540,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);
diff --git a/ruby/ext/google/protobuf_c/storage.c b/ruby/ext/google/protobuf_c/storage.c
index 24064dfd..1437c0b5 100644
--- a/ruby/ext/google/protobuf_c/storage.c
+++ b/ruby/ext/google/protobuf_c/storage.c
@@ -606,12 +606,20 @@ static void check_repeated_field_type(VALUE val, const upb_fielddef* field) {
rb_raise(rb_eTypeError, "Repeated field array has wrong element type");
}
- if (self->field_type == UPB_TYPE_MESSAGE ||
- self->field_type == UPB_TYPE_ENUM) {
+ if (self->field_type == UPB_TYPE_MESSAGE) {
if (self->field_type_class !=
- get_def_obj(upb_fielddef_subdef(field))) {
+ Descriptor_msgclass(get_def_obj(upb_fielddef_subdef(field)))) {
rb_raise(rb_eTypeError,
- "Repeated field array has wrong message/enum class");
+ "Repeated field array has wrong message class");
+ }
+ }
+
+
+ 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,
+ "Repeated field array has wrong enum class");
}
}
}
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/tests/repeated_field_test.rb b/ruby/tests/repeated_field_test.rb
index 25727b7b..61ac4afd 100644
--- a/ruby/tests/repeated_field_test.rb
+++ b/ruby/tests/repeated_field_test.rb
@@ -126,6 +126,12 @@ class RepeatedFieldTest < Test::Unit::TestCase
assert_equal false, m.repeated_string.empty?
end
+ def test_reassign
+ m = TestMessage.new
+ m.repeated_msg = Google::Protobuf::RepeatedField.new(:message, TestMessage2, [TestMessage2.new(:foo => 1)])
+ assert_equal m.repeated_msg.first, TestMessage2.new(:foo => 1)
+ end
+
def test_array_accessor
m = TestMessage.new
reference_arr = %w(foo bar baz)
@@ -363,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/src/Makefile.am b/src/Makefile.am
index cdc2298b..7310210e 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -64,20 +64,6 @@ 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 +76,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 \
@@ -118,6 +101,8 @@ nobase_include_HEADERS = \
google/protobuf/generated_message_table_driven.h \
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 \
@@ -162,7 +147,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 \
@@ -188,8 +172,6 @@ libprotobuf_lite_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libprotobuf-lite.m
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 \
@@ -200,8 +182,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 \
@@ -222,6 +202,7 @@ libprotobuf_lite_la_SOURCES = \
google/protobuf/generated_message_util.cc \
google/protobuf/generated_message_table_driven_lite.h \
google/protobuf/generated_message_table_driven_lite.cc \
+ google/protobuf/implicit_weak_message.cc \
google/protobuf/message_lite.cc \
google/protobuf/repeated_field.cc \
google/protobuf/wire_format_lite.cc \
@@ -427,29 +408,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 \
@@ -587,11 +545,8 @@ EXTRA_DIST = \
$(js_well_known_types_sources) \
solaris/libstdc++.la \
google/protobuf/unittest_proto3.proto \
- google/protobuf/unittest_import_public_proto3.proto \
- google/protobuf/unittest_import_proto3.proto \
google/protobuf/test_messages_proto3.proto \
google/protobuf/test_messages_proto2.proto \
- google/protobuf/map_unittest_proto3.proto \
google/protobuf/io/gzip_stream.h \
google/protobuf/io/gzip_stream_unittest.sh \
google/protobuf/testdata/golden_message \
@@ -723,8 +678,6 @@ protoc_outputs = \
google/protobuf/util/message_differencer_unittest.pb.cc \
google/protobuf/util/message_differencer_unittest.pb.h
-BUILT_SOURCES = $(protoc_outputs) google/protobuf/compiler/js/well_known_types_embed.cc
-
if USE_EXTERNAL_PROTOC
unittest_proto_middleman: $(protoc_inputs)
@@ -752,20 +705,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.
@@ -775,7 +733,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 \
@@ -784,7 +741,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 \
@@ -797,10 +753,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 \
@@ -824,6 +781,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 \
@@ -847,24 +805,24 @@ protobuf_test_SOURCES = \
google/protobuf/util/time_util_test.cc \
google/protobuf/util/type_resolver_util_test.cc \
$(COMMON_TEST_SOURCES)
-
-
nodist_protobuf_test_SOURCES = $(protoc_outputs)
+$(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 = \
google/protobuf/compiler/cpp/cpp_unittest.cc \
$(COMMON_TEST_SOURCES)
nodist_protobuf_lazy_descriptor_test_SOURCES = $(protoc_outputs)
+$(am_protobuf_lazy_descriptor_test_OBJECTS): unittest_proto_middleman
COMMON_LITE_TEST_SOURCES = \
google/protobuf/arena_test_util.cc \
@@ -878,37 +836,39 @@ 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 \
$(COMMON_LITE_TEST_SOURCES)
nodist_protobuf_lite_test_SOURCES = $(protoc_lite_outputs)
+$(am_protobuf_lite_test_OBJECTS): unittest_proto_middleman
# lite_arena_unittest depends on gtest because teboring@ found that without
# 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 \
$(COMMON_LITE_TEST_SOURCES)
nodist_protobuf_lite_arena_test_SOURCES = $(protoc_lite_outputs)
+$(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 \
@@ -929,9 +889,7 @@ 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
diff --git a/src/README.md b/src/README.md
index c9362ee2..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,12 +184,22 @@ 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
library.
+Protobuf and its dependencies can be installed directly by using `vcpkg`:
+
+ >vcpkg install protobuf protobuf:x64-windows
+
+If zlib support is desired, you'll also need to install the zlib feature:
+
+ >vcpkg install protobuf[zlib] protobuf[zlib]:x64-windows
+
+See https://github.com/Microsoft/vcpkg for more information.
+
To build from source using Microsoft Visual C++, see [cmake/README.md](../cmake/README.md).
To build from source using Cygwin or MinGW, follow the Unix installation
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 29687477..9d632efe 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];
@@ -71,15 +68,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
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 ::google::protobuf::internal::once_flag once;
+ ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
@@ -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,17 +188,10 @@ 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();
}
-Any* Any::New(::google::protobuf::Arena* arena) const {
- Any* n = new Any;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
-}
void Any::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Any)
@@ -221,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)) {
@@ -359,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;
}
@@ -421,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 {
@@ -436,5 +424,12 @@ void Any::InternalSwap(Any* other) {
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
+namespace google {
+namespace protobuf {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Any* Arena::CreateMaybeMessage< ::google::protobuf::Any >(Arena* arena) {
+ return Arena::CreateInternal< ::google::protobuf::Any >(arena);
+}
+} // namespace protobuf
+} // namespace google
// @@protoc_insertion_point(global_scope)
diff --git a/src/google/protobuf/any.pb.h b/src/google/protobuf/any.pb.h
index 32847239..bc537999 100644
--- a/src/google/protobuf/any.pb.h
+++ b/src/google/protobuf/any.pb.h
@@ -1,8 +1,8 @@
// 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>
@@ -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,6 +55,11 @@ LIBPROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_;
} // namespace google
namespace google {
namespace protobuf {
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Any* Arena::CreateMaybeMessage<::google::protobuf::Any>(Arena*);
+} // namespace protobuf
+} // namespace google
+namespace google {
+namespace protobuf {
// ===================================================================
@@ -95,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 -----------------------------------------------
@@ -107,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) {
@@ -115,28 +119,33 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
// implements Message ----------------------------------------------
- inline Any* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Any* New() const final {
+ return CreateMaybeMessage<Any>(NULL);
+ }
- Any* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Any* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Any>(arena);
+ }
+ 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 {
@@ -147,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 ----------------------------------------------------
@@ -187,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();
};
// ===================================================================
@@ -320,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/any.proto b/src/google/protobuf/any.proto
index c7486676..49329425 100644
--- a/src/google/protobuf/any.proto
+++ b/src/google/protobuf/any.proto
@@ -120,17 +120,18 @@ option objc_class_prefix = "GPB";
// }
//
message Any {
- // A URL/resource name whose content describes the type of the
- // serialized protocol buffer message.
+ // 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).
//
- // For URLs which use the scheme `http`, `https`, or no scheme, the
- // following restrictions and interpretations apply:
+ // 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
@@ -139,6 +140,10 @@ message Any {
// 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.
//
diff --git a/src/google/protobuf/api.pb.cc b/src/google/protobuf/api.pb.cc
index 439a47c6..e0a249d0 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];
@@ -156,15 +151,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
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 ::google::protobuf::internal::once_flag once;
+ ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
@@ -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,17 +296,10 @@ 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();
}
-Api* Api::New(::google::protobuf::Arena* arena) const {
- Api* n = new Api;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
-}
void Api::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Api)
@@ -344,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)) {
@@ -368,7 +350,8 @@ bool Api::MergePartialFromCodedStream(
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_methods()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_methods()));
} else {
goto handle_unusual;
}
@@ -379,7 +362,8 @@ bool Api::MergePartialFromCodedStream(
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_options()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_options()));
} else {
goto handle_unusual;
}
@@ -418,7 +402,8 @@ bool Api::MergePartialFromCodedStream(
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_mixins()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_mixins()));
} else {
goto handle_unusual;
}
@@ -480,14 +465,18 @@ void Api::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->methods_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->methods(static_cast<int>(i)), output);
+ 2,
+ this->methods(static_cast<int>(i)),
+ output);
}
// repeated .google.protobuf.Option options = 3;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, this->options(static_cast<int>(i)), output);
+ 3,
+ this->options(static_cast<int>(i)),
+ output);
}
// string version = 4;
@@ -503,14 +492,16 @@ void Api::SerializeWithCachedSizes(
// .google.protobuf.SourceContext source_context = 5;
if (this->has_source_context()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 5, *this->source_context_, output);
+ 5, this->_internal_source_context(), output);
}
// repeated .google.protobuf.Mixin mixins = 6;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->mixins_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 6, this->mixins(static_cast<int>(i)), output);
+ 6,
+ this->mixins(static_cast<int>(i)),
+ output);
}
// .google.protobuf.Syntax syntax = 7;
@@ -575,7 +566,7 @@ void Api::SerializeWithCachedSizes(
if (this->has_source_context()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 5, *this->source_context_, deterministic, target);
+ 5, this->_internal_source_context(), deterministic, target);
}
// repeated .google.protobuf.Mixin mixins = 6;
@@ -660,7 +651,7 @@ size_t Api::ByteSizeLong() const {
if (this->has_source_context()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
- *this->source_context_);
+ *source_context_);
}
// .google.protobuf.Syntax syntax = 7;
@@ -670,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;
}
@@ -741,15 +730,16 @@ void Api::Swap(Api* other) {
}
void Api::InternalSwap(Api* other) {
using std::swap;
- methods_.InternalSwap(&other->methods_);
- options_.InternalSwap(&other->options_);
- mixins_.InternalSwap(&other->mixins_);
- name_.Swap(&other->name_);
- version_.Swap(&other->version_);
+ CastToBase(&methods_)->InternalSwap(CastToBase(&other->methods_));
+ CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
+ CastToBase(&mixins_)->InternalSwap(CastToBase(&other->mixins_));
+ 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 {
@@ -777,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) {
@@ -814,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() {
@@ -829,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();
@@ -839,17 +824,10 @@ 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();
}
-Method* Method::New(::google::protobuf::Arena* arena) const {
- Method* n = new Method;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
-}
void Method::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Method)
@@ -873,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)) {
@@ -957,7 +935,8 @@ bool Method::MergePartialFromCodedStream(
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_options()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_options()));
} else {
goto handle_unusual;
}
@@ -1049,7 +1028,9 @@ void Method::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 6, this->options(static_cast<int>(i)), output);
+ 6,
+ this->options(static_cast<int>(i)),
+ output);
}
// .google.protobuf.Syntax syntax = 7;
@@ -1195,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;
}
@@ -1271,15 +1250,17 @@ void Method::Swap(Method* other) {
}
void Method::InternalSwap(Method* other) {
using std::swap;
- options_.InternalSwap(&other->options_);
- name_.Swap(&other->name_);
- request_type_url_.Swap(&other->request_type_url_);
- response_type_url_.Swap(&other->response_type_url_);
+ CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
+ 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 {
@@ -1299,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) {
@@ -1324,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() {
@@ -1338,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();
@@ -1348,17 +1324,10 @@ 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();
}
-Mixin* Mixin::New(::google::protobuf::Arena* arena) const {
- Mixin* n = new Mixin;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
-}
void Mixin::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Mixin)
@@ -1377,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)) {
@@ -1527,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;
}
@@ -1589,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 {
@@ -1604,5 +1572,18 @@ void Mixin::InternalSwap(Mixin* other) {
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
+namespace google {
+namespace protobuf {
+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::CreateMaybeMessage< ::google::protobuf::Method >(Arena* arena) {
+ return Arena::CreateInternal< ::google::protobuf::Method >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Mixin* Arena::CreateMaybeMessage< ::google::protobuf::Mixin >(Arena* arena) {
+ return Arena::CreateInternal< ::google::protobuf::Mixin >(arena);
+}
+} // namespace protobuf
+} // namespace google
// @@protoc_insertion_point(global_scope)
diff --git a/src/google/protobuf/api.pb.h b/src/google/protobuf/api.pb.h
index 96ff3f15..5a720cce 100644
--- a/src/google/protobuf/api.pb.h
+++ b/src/google/protobuf/api.pb.h
@@ -1,8 +1,8 @@
// 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>
@@ -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,6 +62,13 @@ LIBPROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_;
} // namespace google
namespace google {
namespace protobuf {
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Api* Arena::CreateMaybeMessage<::google::protobuf::Api>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Method* Arena::CreateMaybeMessage<::google::protobuf::Method>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Mixin* Arena::CreateMaybeMessage<::google::protobuf::Mixin>(Arena*);
+} // namespace protobuf
+} // namespace google
+namespace google {
+namespace protobuf {
// ===================================================================
@@ -108,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);
@@ -118,28 +116,33 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
// implements Message ----------------------------------------------
- inline Api* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Api* New() const final {
+ return CreateMaybeMessage<Api>(NULL);
+ }
- Api* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Api* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Api>(arena);
+ }
+ 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 {
@@ -150,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 ----------------------------------------------------
@@ -160,11 +163,11 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
int methods_size() const;
void clear_methods();
static const int kMethodsFieldNumber = 2;
- const ::google::protobuf::Method& methods(int index) const;
::google::protobuf::Method* mutable_methods(int index);
- ::google::protobuf::Method* add_methods();
::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >*
mutable_methods();
+ const ::google::protobuf::Method& methods(int index) const;
+ ::google::protobuf::Method* add_methods();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >&
methods() const;
@@ -172,11 +175,11 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
int options_size() const;
void clear_options();
static const int kOptionsFieldNumber = 3;
- const ::google::protobuf::Option& options(int index) const;
::google::protobuf::Option* mutable_options(int index);
- ::google::protobuf::Option* add_options();
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
mutable_options();
+ const ::google::protobuf::Option& options(int index) const;
+ ::google::protobuf::Option* add_options();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
options() const;
@@ -184,11 +187,11 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
int mixins_size() const;
void clear_mixins();
static const int kMixinsFieldNumber = 6;
- const ::google::protobuf::Mixin& mixins(int index) const;
::google::protobuf::Mixin* mutable_mixins(int index);
- ::google::protobuf::Mixin* add_mixins();
::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >*
mutable_mixins();
+ const ::google::protobuf::Mixin& mixins(int index) const;
+ ::google::protobuf::Mixin* add_mixins();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >&
mixins() const;
@@ -224,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();
@@ -246,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();
};
// -------------------------------------------------------------------
@@ -286,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);
@@ -296,28 +301,33 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
// implements Message ----------------------------------------------
- inline Method* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Method* New() const final {
+ return CreateMaybeMessage<Method>(NULL);
+ }
- Method* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Method* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Method>(arena);
+ }
+ 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 {
@@ -328,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 ----------------------------------------------------
@@ -338,11 +348,11 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
int options_size() const;
void clear_options();
static const int kOptionsFieldNumber = 6;
- const ::google::protobuf::Option& options(int index) const;
::google::protobuf::Option* mutable_options(int index);
- ::google::protobuf::Option* add_options();
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
mutable_options();
+ const ::google::protobuf::Option& options(int index) const;
+ ::google::protobuf::Option* add_options();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
options() const;
@@ -417,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();
};
// -------------------------------------------------------------------
@@ -457,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);
@@ -467,28 +476,33 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
// implements Message ----------------------------------------------
- inline Mixin* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Mixin* New() const final {
+ return CreateMaybeMessage<Mixin>(NULL);
+ }
- Mixin* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Mixin* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Mixin>(arena);
+ }
+ 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 {
@@ -499,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 ----------------------------------------------------
@@ -539,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();
};
// ===================================================================
@@ -614,23 +627,23 @@ inline int Api::methods_size() const {
inline void Api::clear_methods() {
methods_.Clear();
}
-inline const ::google::protobuf::Method& Api::methods(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Api.methods)
- return methods_.Get(index);
-}
inline ::google::protobuf::Method* Api::mutable_methods(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.Api.methods)
return methods_.Mutable(index);
}
-inline ::google::protobuf::Method* Api::add_methods() {
- // @@protoc_insertion_point(field_add:google.protobuf.Api.methods)
- return methods_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >*
Api::mutable_methods() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.Api.methods)
return &methods_;
}
+inline const ::google::protobuf::Method& Api::methods(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.Api.methods)
+ return methods_.Get(index);
+}
+inline ::google::protobuf::Method* Api::add_methods() {
+ // @@protoc_insertion_point(field_add:google.protobuf.Api.methods)
+ return methods_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >&
Api::methods() const {
// @@protoc_insertion_point(field_list:google.protobuf.Api.methods)
@@ -641,23 +654,23 @@ Api::methods() const {
inline int Api::options_size() const {
return options_.size();
}
-inline const ::google::protobuf::Option& Api::options(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Api.options)
- return options_.Get(index);
-}
inline ::google::protobuf::Option* Api::mutable_options(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.Api.options)
return options_.Mutable(index);
}
-inline ::google::protobuf::Option* Api::add_options() {
- // @@protoc_insertion_point(field_add:google.protobuf.Api.options)
- return options_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
Api::mutable_options() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.Api.options)
return &options_;
}
+inline const ::google::protobuf::Option& Api::options(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.Api.options)
+ return options_.Get(index);
+}
+inline ::google::protobuf::Option* Api::add_options() {
+ // @@protoc_insertion_point(field_add:google.protobuf.Api.options)
+ return options_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
Api::options() const {
// @@protoc_insertion_point(field_list:google.protobuf.Api.options)
@@ -721,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)
@@ -737,7 +753,8 @@ inline ::google::protobuf::SourceContext* Api::release_source_context() {
inline ::google::protobuf::SourceContext* Api::mutable_source_context() {
if (source_context_ == NULL) {
- source_context_ = new ::google::protobuf::SourceContext;
+ auto* p = CreateMaybeMessage<::google::protobuf::SourceContext>(GetArenaNoVirtual());
+ source_context_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Api.source_context)
return source_context_;
@@ -768,23 +785,23 @@ inline int Api::mixins_size() const {
inline void Api::clear_mixins() {
mixins_.Clear();
}
-inline const ::google::protobuf::Mixin& Api::mixins(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Api.mixins)
- return mixins_.Get(index);
-}
inline ::google::protobuf::Mixin* Api::mutable_mixins(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.Api.mixins)
return mixins_.Mutable(index);
}
-inline ::google::protobuf::Mixin* Api::add_mixins() {
- // @@protoc_insertion_point(field_add:google.protobuf.Api.mixins)
- return mixins_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >*
Api::mutable_mixins() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.Api.mixins)
return &mixins_;
}
+inline const ::google::protobuf::Mixin& Api::mixins(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.Api.mixins)
+ return mixins_.Get(index);
+}
+inline ::google::protobuf::Mixin* Api::add_mixins() {
+ // @@protoc_insertion_point(field_add:google.protobuf.Api.mixins)
+ return mixins_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >&
Api::mixins() const {
// @@protoc_insertion_point(field_list:google.protobuf.Api.mixins)
@@ -1000,23 +1017,23 @@ inline void Method::set_response_streaming(bool value) {
inline int Method::options_size() const {
return options_.size();
}
-inline const ::google::protobuf::Option& Method::options(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Method.options)
- return options_.Get(index);
-}
inline ::google::protobuf::Option* Method::mutable_options(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.Method.options)
return options_.Mutable(index);
}
-inline ::google::protobuf::Option* Method::add_options() {
- // @@protoc_insertion_point(field_add:google.protobuf.Method.options)
- return options_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
Method::mutable_options() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.Method.options)
return &options_;
}
+inline const ::google::protobuf::Option& Method::options(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.Method.options)
+ return options_.Get(index);
+}
+inline ::google::protobuf::Option* Method::add_options() {
+ // @@protoc_insertion_point(field_add:google.protobuf.Method.options)
+ return options_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
Method::options() const {
// @@protoc_insertion_point(field_list:google.protobuf.Method.options)
@@ -1162,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 e9289988..c117c9e5 100755
--- 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,24 +65,25 @@ 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
// single-threaded case to allocate on the first block without having to
// perform atomic operations.
- InitBlock(initial_block_, &thread_cache(), options_.initial_block_size);
- ThreadInfo* info = NewThreadInfo(initial_block_);
- info->next = NULL;
- google::protobuf::internal::NoBarrier_Store(&threads_,
- reinterpret_cast<google::protobuf::internal::AtomicWord>(info));
- google::protobuf::internal::NoBarrier_Store(&space_allocated_,
- options_.initial_block_size);
- CacheBlock(initial_block_);
+ new (initial_block_) Block(options_.initial_block_size, NULL);
+ SerialArena* serial =
+ SerialArena::New(initial_block_, &thread_cache(), this);
+ serial->set_next(NULL);
+ 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);
}
}
@@ -103,164 +104,158 @@ uint64 ArenaImpl::Reset() {
return space_allocated;
}
-ArenaImpl::Block* ArenaImpl::NewBlock(void* me, Block* my_last_block,
- size_t min_bytes) {
+ArenaImpl::Block* ArenaImpl::NewBlock(Block* last_block, size_t min_bytes) {
size_t size;
- if (my_last_block != NULL) {
+ if (last_block) {
// Double the current block size, up to a limit.
- size = std::min(2 * my_last_block->size, options_.max_block_size);
+ size = std::min(2 * last_block->size(), options_.max_block_size);
} else {
size = options_.start_block_size;
}
- // Verify that min_bytes + kHeaderSize won't overflow.
- GOOGLE_CHECK_LE(min_bytes, std::numeric_limits<size_t>::max() - kHeaderSize);
- size = std::max(size, kHeaderSize + min_bytes);
+ // Verify that min_bytes + kBlockHeaderSize won't overflow.
+ GOOGLE_CHECK_LE(min_bytes, std::numeric_limits<size_t>::max() - kBlockHeaderSize);
+ size = std::max(size, kBlockHeaderSize + min_bytes);
- Block* b = reinterpret_cast<Block*>(options_.block_alloc(size));
- InitBlock(b, me, size);
- google::protobuf::internal::NoBarrier_AtomicIncrement(&space_allocated_, size);
+ void* mem = options_.block_alloc(size);
+ Block* b = new (mem) Block(size, last_block);
+ space_allocated_.fetch_add(size, std::memory_order_relaxed);
return b;
}
-void ArenaImpl::InitBlock(Block* b, void *me, size_t size) {
- b->pos = kHeaderSize;
- b->size = size;
- b->owner = me;
- b->next = NULL;
-#ifdef ADDRESS_SANITIZER
- // Poison the rest of the block for ASAN. It was unpoisoned by the underlying
- // malloc but it's not yet usable until we return it as part of an allocation.
- ASAN_POISON_MEMORY_REGION(
- reinterpret_cast<char*>(b) + b->pos, b->size - b->pos);
-#endif // ADDRESS_SANITIZER
-}
+ArenaImpl::Block::Block(size_t size, Block* next)
+ : next_(next), pos_(kBlockHeaderSize), size_(size) {}
-ArenaImpl::CleanupChunk* ArenaImpl::ExpandCleanupList(CleanupChunk* cleanup,
- Block* b) {
- size_t size = cleanup ? cleanup->size * 2 : kMinCleanupListElements;
+GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+void ArenaImpl::SerialArena::AddCleanupFallback(void* elem,
+ void (*cleanup)(void*)) {
+ size_t size = cleanup_ ? cleanup_->size * 2 : kMinCleanupListElements;
size = std::min(size, kMaxCleanupListElements);
size_t bytes = internal::AlignUpTo8(CleanupChunk::SizeOf(size));
- if (b->avail() < bytes) {
- b = GetBlock(bytes);
- }
- CleanupChunk* list =
- reinterpret_cast<CleanupChunk*>(AllocFromBlock(b, bytes));
- list->next = b->thread_info->cleanup;
+ CleanupChunk* list = reinterpret_cast<CleanupChunk*>(AllocateAligned(bytes));
+ list->next = cleanup_;
list->size = size;
- list->len = 0;
- b->thread_info->cleanup = list;
- return list;
+
+ cleanup_ = list;
+ cleanup_ptr_ = &list->nodes[0];
+ cleanup_limit_ = &list->nodes[size];
+
+ AddCleanup(elem, cleanup);
}
-inline GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
-void ArenaImpl::AddCleanupInBlock(
- Block* b, void* elem, void (*func)(void*)) {
- CleanupChunk* cleanup = b->thread_info->cleanup;
- if (cleanup == NULL || cleanup->len == cleanup->size) {
- cleanup = ExpandCleanupList(cleanup, b);
+GOOGLE_PROTOBUF_ATTRIBUTE_FUNC_ALIGN(32)
+void* ArenaImpl::AllocateAligned(size_t n) {
+ SerialArena* arena;
+ if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) {
+ return arena->AllocateAligned(n);
+ } else {
+ return AllocateAlignedFallback(n);
}
+}
- CleanupNode* node = &cleanup->nodes[cleanup->len++];
-
- node->elem = elem;
- node->cleanup = func;
+void* ArenaImpl::AllocateAlignedAndAddCleanup(size_t n,
+ void (*cleanup)(void*)) {
+ SerialArena* arena;
+ if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) {
+ return arena->AllocateAlignedAndAddCleanup(n, cleanup);
+ } else {
+ return AllocateAlignedAndAddCleanupFallback(n, cleanup);
+ }
}
void ArenaImpl::AddCleanup(void* elem, void (*cleanup)(void*)) {
- return AddCleanupInBlock(GetBlock(0), elem, cleanup);
+ SerialArena* arena;
+ if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) {
+ arena->AddCleanup(elem, cleanup);
+ } else {
+ return AddCleanupFallback(elem, cleanup);
+ }
}
-void* ArenaImpl::AllocateAligned(size_t n) {
- GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
-
- return AllocFromBlock(GetBlock(n), n);
+GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+void* ArenaImpl::AllocateAlignedFallback(size_t n) {
+ return GetSerialArena()->AllocateAligned(n);
}
-void* ArenaImpl::AllocateAlignedAndAddCleanup(size_t n,
- void (*cleanup)(void*)) {
- GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
+GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+void* ArenaImpl::AllocateAlignedAndAddCleanupFallback(size_t n,
+ void (*cleanup)(void*)) {
+ return GetSerialArena()->AllocateAlignedAndAddCleanup(n, cleanup);
+}
- Block* b = GetBlock(n);
- void* mem = AllocFromBlock(b, n);
- AddCleanupInBlock(b, mem, cleanup);
- return mem;
+GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+void ArenaImpl::AddCleanupFallback(void* elem, void (*cleanup)(void*)) {
+ GetSerialArena()->AddCleanup(elem, cleanup);
}
inline GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
-ArenaImpl::Block* ArenaImpl::GetBlock(size_t n) {
- Block* my_block = NULL;
-
+bool ArenaImpl::GetSerialArenaFast(ArenaImpl::SerialArena** arena) {
// If this thread already owns a block in this arena then try to use that.
// This fast path optimizes the case where multiple threads allocate from the
// same arena.
ThreadCache* tc = &thread_cache();
- if (tc->last_lifecycle_id_seen == lifecycle_id_) {
- my_block = tc->last_block_used_;
- if (my_block->avail() >= n) {
- return my_block;
- }
+ if (GOOGLE_PREDICT_TRUE(tc->last_lifecycle_id_seen == lifecycle_id_)) {
+ *arena = tc->last_serial_arena;
+ return true;
}
- // Check whether we own the last accessed block on this arena.
- // This fast path optimizes the case where a single thread uses multiple
- // arenas.
- Block* b = reinterpret_cast<Block*>(google::protobuf::internal::Acquire_Load(&hint_));
- if (b != NULL && b->owner == tc) {
- my_block = b;
- if (my_block->avail() >= n) {
- return my_block;
- }
+ // Check whether we own the last accessed SerialArena on this arena. This
+ // fast path optimizes the case where a single thread uses multiple arenas.
+ SerialArena* serial = hint_.load(std::memory_order_acquire);
+ if (GOOGLE_PREDICT_TRUE(serial != NULL && serial->owner() == tc)) {
+ *arena = serial;
+ return true;
}
- return GetBlockSlow(tc, my_block, n);
+
+ return false;
}
-inline GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
-void* ArenaImpl::AllocFromBlock(Block* b, size_t n) {
- GOOGLE_DCHECK_EQ(internal::AlignUpTo8(b->pos), b->pos); // Must be already aligned.
- GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
- GOOGLE_DCHECK_GE(b->avail(), n);
- size_t p = b->pos;
- b->pos = p + n;
+ArenaImpl::SerialArena* ArenaImpl::GetSerialArena() {
+ SerialArena* arena;
+ if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) {
+ return arena;
+ } else {
+ return GetSerialArenaFallback(&thread_cache());
+ }
+}
+
+GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+void* ArenaImpl::SerialArena::AllocateAlignedFallback(size_t n) {
+ // Sync back to current's pos.
+ head_->set_pos(head_->size() - (limit_ - ptr_));
+
+ head_ = arena_->NewBlock(head_, n);
+ ptr_ = head_->Pointer(head_->pos());
+ limit_ = head_->Pointer(head_->size());
+
#ifdef ADDRESS_SANITIZER
- ASAN_UNPOISON_MEMORY_REGION(reinterpret_cast<char*>(b) + p, n);
+ ASAN_POISON_MEMORY_REGION(ptr_, limit_ - ptr_);
#endif // ADDRESS_SANITIZER
- return reinterpret_cast<char*>(b) + p;
-}
-ArenaImpl::Block* ArenaImpl::GetBlockSlow(void* me, Block* my_full_block,
- size_t n) {
- ThreadInfo* info =
- my_full_block ? my_full_block->thread_info : GetThreadInfo(me, n);
- GOOGLE_DCHECK(info != NULL);
- Block* b = info->head;
- if (b->avail() < n) {
- Block* new_b = NewBlock(me, b, n);
- new_b->thread_info = info;
- new_b->next = b;
- info->head = new_b;
- b = new_b;
- }
- CacheBlock(b);
- return b;
+ return AllocateAligned(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 {
- ThreadInfo* info =
- reinterpret_cast<ThreadInfo*>(google::protobuf::internal::Acquire_Load(&threads_));
+ SerialArena* serial = threads_.load(std::memory_order_acquire);
uint64 space_used = 0;
-
- for ( ; info; info = info->next) {
- // Remove the overhead of the ThreadInfo itself.
- space_used -= sizeof(ThreadInfo);
- for (Block* b = info->head; b; b = b->next) {
- space_used += (b->pos - kHeaderSize);
- }
+ for ( ; serial; serial = serial->next()) {
+ space_used += serial->SpaceUsed();
}
+ return space_used;
+}
+uint64 ArenaImpl::SerialArena::SpaceUsed() const {
+ // Get current block's size from ptr_ (since we can't trust head_->pos().
+ uint64 space_used = ptr_ - head_->Pointer(kBlockHeaderSize);
+ // Get subsequent block size from b->pos().
+ for (Block* b = head_->next(); b; b = b->next()) {
+ space_used += (b->pos() - kBlockHeaderSize);
+ }
+ // Remove the overhead of the SerialArena itself.
+ space_used -= kSerialArenaSize;
return space_used;
}
@@ -268,30 +263,44 @@ 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.
- ThreadInfo* info =
- reinterpret_cast<ThreadInfo*>(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.
+ SerialArena* next = serial->next();
+ space_allocated += ArenaImpl::SerialArena::Free(serial, initial_block_,
+ options_.block_dealloc);
+ // serial is dead now.
+ serial = next;
+ }
- while (info) {
+ return space_allocated;
+}
+
+uint64 ArenaImpl::SerialArena::Free(ArenaImpl::SerialArena* serial,
+ Block* initial_block,
+ void (*block_dealloc)(void*, size_t)) {
+ uint64 space_allocated = 0;
+
+ // We have to be careful in this function, since we will be freeing the Block
+ // that contains this SerialArena. Be careful about accessing |serial|.
+
+ for (Block* b = serial->head_; b; ) {
// This is inside the block we are freeing, so we need to read it now.
- ThreadInfo* next_info = info->next;
- for (Block* b = info->head; b; ) {
- // This is inside the block we are freeing, so we need to read it now.
- Block* next_block = b->next;
- space_allocated += (b->size);
+ Block* next_block = b->next();
+ space_allocated += (b->size());
#ifdef ADDRESS_SANITIZER
- // This memory was provided by the underlying allocator as unpoisoned, so
- // return it in an unpoisoned state.
- ASAN_UNPOISON_MEMORY_REGION(reinterpret_cast<char*>(b), b->size);
+ // This memory was provided by the underlying allocator as unpoisoned, so
+ // return it in an unpoisoned state.
+ ASAN_UNPOISON_MEMORY_REGION(b->Pointer(0), b->size());
#endif // ADDRESS_SANITIZER
- if (b != initial_block_) {
- options_.block_dealloc(b, b->size);
- }
-
- b = next_block;
+ if (b != initial_block) {
+ block_dealloc(b, b->size());
}
- info = next_info;
+
+ b = next_block;
}
return space_allocated;
@@ -300,63 +309,84 @@ uint64 ArenaImpl::FreeBlocks() {
void ArenaImpl::CleanupList() {
// By omitting an Acquire barrier we ensure that any user code that doesn't
// properly synchronize Reset() or the destructor will throw a TSAN warning.
- ThreadInfo* info =
- reinterpret_cast<ThreadInfo*>(google::protobuf::internal::NoBarrier_Load(&threads_));
-
- for ( ; info; info = info->next) {
- CleanupChunk* list = info->cleanup;
- while (list) {
- size_t n = list->len;
- CleanupNode* node = &list->nodes[list->len - 1];
- for (size_t i = 0; i < n; i++, node--) {
- node->cleanup(node->elem);
- }
- list = list->next;
- }
+ SerialArena* serial = threads_.load(std::memory_order_relaxed);
+
+ for ( ; serial; serial = serial->next()) {
+ serial->CleanupList();
}
}
-ArenaImpl::ThreadInfo* ArenaImpl::NewThreadInfo(Block* b) {
- GOOGLE_DCHECK(FindThreadInfo(b->owner) == NULL);
- ThreadInfo* info =
- reinterpret_cast<ThreadInfo*>(AllocFromBlock(b, sizeof(ThreadInfo)));
- b->thread_info = info;
- info->owner = b->owner;
- info->head = b;
- info->cleanup = NULL;
- return info;
+void ArenaImpl::SerialArena::CleanupList() {
+ if (cleanup_ != NULL) {
+ CleanupListFallback();
+ }
}
-ArenaImpl::ThreadInfo* ArenaImpl::FindThreadInfo(void* me) {
- ThreadInfo* info =
- reinterpret_cast<ThreadInfo*>(google::protobuf::internal::Acquire_Load(&threads_));
- for ( ; info; info = info->next) {
- if (info->owner == me) {
- return info;
+void ArenaImpl::SerialArena::CleanupListFallback() {
+ // Cleanup newest chunk: ptrs give us length.
+ size_t n = cleanup_ptr_ - &cleanup_->nodes[0];
+ CleanupNode* node = cleanup_ptr_;
+ for (size_t i = 0; i < n; i++) {
+ --node;
+ node->cleanup(node->elem);
+ }
+
+ // Cleanup older chunks, which are known to be full.
+ CleanupChunk* list = cleanup_->next;
+ while (list) {
+ size_t n = list->size;
+ CleanupNode* node = &list->nodes[list->size];
+ for (size_t i = 0; i < n; i++) {
+ --node;
+ node->cleanup(node->elem);
}
+ list = list->next;
}
+}
- return NULL;
+ArenaImpl::SerialArena* ArenaImpl::SerialArena::New(Block* b, void* owner,
+ ArenaImpl* arena) {
+ GOOGLE_DCHECK_EQ(b->pos(), kBlockHeaderSize); // Should be a fresh block
+ GOOGLE_DCHECK_LE(kBlockHeaderSize + kSerialArenaSize, b->size());
+ SerialArena* serial =
+ reinterpret_cast<SerialArena*>(b->Pointer(kBlockHeaderSize));
+ b->set_pos(kBlockHeaderSize + kSerialArenaSize);
+ serial->arena_ = arena;
+ serial->owner_ = owner;
+ serial->head_ = b;
+ serial->ptr_ = b->Pointer(b->pos());
+ serial->limit_ = b->Pointer(b->size());
+ serial->cleanup_ = NULL;
+ serial->cleanup_ptr_ = NULL;
+ serial->cleanup_limit_ = NULL;
+ return serial;
}
-ArenaImpl::ThreadInfo* ArenaImpl::GetThreadInfo(void* me, size_t n) {
- ThreadInfo* info = FindThreadInfo(me);
+GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+ArenaImpl::SerialArena* ArenaImpl::GetSerialArenaFallback(void* me) {
+ // Look for this SerialArena in our linked list.
+ SerialArena* serial = threads_.load(std::memory_order_acquire);
+ for ( ; serial; serial = serial->next()) {
+ if (serial->owner() == me) {
+ break;
+ }
+ }
- if (!info) {
- // This thread doesn't have any ThreadInfo, which also means it doesn't have
- // any blocks yet. So we'll allocate its first block now.
- Block* b = NewBlock(me, NULL, sizeof(ThreadInfo) + n);
- info = NewThreadInfo(b);
+ if (!serial) {
+ // This thread doesn't have any SerialArena, which also means it doesn't
+ // have any blocks yet. So we'll allocate its first block now.
+ 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_);
- info->next = reinterpret_cast<ThreadInfo*>(head);
- } while (google::protobuf::internal::Release_CompareAndSwap(
- &threads_, head, reinterpret_cast<google::protobuf::internal::AtomicWord>(info)) != head);
+ serial->set_next(head);
+ } while (!threads_.compare_exchange_weak(
+ head, serial, std::memory_order_release, std::memory_order_relaxed));
}
- return info;
+ CacheSerialArena(serial);
+ return serial;
}
} // namespace internal
diff --git a/src/google/protobuf/arena.h b/src/google/protobuf/arena.h
index 32be9a17..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,25 +50,48 @@ using type_info = ::type_info;
#include <google/protobuf/arena_impl.h>
#include <google/protobuf/stubs/port.h>
+#include <type_traits>
namespace google {
namespace protobuf {
-class Arena; // defined below
-class Message; // message.h
+struct ArenaOptions; // defined below
+
+} // namespace protobuf
+
+namespace quality_webanswers {
+
+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
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) {
@@ -117,6 +137,20 @@ struct ArenaOptions {
// from the arena. By default, it contains a ptr to a wrapper function that
// calls free.
void (*block_dealloc)(void*, size_t);
+
+ ArenaOptions()
+ : start_block_size(kDefaultStartBlockSize),
+ max_block_size(kDefaultMaxBlockSize),
+ initial_block(NULL),
+ initial_block_size(0),
+ block_alloc(&::operator new),
+ block_dealloc(&internal::arena_free),
+ on_arena_init(NULL),
+ on_arena_reset(NULL),
+ on_arena_destruction(NULL),
+ on_arena_allocation(NULL) {}
+
+ private:
// Hooks for adding external functionality such as user-specific metrics
// collection, specific debugging abilities, etc.
// Init hook may return a pointer to a cookie to be stored in the arena.
@@ -136,25 +170,17 @@ 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);
-
- ArenaOptions()
- : start_block_size(kDefaultStartBlockSize),
- max_block_size(kDefaultMaxBlockSize),
- initial_block(NULL),
- initial_block_size(0),
- block_alloc(&::operator new),
- block_dealloc(&internal::arena_free),
- on_arena_init(NULL),
- on_arena_reset(NULL),
- on_arena_destruction(NULL),
- on_arena_allocation(NULL) {}
+ uint64 alloc_size, void* cookie);
- private:
// 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*);
+ friend class Arena;
+ friend class ArenaOptionsTestFriend;
};
// Support for non-RTTI environments. (The metrics hooks API uses type
@@ -229,14 +255,15 @@ class LIBPROTOBUF_EXPORT Arena {
// WARNING: if you allocate multiple objects, it is difficult to guarantee
// that a series of allocations will fit in the initial block, especially if
// Arena changes its alignment guarantees in the future!
- static const size_t kBlockOverhead = internal::ArenaImpl::kHeaderSize;
+ static const size_t kBlockOverhead = internal::ArenaImpl::kBlockHeaderSize +
+ internal::ArenaImpl::kSerialArenaSize;
// Default constructor with sensible default options, tuned for average
// use-cases.
Arena() : impl_(ArenaOptions()) { Init(ArenaOptions()); }
~Arena() {
- if (on_arena_reset_ != NULL || on_arena_destruction_ != NULL) {
+ if (hooks_cookie_) {
CallDestructorHooks();
}
}
@@ -263,69 +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
@@ -343,152 +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
@@ -497,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)));
@@ -522,6 +359,7 @@ class LIBPROTOBUF_EXPORT Arena {
//
// Combines SpaceAllocated and SpaceUsed. Returns a pair of
// <space_allocated, space_used>.
+ PROTOBUF_RUNTIME_DEPRECATED("Please use SpaceAllocated() and SpaceUsed()")
std::pair<uint64, uint64> SpaceAllocatedAndUsed() const {
return std::make_pair(SpaceAllocated(), SpaceUsed());
}
@@ -541,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
@@ -551,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>);
}
@@ -571,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>());
}
@@ -583,60 +422,92 @@ 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, 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");
+ if (arena == NULL) {
+ return new T(nullptr, std::forward<Args>(args)...);
+ } else {
+ return arena->DoCreateMessage<T>(std::forward<Args>(args)...);
+ }
+ }
+
+ // 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->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)...);
+ }
+ }
+
void CallDestructorHooks();
void OnArenaAllocation(const std::type_info* allocated_type, size_t n) const;
inline void AllocHook(const std::type_info* allocated_type, size_t n) const {
@@ -648,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.
@@ -666,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 CreateMessage<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, 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, 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> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static T* CreateMaybeMessage(Arena* arena, google::protobuf::internal::false_type) {
- return Create<T>(arena);
+ 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> 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* 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.
@@ -694,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,
@@ -845,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);
}
@@ -869,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>);
}
@@ -886,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;
}
@@ -907,7 +676,6 @@ class LIBPROTOBUF_EXPORT Arena {
internal::ArenaImpl impl_;
- void* (*on_arena_init_)(Arena* arena);
void (*on_arena_allocation_)(const std::type_info* allocated_type,
uint64 alloc_size, void* cookie);
void (*on_arena_reset_)(Arena* arena, void* cookie, uint64 space_used);
@@ -918,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 6cc7096b..f648f166 100644
--- a/src/google/protobuf/arena_impl.h
+++ b/src/google/protobuf/arena_impl.h
@@ -33,17 +33,18 @@
#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/type_traits.h>
#include <google/protobuf/stubs/port.h>
+#ifdef ADDRESS_SANITIZER
+#include <sanitizer/asan_interface.h>
+#endif // ADDRESS_SANITIZER
+
namespace google {
namespace protobuf {
@@ -112,6 +113,10 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
void AddCleanup(void* elem, void (*cleanup)(void*));
private:
+ void* AllocateAlignedFallback(size_t n);
+ void* AllocateAlignedAndAddCleanupFallback(size_t n, void (*cleanup)(void*));
+ void AddCleanupFallback(void* elem, void (*cleanup)(void*));
+
// Node contains the ptr of the object to be cleaned up and the associated
// cleanup function ptr.
struct CleanupNode {
@@ -124,34 +129,107 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
static size_t SizeOf(size_t i) {
return sizeof(CleanupChunk) + (sizeof(CleanupNode) * (i - 1));
}
- size_t len; // Number of elements currently present.
size_t size; // Total elements in the list.
CleanupChunk* next; // Next node in the list.
CleanupNode nodes[1]; // True length is |size|.
};
- struct Block;
+ class Block;
+
+ // A thread-unsafe Arena that can only be used within its owning thread.
+ class LIBPROTOBUF_EXPORT SerialArena {
+ public:
+ // The allocate/free methods here are a little strange, since SerialArena is
+ // allocated inside a Block which it also manages. This is to avoid doing
+ // an extra allocation for the SerialArena itself.
+
+ // Creates a new SerialArena inside Block* and returns it.
+ static SerialArena* New(Block* b, void* owner, ArenaImpl* arena);
+
+ // Destroys this SerialArena, freeing all blocks with the given dealloc
+ // function, except any block equal to |initial_block|.
+ static uint64 Free(SerialArena* serial, Block* initial_block,
+ void (*block_dealloc)(void*, size_t));
+
+ void CleanupList();
+ uint64 SpaceUsed() const;
+
+ void* AllocateAligned(size_t n) {
+ GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
+ GOOGLE_DCHECK_GE(limit_, ptr_);
+ if (GOOGLE_PREDICT_FALSE(static_cast<size_t>(limit_ - ptr_) < n)) {
+ return AllocateAlignedFallback(n);
+ }
+ void* ret = ptr_;
+ ptr_ += n;
+#ifdef ADDRESS_SANITIZER
+ ASAN_UNPOISON_MEMORY_REGION(ret, n);
+#endif // ADDRESS_SANITIZER
+ return ret;
+ }
+
+ void AddCleanup(void* elem, void (*cleanup)(void*)) {
+ if (GOOGLE_PREDICT_FALSE(cleanup_ptr_ == cleanup_limit_)) {
+ AddCleanupFallback(elem, cleanup);
+ return;
+ }
+ cleanup_ptr_->elem = elem;
+ cleanup_ptr_->cleanup = cleanup;
+ cleanup_ptr_++;
+ }
+
+ void* AllocateAlignedAndAddCleanup(size_t n, void (*cleanup)(void*)) {
+ void* ret = AllocateAligned(n);
+ AddCleanup(ret, cleanup);
+ return ret;
+ }
- // Tracks per-thread info. ThreadInfos are kept in a linked list.
- struct ThreadInfo {
- void *owner; // &ThreadCache of this thread;
- Block* head; // Head of linked list of blocks.
- CleanupChunk* cleanup; // Head of cleanup list.
- ThreadInfo* next; // Next ThreadInfo in this linked list.
+ void* owner() const { return owner_; }
+ SerialArena* next() const { return next_; }
+ void set_next(SerialArena* next) { next_ = next; }
+
+ private:
+ void* AllocateAlignedFallback(size_t n);
+ void AddCleanupFallback(void* elem, void (*cleanup)(void*));
+ void CleanupListFallback();
+
+ ArenaImpl* arena_; // Containing arena.
+ void* owner_; // &ThreadCache of this thread;
+ Block* head_; // Head of linked list of blocks.
+ CleanupChunk* cleanup_; // Head of cleanup list.
+ SerialArena* next_; // Next SerialArena in this linked list.
+
+ // Next pointer to allocate from. Always 8-byte aligned. Points inside
+ // head_ (and head_->pos will always be non-canonical). We keep these
+ // here to reduce indirection.
+ char* ptr_;
+ char* limit_;
+
+ // Next CleanupList members to append to. These point inside cleanup_.
+ CleanupNode* cleanup_ptr_;
+ CleanupNode* cleanup_limit_;
};
// Blocks are variable length malloc-ed objects. The following structure
// describes the common header for all blocks.
- struct Block {
- void* owner; // &ThreadCache of thread that owns this block.
- ThreadInfo* thread_info; // ThreadInfo of thread that owns this block.
- Block* next; // Next block in arena (may have different owner)
- // ((char*) &block) + pos is next available byte. It is always
- // aligned at a multiple of 8 bytes.
- size_t pos;
- size_t size; // total size of the block.
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- size_t avail() const { return size - pos; }
+ class LIBPROTOBUF_EXPORT Block {
+ public:
+ Block(size_t size, Block* next);
+
+ char* Pointer(size_t n) {
+ GOOGLE_DCHECK(n <= size_);
+ return reinterpret_cast<char*>(this) + n;
+ }
+
+ Block* next() const { return next_; }
+ size_t pos() const { return pos_; }
+ size_t size() const { return size_; }
+ void set_pos(size_t pos) { pos_ = pos; }
+
+ private:
+ Block* next_; // Next block for this thread.
+ size_t pos_;
+ size_t size_;
// data follows
};
@@ -160,15 +238,15 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
// If we are using the ThreadLocalStorage class to store the ThreadCache,
// then the ThreadCache's default constructor has to be responsible for
// initializing it.
- ThreadCache() : last_lifecycle_id_seen(-1), last_block_used_(NULL) {}
+ ThreadCache() : last_lifecycle_id_seen(-1), last_serial_arena(NULL) {}
#endif
// The ThreadCache is considered valid as long as this matches the
// lifecycle_id of the arena being used.
int64 last_lifecycle_id_seen;
- Block* last_block_used_;
+ 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.
@@ -188,51 +266,52 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
// Free all blocks and return the total space used which is the sums of sizes
// of the all the allocated blocks.
uint64 FreeBlocks();
-
- void AddCleanupInBlock(Block* b, void* elem, void (*func)(void*));
- CleanupChunk* ExpandCleanupList(CleanupChunk* cleanup, Block* b);
// Delete or Destruct all objects owned by the arena.
void CleanupList();
- inline void CacheBlock(Block* block) {
- thread_cache().last_block_used_ = block;
+ inline void CacheSerialArena(SerialArena* serial) {
+ thread_cache().last_serial_arena = serial;
thread_cache().last_lifecycle_id_seen = lifecycle_id_;
// TODO(haberman): evaluate whether we would gain efficiency by getting rid
// of hint_. It's the only write we do to ArenaImpl in the allocation path,
// which will dirty the cache line.
- google::protobuf::internal::Release_Store(&hint_, reinterpret_cast<google::protobuf::internal::AtomicWord>(block));
+
+ hint_.store(serial, std::memory_order_release);
}
- google::protobuf::internal::AtomicWord threads_; // Pointer to a linked list of ThreadInfo.
- google::protobuf::internal::AtomicWord hint_; // Fast thread-local block access
- google::protobuf::internal::AtomicWord space_allocated_; // Sum of sizes of all allocated blocks.
+
+ 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.
- // Returns a block owned by this thread.
- Block* GetBlock(size_t n);
- Block* GetBlockSlow(void* me, Block* my_full_block, size_t n);
- Block* NewBlock(void* me, Block* my_last_block, size_t min_bytes);
- void InitBlock(Block* b, void *me, size_t size);
- static void* AllocFromBlock(Block* b, size_t n);
- ThreadInfo* NewThreadInfo(Block* b);
- ThreadInfo* FindThreadInfo(void* me);
- ThreadInfo* GetThreadInfo(void* me, size_t n);
+ Block* NewBlock(Block* last_block, size_t min_bytes);
+ SerialArena* GetSerialArena();
+ bool GetSerialArenaFast(SerialArena** arena);
+ SerialArena* GetSerialArenaFallback(void* me);
int64 lifecycle_id_; // Unique for each arena. Changes on Reset().
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:
- // kHeaderSize is sizeof(Block), aligned up to the nearest multiple of 8 to
- // protect the invariant that pos is always at a multiple of 8.
- static const size_t kHeaderSize = (sizeof(Block) + 7) & -8;
-#if LANG_CXX11
- static_assert(kHeaderSize % 8 == 0, "kHeaderSize must be a multiple of 8.");
-#endif
+ // 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;
+ static_assert(kBlockHeaderSize % 8 == 0,
+ "kBlockHeaderSize must be a multiple of 8.");
+ static_assert(kSerialArenaSize % 8 == 0,
+ "kSerialArenaSize must be a multiple of 8.");
};
} // 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 c6ff25e8..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>
@@ -67,7 +65,6 @@ using protobuf_unittest::TestOneof2;
using protobuf_unittest::TestEmptyMessage;
namespace protobuf {
-namespace {
class Notifier {
public:
@@ -154,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);
@@ -198,7 +205,6 @@ TEST(ArenaTest, CreateAndNonConstCopy) {
EXPECT_EQ("foo", *s_copy);
}
-#if LANG_CXX11
TEST(ArenaTest, CreateAndMove) {
Arena arena;
string s("foo");
@@ -207,7 +213,6 @@ TEST(ArenaTest, CreateAndMove) {
EXPECT_TRUE(s.empty()); // NOLINT
EXPECT_EQ("foo", *s_move);
}
-#endif
TEST(ArenaTest, CreateWithFourConstructorArguments) {
Arena arena;
@@ -243,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) {}
@@ -264,13 +268,12 @@ 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
// arena allocator; then, allocate an object which will not fit in the
// initial block.
- std::vector<char> arena_block(72);
+ std::vector<char> arena_block(96);
ArenaOptions options;
options.initial_block = &arena_block[0];
options.initial_block_size = arena_block.size();
@@ -443,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);
@@ -469,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());
@@ -490,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);
@@ -601,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);
@@ -899,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) {
@@ -1299,12 +1284,12 @@ TEST(ArenaTest, SpaceAllocated_and_Used) {
options.initial_block_size = 0;
Arena arena_3(options);
EXPECT_EQ(0, arena_3.SpaceUsed());
- ::google::protobuf::Arena::CreateArray<char>(&arena_3, 182);
+ ::google::protobuf::Arena::CreateArray<char>(&arena_3, 160);
EXPECT_EQ(256, arena_3.SpaceAllocated());
- EXPECT_EQ(Align8(182), arena_3.SpaceUsed());
+ EXPECT_EQ(Align8(160), arena_3.SpaceUsed());
::google::protobuf::Arena::CreateArray<char>(&arena_3, 70);
EXPECT_EQ(256 + 512, arena_3.SpaceAllocated());
- EXPECT_EQ(Align8(182) + Align8(70), arena_3.SpaceUsed());
+ EXPECT_EQ(Align8(160) + Align8(70), arena_3.SpaceUsed());
EXPECT_EQ(256 + 512, arena_3.Reset());
}
@@ -1347,6 +1332,13 @@ TEST(ArenaTest, GetArenaShouldReturnNullForNonArenaAllocatedMessages) {
EXPECT_EQ(NULL, Arena::GetArena(const_pointer_to_message));
}
+TEST(ArenaTest, AddCleanup) {
+ ::google::protobuf::Arena arena;
+ for (int i = 0; i < 100; i++) {
+ arena.Own(new int);
+ }
+}
+
TEST(ArenaTest, UnsafeSetAllocatedOnArena) {
::google::protobuf::Arena arena;
TestAllTypes* message = Arena::CreateMessage<TestAllTypes>(&arena);
@@ -1405,13 +1397,20 @@ uint32 ArenaHooksTestUtil::num_reset = 0;
uint32 ArenaHooksTestUtil::num_destruct = 0;
const int ArenaHooksTestUtil::kCookieValue;
+class ArenaOptionsTestFriend {
+ public:
+ static void Set(::google::protobuf::ArenaOptions* options) {
+ options->on_arena_init = ArenaHooksTestUtil::on_init;
+ options->on_arena_allocation = ArenaHooksTestUtil::on_allocation;
+ options->on_arena_reset = ArenaHooksTestUtil::on_reset;
+ options->on_arena_destruction = ArenaHooksTestUtil::on_destruction;
+ }
+};
+
// Test the hooks are correctly called and that the cookie is passed.
TEST(ArenaTest, ArenaHooksSanity) {
::google::protobuf::ArenaOptions options;
- options.on_arena_init = ArenaHooksTestUtil::on_init;
- options.on_arena_allocation = ArenaHooksTestUtil::on_allocation;
- options.on_arena_reset = ArenaHooksTestUtil::on_reset;
- options.on_arena_destruction = ArenaHooksTestUtil::on_destruction;
+ ArenaOptionsTestFriend::Set(&options);
// Scope for defining the arena
{
@@ -1419,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);
@@ -1433,6 +1432,5 @@ TEST(ArenaTest, ArenaHooksSanity) {
}
-} // namespace
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/arenastring.h b/src/google/protobuf/arenastring.h
index c9d045a1..168fc972 100755
--- a/src/google/protobuf/arenastring.h
+++ b/src/google/protobuf/arenastring.h
@@ -51,6 +51,18 @@ namespace google {
namespace protobuf {
namespace internal {
+template <typename T>
+class TaggedPtr {
+ public:
+ void Set(T* p) { ptr_ = reinterpret_cast<uintptr_t>(p); }
+ T* Get() const { return reinterpret_cast<T*>(ptr_); }
+
+ bool IsNull() { return ptr_ == 0; }
+
+ private:
+ uintptr_t ptr_;
+};
+
struct LIBPROTOBUF_EXPORT ArenaStringPtr {
inline void Set(const ::std::string* default_value,
const ::std::string& value, ::google::protobuf::Arena* arena) {
@@ -87,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.
@@ -152,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,
@@ -174,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|.
@@ -241,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) {
@@ -294,6 +352,15 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
return ptr_ == default_value;
}
+ // Internal accessors!!!!
+ void UnsafeSetTaggedPointer(TaggedPtr< ::std::string> value) {
+ ptr_ = value.Get();
+ }
+ // Generated code only! An optimization, in certain cases the generated
+ // code is certain we can obtain a string with no default checks and
+ // tag tests.
+ ::std::string* UnsafeMutablePointer() { return ptr_; }
+
private:
::std::string* ptr_;
@@ -301,10 +368,8 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
void CreateInstance(::google::protobuf::Arena* arena,
const ::std::string* initial_value) {
GOOGLE_DCHECK(initial_value != NULL);
- ptr_ = new ::std::string(*initial_value);
- if (arena != NULL) {
- arena->Own(ptr_);
- }
+ // uses "new ::std::string" when arena is nullptr
+ ptr_ = Arena::Create< ::std::string >(arena, *initial_value);
}
GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
void CreateInstanceNoArena(const ::std::string* initial_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 aa14faf6..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>
@@ -76,10 +73,9 @@ void AddFile(const string& filename, const string& data) {
true));
}
-bool CaptureMetadata(const string& filename, const string& plugin_specific_args,
- const string& meta_file_suffix, CommandLineInterface* cli,
- FileDescriptorProto* file,
- std::vector<ExpectedOutput>* outputs) {
+bool RunProtoCompiler(const string& filename,
+ const string& plugin_specific_args,
+ CommandLineInterface* cli, FileDescriptorProto* file) {
cli->SetInputsAreProtoPathRelative(true);
DescriptorCapturingGenerator capturing_generator(file);
@@ -92,24 +88,7 @@ bool CaptureMetadata(const string& filename, const string& plugin_specific_args,
plugin_specific_args.c_str(), capture_out.c_str(),
filename.c_str()};
- if (cli->Run(5, argv) != 0) {
- return false;
- }
-
- if (outputs != NULL) {
- for (std::vector<ExpectedOutput>::iterator i = outputs->begin();
- i != outputs->end(); ++i) {
- GOOGLE_CHECK_OK(File::GetContents(TestTempDir() + "/" + i->file_path,
- &i->file_content, true));
- if (!DecodeMetadata(
- TestTempDir() + "/" + i->file_path + meta_file_suffix,
- &i->file_info)) {
- return false;
- }
- }
- }
-
- return true;
+ return cli->Run(5, argv) == 0;
}
bool DecodeMetadata(const string& path, GeneratedCodeInfo* info) {
diff --git a/src/google/protobuf/compiler/annotation_test_util.h b/src/google/protobuf/compiler/annotation_test_util.h
index 4598a45a..90bd88b3 100644
--- a/src/google/protobuf/compiler/annotation_test_util.h
+++ b/src/google/protobuf/compiler/annotation_test_util.h
@@ -59,25 +59,20 @@ struct ExpectedOutput {
// directory.
void AddFile(const string& filename, const string& data);
-// Tries to capture a FileDescriptorProto, GeneratedCodeInfo, and output
-// code from the previously added file with name `filename`.
+// Runs proto compiler. Captures proto file structrue in FileDescriptorProto.
+// Files will be generated in TestTempDir() folder. Callers of this
+// function must read generated files themselves.
//
// filename: source .proto file used to generate code.
// plugin_specific_args: command line arguments specific to current generator.
// For Java, this value might be "--java_out=annotate_code:test_temp_dir"
-// meta_file_suffix: suffix of meta files that contain annotations. For Java
-// it is ".pb.meta" because for file Foo.java meta file is Foo.java.pb.meta
// cli: instance of command line interface to run generator. See Java's
// annotation_unittest.cc for an example of how to initialize it.
// file: output parameter, will be set to the descriptor of the proto file
// specified in filename.
-// outputs: output parameter. If not NULL, each ExpectedOutput in the vector
-// should have its file_path set; CaptureMetadata will fill the rest of
-// the fields appropriately.
-bool CaptureMetadata(const string& filename, const string& plugin_specific_args,
- const string& meta_file_suffix, CommandLineInterface* cli,
- FileDescriptorProto* file,
- std::vector<ExpectedOutput>* outputs);
+bool RunProtoCompiler(const string& filename,
+ const string& plugin_specific_args,
+ CommandLineInterface* cli, FileDescriptorProto* file);
bool DecodeMetadata(const string& path, GeneratedCodeInfo* info);
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/code_generator.h b/src/google/protobuf/compiler/code_generator.h
index 4b1d90b8..4c2b3ee1 100644
--- a/src/google/protobuf/compiler/code_generator.h
+++ b/src/google/protobuf/compiler/code_generator.h
@@ -166,7 +166,7 @@ typedef GeneratorContext OutputDirectory;
// "foo=bar,baz,qux=corge"
// parses to the pairs:
// ("foo", "bar"), ("baz", ""), ("qux", "corge")
-void ParseGeneratorParameter(
+LIBPROTOC_EXPORT void ParseGeneratorParameter(
const string&, std::vector<std::pair<string, string> >*);
} // namespace compiler
diff --git a/src/google/protobuf/compiler/command_line_interface.cc b/src/google/protobuf/compiler/command_line_interface.cc
index 1f6d748d..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];
@@ -226,7 +222,7 @@ bool IsInstalledProtoPath(const string& path) {
// Add the paths where google/protobuf/descriptor.proto and other well-known
// type protos are installed.
-void AddDefaultProtoPaths(vector<pair<string, string> >* paths) {
+void AddDefaultProtoPaths(std::vector<std::pair<string, string> >* paths) {
// TODO(xiaofeng): The code currently only checks relative paths of where
// the protoc binary is installed. We probably should make it handle more
// cases than that.
@@ -242,12 +238,12 @@ void AddDefaultProtoPaths(vector<pair<string, string> >* paths) {
path = path.substr(0, pos);
// Check the binary's directory.
if (IsInstalledProtoPath(path)) {
- paths->push_back(pair<string, string>("", path));
+ paths->push_back(std::pair<string, string>("", path));
return;
}
// Check if there is an include subdirectory.
if (IsInstalledProtoPath(path + "/include")) {
- paths->push_back(pair<string, string>("", path + "/include"));
+ paths->push_back(std::pair<string, string>("", path + "/include"));
return;
}
// Check if the upper level directory has an "include" subdirectory.
@@ -257,7 +253,7 @@ void AddDefaultProtoPaths(vector<pair<string, string> >* paths) {
}
path = path.substr(0, pos);
if (IsInstalledProtoPath(path + "/include")) {
- paths->push_back(pair<string, string>("", path + "/include"));
+ paths->push_back(std::pair<string, string>("", path + "/include"));
return;
}
}
@@ -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 3d5b5b8d..50c7b5f3 100644
--- a/src/google/protobuf/compiler/cpp/cpp_enum_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_enum_field.cc
@@ -195,7 +195,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"inline $type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
- " return static_cast< $type$ >($oneof_prefix$$name$_);\n"
+ " return static_cast< $type$ >($field_member$);\n"
" }\n"
" return static_cast< $type$ >($default$);\n"
"}\n"
@@ -209,14 +209,14 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" }\n"
- " $oneof_prefix$$name$_ = value;\n"
+ " $field_member$ = value;\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n");
}
void EnumOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
- printer->Print(variables_, "$oneof_prefix$$name$_ = $default$;\n");
+ printer->Print(variables_, "$field_member$ = $default$;\n");
}
void EnumOneofFieldGenerator::
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 f8e11855..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 {
@@ -67,12 +64,7 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
(*variables)["number"] = SimpleItoa(descriptor->number());
(*variables)["classname"] = ClassName(FieldScope(descriptor), false);
(*variables)["declared_type"] = DeclaredTypeMethodName(descriptor->type());
-
- // non_null_ptr_to_name is usable only if has_$name$ is true. It yields a
- // pointer that will not be NULL. Subclasses of FieldGenerator may set
- // (*variables)["non_null_ptr_to_name"] differently.
- (*variables)["non_null_ptr_to_name"] =
- StrCat("&this->", FieldName(descriptor), "()");
+ (*variables)["field_member"] = FieldName(descriptor) + "_";
(*variables)["tag_size"] = SimpleItoa(
WireFormat::TagSize(descriptor->number(), descriptor->type()));
@@ -81,8 +73,6 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
(*variables)["deprecated_attr"] = descriptor->options().deprecated()
? "GOOGLE_PROTOBUF_DEPRECATED_ATTR " : "";
- (*variables)["cppget"] = "Get";
-
if (HasFieldPresence(descriptor->file())) {
(*variables)["set_hasbit"] =
"set_has_" + FieldName(descriptor) + "();";
@@ -93,10 +83,6 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
(*variables)["clear_hasbit"] = "";
}
- // By default, empty string, so that generic code used for both oneofs and
- // singular fields can be written.
- (*variables)["oneof_prefix"] = "";
-
// These variables are placeholders to pick out the beginning and ends of
// identifiers for annotations (when doing so with existing variables would
// be ambiguous or impossible). They should never be set to anything but the
@@ -108,10 +94,8 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
void SetCommonOneofFieldVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables) {
const string prefix = descriptor->containing_oneof()->name() + "_.";
- (*variables)["oneof_prefix"] = prefix;
(*variables)["oneof_name"] = descriptor->containing_oneof()->name();
- (*variables)["non_null_ptr_to_name"] =
- StrCat(prefix, (*variables)["name"], "_");
+ (*variables)["field_member"] = StrCat(prefix, (*variables)["name"], "_");
}
FieldGenerator::~FieldGenerator() {}
@@ -129,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()) {
@@ -164,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.
@@ -179,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 891e30f6..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;
@@ -184,6 +156,10 @@ class FieldGenerator {
// message's MergeFromCodedStream() method.
virtual void GenerateMergeFromCodedStream(io::Printer* printer) const = 0;
+ // Returns true if this field's "MergeFromCodedStream" code needs the arena
+ // to be defined as a variable.
+ virtual bool MergeFromCodedStreamNeedsArena() const { return false; }
+
// Generate lines to decode this field from a packed value, which will be
// placed inside the message's MergeFromCodedStream() method.
virtual void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer)
@@ -203,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_;
@@ -213,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;
@@ -221,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 52a16835..42525687 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,20 +387,40 @@ 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);
// Define default instances
GenerateSourceDefaultInstance(idx, printer);
- if (UsingImplicitWeakFields(file_, options_)) {
+ if (options_.lite_implicit_weak_fields) {
printer->Print("void $classname$_ReferenceStrong() {}\n", "classname",
message_generators_[idx]->classname_);
}
@@ -411,10 +434,11 @@ 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);
+ printer->Print(
+ "} // namespace protobuf\n} // namespace google\n");
printer->Print(
"\n"
@@ -423,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);
@@ -459,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);
@@ -467,7 +495,7 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
// Define default instances
for (int i = 0; i < message_generators_.size(); i++) {
GenerateSourceDefaultInstance(i, printer);
- if (UsingImplicitWeakFields(file_, options_)) {
+ if (options_.lite_implicit_weak_fields) {
printer->Print("void $classname$_ReferenceStrong() {}\n", "classname",
message_generators_[i]->classname_);
}
@@ -476,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.
@@ -525,6 +569,15 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
"\n"
"// @@protoc_insertion_point(namespace_scope)\n");
}
+
+ printer->Print(
+ "namespace google {\nnamespace protobuf {\n");
+ for (int i = 0; i < message_generators_.size(); i++) {
+ message_generators_[i]->GenerateSourceInProto2Namespace(printer);
+ }
+ printer->Print(
+ "} // namespace protobuf\n} // namespace google\n");
+
printer->Print(
"\n"
"// @@protoc_insertion_point(global_scope)\n");
@@ -544,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;
@@ -553,7 +606,42 @@ class FileGenerator::ForwardDeclarations {
std::map<string, const Descriptor*>& classes() { return classes_; }
std::map<string, const EnumDescriptor*>& enums() { return enums_; }
- void Print(io::Printer* printer, const Options& options) const {
+ void PrintForwardDeclarations(io::Printer* printer,
+ const Options& options) const {
+ PrintNestedDeclarations(printer, options);
+ PrintTopLevelDeclarations(printer, options);
+ }
+
+
+ private:
+ void PrintNestedDeclarations(io::Printer* printer,
+ const Options& options) const {
+ PrintDeclarationsInsideNamespace(printer, options);
+ for (std::map<string, ForwardDeclarations *>::const_iterator
+ it = namespaces_.begin(),
+ end = namespaces_.end();
+ it != end; ++it) {
+ printer->Print("namespace $nsname$ {\n",
+ "nsname", it->first);
+ it->second->PrintNestedDeclarations(printer, options);
+ printer->Print("} // namespace $nsname$\n",
+ "nsname", it->first);
+ }
+ }
+
+ void PrintTopLevelDeclarations(io::Printer* printer,
+ const Options& options) const {
+ PrintDeclarationsOutsideNamespace(printer, options);
+ for (std::map<string, ForwardDeclarations *>::const_iterator
+ it = namespaces_.begin(),
+ end = namespaces_.end();
+ it != end; ++it) {
+ it->second->PrintTopLevelDeclarations(printer, options);
+ }
+ }
+
+ void PrintDeclarationsInsideNamespace(io::Printer* printer,
+ const Options& options) const {
for (std::map<string, const EnumDescriptor *>::const_iterator
it = enums_.begin(),
end = enums_.end();
@@ -584,20 +672,31 @@ class FileGenerator::ForwardDeclarations {
"classname", it->first);
}
}
- for (std::map<string, ForwardDeclarations *>::const_iterator
- it = namespaces_.begin(),
- end = namespaces_.end();
+ }
+
+ void PrintDeclarationsOutsideNamespace(io::Printer* printer,
+ const Options& options) const {
+ if (classes_.size() == 0) return;
+
+ printer->Print(
+ "namespace google {\nnamespace protobuf {\n");
+ for (std::map<string, const Descriptor*>::const_iterator
+ it = classes_.begin(),
+ end = classes_.end();
it != end; ++it) {
- printer->Print("namespace $nsname$ {\n",
- "nsname", it->first);
- it->second->Print(printer, options);
- printer->Print("} // namespace $nsname$\n",
- "nsname", it->first);
+ const Descriptor* d = it->second;
+ printer->Print(
+ "template<> "
+ "$dllexport_decl$"
+ "$classname$* Arena::CreateMaybeMessage<$classname$>"
+ "(Arena*);\n",
+ "classname", QualifiedClassName(d), "dllexport_decl",
+ options.dllexport_decl.empty() ? "" : options.dllexport_decl + " ");
}
+ printer->Print(
+ "} // namespace protobuf\n} // namespace google\n");
}
-
- private:
std::map<string, ForwardDeclarations*> namespaces_;
std::map<string, const Descriptor*> classes_;
std::map<string, const EnumDescriptor*> enums_;
@@ -691,7 +790,6 @@ 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"
// Make sure the file has found its way into the pool. If a descriptor
@@ -699,10 +797,9 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
// 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",
@@ -711,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 ::google::protobuf::internal::once_flag once;\n"
+ " ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);\n"
"}\n"
"\n",
"filename", file_->name(), "metadata",
@@ -728,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
@@ -824,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(
@@ -840,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++) {
@@ -915,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.
@@ -1038,22 +1103,12 @@ 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) {
ForwardDeclarations decls;
FillForwardDeclarations(&decls);
- decls.Print(printer, options_);
+ decls.PrintForwardDeclarations(printer, options_);
}
void FileGenerator::FillForwardDeclarations(ForwardDeclarations* decls) {
@@ -1078,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);
@@ -1089,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);
}
@@ -1126,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(
@@ -1213,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 ? ">" : "\"");
@@ -1251,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_));
@@ -1349,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 e01e5dca..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>
-#include <google/protobuf/stubs/strutil.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
@@ -85,7 +77,6 @@ bool CppGenerator::Generate(const FileDescriptor* file,
// __declspec(dllimport) depending on what is being compiled.
//
Options file_options;
- bool split_source = false;
for (int i = 0; i < options.size(); i++) {
if (options[i].first == "dllexport_decl") {
file_options.dllexport_decl = options[i].second;
@@ -101,28 +92,39 @@ bool CppGenerator::Generate(const FileDescriptor* file,
file_options.enforce_lite = true;
} else if (options[i].first == "lite_implicit_weak_fields") {
file_options.lite_implicit_weak_fields = true;
+ if (!options[i].second.empty()) {
+ file_options.num_cc_files = strto32(options[i].second.c_str(),
+ NULL, 10);
+ }
} else if (options[i].first == "table_driven_parsing") {
file_options.table_driven_parsing = true;
} else if (options[i].first == "table_driven_serialization") {
file_options.table_driven_serialization = true;
- } else if (options[i].first == "split_source") {
- split_source = true;
} else {
*error = "Unknown generator option: " + options[i].first;
return false;
}
}
+ // The safe_boundary_check option controls behavior for Google-internal
+ // protobuf APIs.
+ if (file_options.safe_boundary_check) {
+ *error =
+ "The safe_boundary_check option is not supported outside of Google.";
+ return false;
+ }
+
// -----------------------------------------------------------------
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(
@@ -134,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(
@@ -153,30 +155,44 @@ 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());
}
}
- // Generate cc file.
- if (split_source) {
+ // Generate cc file(s).
+ 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);
}
- for (int i = 0; i < file_generator.NumMessages(); i++) {
+
+ int num_cc_files = file_generator.NumMessages();
+
+ // If we're using implicit weak fields then we allow the user to optionally
+ // specify how many files to generate, not counting the global pb.cc file.
+ // If we have more files than messages, then some files will be generated as
+ // empty placeholders.
+ if (file_options.num_cc_files > 0) {
+ GOOGLE_CHECK_LE(file_generator.NumMessages(), file_options.num_cc_files)
+ << "There must be at least as many numbered .cc files as messages.";
+ num_cc_files = file_options.num_cc_files;
+ }
+ for (int i = 0; i < num_cc_files; i++) {
// TODO(gerbens) Agree on naming scheme.
- 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(), '$');
- file_generator.GenerateSourceForMessage(i, &printer);
+ if (i < file_generator.NumMessages()) {
+ file_generator.GenerateSourceForMessage(i, &printer);
+ }
}
} 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 96950e52..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_repeated() && !field->is_map() &&
- field->containing_oneof() == NULL;
+ !field->is_required() && !field->is_map() &&
+ 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 e0f809c9..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);
@@ -310,6 +288,15 @@ inline bool IsCrossFileMessage(const FieldDescriptor* field) {
field->message_type()->file() != field->file();
}
+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);
@@ -346,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,
@@ -458,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 34a70b12..8c2336af 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 {
@@ -325,6 +323,109 @@ bool IsCrossFileMaybeMap(const FieldDescriptor* field) {
return IsCrossFileMessage(field);
}
+bool IsRequired(const std::vector<const FieldDescriptor*>& v) {
+ return v.front()->is_required();
+}
+
+// Allows chunking repeated fields together and non-repeated fields if the
+// fields share the same has_byte index.
+// TODO(seongkim): use lambda with capture instead of functor.
+class MatchRepeatedAndHasByte {
+ public:
+ MatchRepeatedAndHasByte(const std::vector<int>* has_bit_indices,
+ bool has_field_presence)
+ : has_bit_indices_(*has_bit_indices),
+ has_field_presence_(has_field_presence) {}
+
+ // Returns true if the following conditions are met:
+ // --both fields are repeated fields
+ // --both fields are non-repeated fields with either has_field_presence is
+ // false or have the same has_byte index.
+ bool operator()(const FieldDescriptor* a, const FieldDescriptor* b) const {
+ return a->is_repeated() == b->is_repeated() &&
+ (!has_field_presence_ || a->is_repeated() ||
+ has_bit_indices_[a->index()] / 8 ==
+ has_bit_indices_[b->index()] / 8);
+ }
+
+ private:
+ const std::vector<int>& has_bit_indices_;
+ const bool has_field_presence_;
+};
+
+// Allows chunking required fields separately after chunking with
+// MatchRepeatedAndHasByte.
+class MatchRepeatedAndHasByteAndRequired : public MatchRepeatedAndHasByte {
+ public:
+ MatchRepeatedAndHasByteAndRequired(const std::vector<int>* has_bit_indices,
+ bool has_field_presence)
+ : MatchRepeatedAndHasByte(has_bit_indices, has_field_presence) {}
+
+ bool operator()(const FieldDescriptor* a, const FieldDescriptor* b) const {
+ return MatchRepeatedAndHasByte::operator()(a, b) &&
+ a->is_required() == b->is_required();
+ }
+};
+
+// Allows chunking zero-initializable fields separately after chunking with
+// MatchRepeatedAndHasByte.
+class MatchRepeatedAndHasByteAndZeroInits : public MatchRepeatedAndHasByte {
+ public:
+ MatchRepeatedAndHasByteAndZeroInits(const std::vector<int>* has_bit_indices,
+ bool has_field_presence)
+ : MatchRepeatedAndHasByte(has_bit_indices, has_field_presence) {}
+
+ bool operator()(const FieldDescriptor* a, const FieldDescriptor* b) const {
+ return MatchRepeatedAndHasByte::operator()(a, b) &&
+ CanInitializeByZeroing(a) == CanInitializeByZeroing(b);
+ }
+};
+
+// Collects neighboring fields based on a given criteria (equivalent predicate).
+template <typename Predicate>
+std::vector<std::vector<const FieldDescriptor*> > CollectFields(
+ const std::vector<const FieldDescriptor*>& fields,
+ const Predicate& equivalent) {
+ std::vector<std::vector<const FieldDescriptor*> > chunks;
+ if (fields.empty()) {
+ return chunks;
+ }
+
+ const FieldDescriptor* last_field = fields.front();
+ std::vector<const FieldDescriptor*> chunk;
+ for (int i = 0; i < fields.size(); i++) {
+ if (!equivalent(last_field, fields[i]) && !chunk.empty()) {
+ chunks.push_back(chunk);
+ chunk.clear();
+ }
+ chunk.push_back(fields[i]);
+ last_field = fields[i];
+ }
+ if (!chunk.empty()) {
+ chunks.push_back(chunk);
+ }
+ return chunks;
+}
+
+// Returns a bit mask based on has_bit index of "fields" that are typically on
+// the same chunk. It is used in a group presence check where _has_bits_ is
+// masked to tell if any thing in "fields" is present.
+uint32 GenChunkMask(const std::vector<const FieldDescriptor*>& fields,
+ const std::vector<int>& has_bit_indices) {
+ GOOGLE_CHECK(!fields.empty());
+ int first_index_offset = has_bit_indices[fields.front()->index()] / 32;
+ uint32 chunk_mask = 0;
+ for (int i = 0; i < fields.size(); i++) {
+ const FieldDescriptor* field = fields[i];
+ // "index" defines where in the _has_bits_ the field appears.
+ int index = has_bit_indices[field->index()];
+ GOOGLE_CHECK_EQ(first_index_offset, index / 32);
+ chunk_mask |= static_cast<uint32>(1) << (index % 32);
+ }
+ GOOGLE_CHECK_NE(0, chunk_mask);
+ return chunk_mask;
+}
+
} // anonymous namespace
// ===================================================================
@@ -337,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) {
@@ -389,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_);
@@ -436,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
@@ -482,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);
@@ -534,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),
@@ -542,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) {
@@ -709,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()) {
@@ -748,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::
@@ -816,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 {
@@ -824,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_;
@@ -839,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();
@@ -913,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");
}
@@ -968,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");
@@ -988,10 +967,12 @@ 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";
printer->Print(vars,
"void Swap($classname$* other);\n"
@@ -1001,29 +982,33 @@ GenerateClassDefinition(io::Printer* printer) {
"\n"
"// implements Message ----------------------------------------------\n"
"\n"
- "inline $classname$* New() const$new_final$ { return New(NULL); }\n"
+ "inline $classname$* New() const$new_final$ {\n"
+ " return CreateMaybeMessage<$classname$>(NULL);\n"
+ "}\n"
"\n"
- "$classname$* New(::google::protobuf::Arena* arena) const$new_final$;\n");
+ "$classname$* New(::google::protobuf::Arena* arena) const$new_final$ {\n"
+ " return CreateMaybeMessage<$classname$>(arena);\n"
+ "}\n");
// For instances that derive from Message (rather than MessageLite), some
// methods are virtual and should be marked as final.
string use_final = HasDescriptorMethods(descriptor_->file(), options_) ?
- " 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,
@@ -1032,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 ||
@@ -1040,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.
@@ -1052,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
@@ -1104,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");
}
@@ -1187,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());
}
@@ -1205,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 ? "" :
@@ -1315,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("};");
@@ -1329,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);
@@ -1495,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()) {
@@ -1516,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);
@@ -1560,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()));
@@ -1568,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()));
@@ -1657,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()) {
@@ -1804,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_);
}
@@ -1941,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;
}
}
@@ -1985,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");
}
@@ -2042,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;
}
@@ -2066,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:
@@ -2137,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++) {
@@ -2178,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);
@@ -2196,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");
}
@@ -2383,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) {
@@ -2420,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",
@@ -2440,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"
@@ -2452,112 +2424,110 @@ GenerateStructors(io::Printer* printer) {
}
// Generate the copy constructor.
- printer->Print(
- "$classname$::$classname$(const $classname$& from)\n"
- " : $superclass$()",
- "classname", classname_,
- "superclass", superclass,
- "full_name", descriptor_->full_name());
- printer->Indent();
- printer->Indent();
- printer->Indent();
+ if (UsingImplicitWeakFields(descriptor_->file(), options_)) {
+ // If we are in lite mode and using implicit weak fields, we generate a
+ // one-liner copy constructor that delegates to MergeFrom. This saves some
+ // code size and also cuts down on the complexity of implicit weak fields.
+ // We might eventually want to do this for all lite protos.
+ printer->Print(
+ "$classname$::$classname$(const $classname$& from)\n"
+ " : $classname$() {\n"
+ " MergeFrom(from);\n"
+ "}\n",
+ "classname", classname_);
+ } else {
+ printer->Print(
+ "$classname$::$classname$(const $classname$& from)\n"
+ " : $superclass$()",
+ "classname", classname_,
+ "superclass", superclass,
+ "full_name", descriptor_->full_name());
+ printer->Indent();
+ printer->Indent();
+ printer->Indent();
- printer->Print(
- ",\n_internal_metadata_(NULL)");
+ printer->Print(
+ ",\n_internal_metadata_(NULL)");
- if (HasFieldPresence(descriptor_->file())) {
- printer->Print(",\n_has_bits_(from._has_bits_)");
- }
+ if (HasFieldPresence(descriptor_->file())) {
+ 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];
- std::vector<bool> processed(optimized_order_.size(), false);
- for (int i = 0; i < optimized_order_.size(); ++i) {
- const FieldDescriptor* field = optimized_order_[i];
+ if (!(field->is_repeated() && !(field->is_map()))
+ ) {
+ continue;
+ }
- if (!(field->is_repeated() && !(field->is_map()))
- ) {
- continue;
+ processed[i] = true;
+ printer->Print(",\n$name$_(from.$name$_)",
+ "name", FieldName(field));
}
- processed[i] = true;
- printer->Print(",\n$name$_(from.$name$_)",
- "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_)");
- }
- if (num_weak_fields_ > 0) {
- printer->Print(",\n_weak_field_map_(from._weak_field_map_)");
- }
+ if (IsAnyMessage(descriptor_)) {
+ printer->Print(",\n_any_metadata_(&type_url_, &value_)");
+ }
+ if (num_weak_fields_ > 0) {
+ printer->Print(",\n_weak_field_map_(from._weak_field_map_)");
+ }
- printer->Outdent();
- printer->Outdent();
- printer->Print(" {\n");
+ printer->Outdent();
+ printer->Outdent();
+ printer->Print(" {\n");
- printer->Print(
- "_internal_metadata_.MergeFrom(from._internal_metadata_);\n");
+ printer->Print(
+ "_internal_metadata_.MergeFrom(from._internal_metadata_);\n");
- if (descriptor_->extension_range_count() > 0) {
- printer->Print("_extensions_.MergeFrom(from._extensions_);\n");
- }
+ if (descriptor_->extension_range_count() > 0) {
+ printer->Print("_extensions_.MergeFrom(from._extensions_);\n");
+ }
- GenerateConstructorBody(printer, processed, true);
+ GenerateConstructorBody(printer, processed, true);
- // Copy oneof fields. Oneof field requires oneof case check.
- for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) {
- printer->Print(
- "clear_has_$oneofname$();\n"
- "switch (from.$oneofname$_case()) {\n",
- "oneofname", descriptor_->oneof_decl(i)->name());
- printer->Indent();
- for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
- const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
+ // Copy oneof fields. Oneof field requires oneof case check.
+ for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) {
printer->Print(
- "case k$field_name$: {\n",
- "field_name", UnderscoresToCamelCase(field->name(), true));
+ "clear_has_$oneofname$();\n"
+ "switch (from.$oneofname$_case()) {\n",
+ "oneofname", descriptor_->oneof_decl(i)->name());
printer->Indent();
- field_generators_.get(field).GenerateMergingCode(printer);
+ for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
+ const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
+ printer->Print(
+ "case k$field_name$: {\n",
+ "field_name", UnderscoresToCamelCase(field->name(), true));
+ printer->Indent();
+ field_generators_.get(field).GenerateMergingCode(printer);
+ printer->Print(
+ "break;\n");
+ printer->Outdent();
+ printer->Print(
+ "}\n");
+ }
printer->Print(
- "break;\n");
+ "case $cap_oneof_name$_NOT_SET: {\n"
+ " break;\n"
+ "}\n",
+ "oneof_index",
+ SimpleItoa(descriptor_->oneof_decl(i)->index()),
+ "cap_oneof_name",
+ ToUpper(descriptor_->oneof_decl(i)->name()));
printer->Outdent();
printer->Print(
"}\n");
}
- printer->Print(
- "case $cap_oneof_name$_NOT_SET: {\n"
- " break;\n"
- "}\n",
- "oneof_index",
- SimpleItoa(descriptor_->oneof_decl(i)->index()),
- "cap_oneof_name",
- ToUpper(descriptor_->oneof_decl(i)->name()));
+
printer->Outdent();
printer->Print(
- "}\n");
+ " // @@protoc_insertion_point(copy_constructor:$full_name$)\n"
+ "}\n"
+ "\n",
+ "full_name", descriptor_->full_name());
}
- printer->Outdent();
- printer->Print(
- " // @@protoc_insertion_point(copy_constructor:$full_name$)\n"
- "}\n"
- "\n",
- "full_name", descriptor_->full_name());
-
// Generate the shared constructor code.
GenerateSharedConstructorCode(printer);
@@ -2581,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_) &&
@@ -2605,29 +2573,24 @@ 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",
FileLevelNamespace(descriptor_));
+}
- if (SupportsArenas(descriptor_)) {
- printer->Print(
- "$classname$* $classname$::New(::google::protobuf::Arena* arena) const {\n"
- " return ::google::protobuf::Arena::CreateMessage<$classname$>(arena);\n"
- "}\n",
- "classname", classname_);
- } else {
- printer->Print(
- "$classname$* $classname$::New(::google::protobuf::Arena* arena) const {\n"
- " $classname$* n = new $classname$;\n"
- " if (arena != NULL) {\n"
- " arena->Own(n);\n"
- " }\n"
- " return n;\n"
+void MessageGenerator::GenerateSourceInProto2Namespace(io::Printer* printer) {
+ printer->Print(
+ "template<> "
+ "GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE "
+ "$classname$* Arena::CreateMaybeMessage< $classname$ >(Arena* arena) {\n"
+ " return Arena::$create_func$Internal< $classname$ >(arena);\n"
"}\n",
- "classname", classname_);
- }
+ "classname", QualifiedClassName(descriptor_),
+ "create_func", MessageCreateFunction(descriptor_));
}
// Return the number of bits set in n, a non-negative integer.
@@ -2681,7 +2644,6 @@ GenerateClear(io::Printer* printer) {
printer->Print("_extensions_.Clear();\n");
}
- int last_i = -1;
int unconditional_budget = kMaxUnconditionalPrimitiveBytesClear;
for (int i = 0; i < optimized_order_.size(); i++) {
const FieldDescriptor* field = optimized_order_[i];
@@ -2693,197 +2655,162 @@ GenerateClear(io::Printer* printer) {
unconditional_budget -= EstimateAlignmentSize(field);
}
- for (int i = 0; i < optimized_order_.size(); ) {
- // Detect infinite loops.
- GOOGLE_CHECK_NE(i, last_i);
- last_i = i;
+ std::vector<std::vector<const FieldDescriptor*> > chunks_frag = CollectFields(
+ optimized_order_,
+ MatchRepeatedAndHasByteAndZeroInits(
+ &has_bit_indices_, HasFieldPresence(descriptor_->file())));
+
+ // Merge next non-zero initializable chunk if it has the same has_byte index
+ // and not meeting unconditional clear condition.
+ std::vector<std::vector<const FieldDescriptor*> > chunks;
+ if (!HasFieldPresence(descriptor_->file())) {
+ // Don't bother with merging without has_bit field.
+ chunks = chunks_frag;
+ } else {
+ // Note that only the next chunk is considered for merging.
+ for (int i = 0; i < chunks_frag.size(); i++) {
+ 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() : nullptr;
+ if (CanInitializeByZeroing(field) &&
+ (chunks_frag[i].size() == 1 || unconditional_budget < 0) &&
+ next_field != nullptr &&
+ has_bit_indices_[field->index()] / 8 ==
+ has_bit_indices_[next_field->index()] / 8) {
+ GOOGLE_CHECK(!CanInitializeByZeroing(next_field));
+ // Insert next chunk to the current one and skip next chunk.
+ chunks.back().insert(chunks.back().end(), chunks_frag[i + 1].begin(),
+ chunks_frag[i + 1].end());
+ i++;
+ }
+ }
+ }
+
+ for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) {
+ std::vector<const FieldDescriptor*>& chunk = chunks[chunk_index];
+ GOOGLE_CHECK(!chunk.empty());
// Step 2: Repeated fields don't use _has_bits_; emit code to clear them
// here.
- for (; i < optimized_order_.size(); i++) {
- const FieldDescriptor* field = optimized_order_[i];
- const FieldGenerator& generator = field_generators_.get(field);
+ if (chunk.front()->is_repeated()) {
+ for (int i = 0; i < chunk.size(); i++) {
+ const FieldDescriptor* field = chunk[i];
+ const FieldGenerator& generator = field_generators_.get(field);
- if (!field->is_repeated()) {
- break;
+ generator.GenerateMessageClearingCode(printer);
}
-
- generator.GenerateMessageClearingCode(printer);
+ continue;
}
- // Step 3: Greedily seek runs of fields that can be cleared by
- // memset-to-0.
- int last_chunk = -1;
- int last_chunk_start = -1;
- int last_chunk_end = -1;
- uint32 last_chunk_mask = 0;
-
+ // Step 3: Non-repeated fields that can be cleared by memset-to-0, then
+ // non-repeated, non-zero initializable fields.
+ int last_chunk = HasFieldPresence(descriptor_->file())
+ ? has_bit_indices_[chunk.front()->index()] / 8
+ : 0;
+ int last_chunk_start = 0;
int memset_run_start = -1;
int memset_run_end = -1;
- for (; i < optimized_order_.size(); i++) {
- const FieldDescriptor* field = optimized_order_[i];
-
- if (!CanInitializeByZeroing(field)) {
- break;
- }
- // "index" defines where in the _has_bits_ the field appears.
- // "i" is our loop counter within optimized_order_.
- int index = HasFieldPresence(descriptor_->file()) ?
- has_bit_indices_[field->index()] : 0;
- int chunk = index / 8;
-
- if (last_chunk == -1) {
- last_chunk = chunk;
- last_chunk_start = i;
- } else if (chunk != last_chunk) {
- // Emit the fields for this chunk so far.
- break;
- }
-
- if (memset_run_start == -1) {
- memset_run_start = i;
+ for (int i = 0; i < chunk.size(); i++) {
+ const FieldDescriptor* field = chunk[i];
+ if (CanInitializeByZeroing(field)) {
+ if (memset_run_start == -1) {
+ memset_run_start = i;
+ }
+ memset_run_end = i;
}
-
- memset_run_end = i;
- last_chunk_end = i;
- last_chunk_mask |= static_cast<uint32>(1) << (index % 32);
}
- if (memset_run_start != memset_run_end && unconditional_budget >= 0) {
- // Flush the memset fields.
- goto flush;
- }
+ const bool have_outer_if =
+ HasFieldPresence(descriptor_->file()) && chunk.size() > 1 &&
+ (memset_run_end != chunk.size() - 1 || unconditional_budget < 0);
- // Step 4: Non-repeated, non-zero initializable fields.
- for (; i < optimized_order_.size(); i++) {
- const FieldDescriptor* field = optimized_order_[i];
- if (field->is_repeated() || CanInitializeByZeroing(field)) {
- break;
- }
+ if (have_outer_if) {
+ uint32 last_chunk_mask = GenChunkMask(chunk, has_bit_indices_);
+ const int count = popcnt(last_chunk_mask);
- // "index" defines where in the _has_bits_ the field appears.
- // "i" is our loop counter within optimized_order_.
- int index = HasFieldPresence(descriptor_->file()) ?
- has_bit_indices_[field->index()] : 0;
- int chunk = index / 8;
+ // Check (up to) 8 has_bits at a time if we have more than one field in
+ // this chunk. Due to field layout ordering, we may check
+ // _has_bits_[last_chunk * 8 / 32] multiple times.
+ GOOGLE_DCHECK_LE(2, count);
+ GOOGLE_DCHECK_GE(8, count);
- if (last_chunk == -1) {
- last_chunk = chunk;
- last_chunk_start = i;
- } else if (chunk != last_chunk) {
- // Emit the fields for this chunk so far.
- break;
+ if (cached_has_bit_index != last_chunk / 4) {
+ cached_has_bit_index = last_chunk / 4;
+ printer->Print("cached_has_bits = _has_bits_[$idx$];\n", "idx",
+ SimpleItoa(cached_has_bit_index));
}
-
- last_chunk_end = i;
- last_chunk_mask |= static_cast<uint32>(1) << (index % 32);
+ printer->Print("if (cached_has_bits & $mask$u) {\n", "mask",
+ SimpleItoa(last_chunk_mask));
+ printer->Indent();
}
-flush:
-
- if (last_chunk != -1) {
- GOOGLE_DCHECK_NE(-1, last_chunk_start);
- GOOGLE_DCHECK_NE(-1, last_chunk_end);
- GOOGLE_DCHECK_NE(0, last_chunk_mask);
-
- const int count = popcnt(last_chunk_mask);
- const bool have_outer_if = HasFieldPresence(descriptor_->file()) &&
- (last_chunk_start != last_chunk_end) &&
- (memset_run_start != last_chunk_start ||
- memset_run_end != last_chunk_end ||
- unconditional_budget < 0);
-
- if (have_outer_if) {
- // Check (up to) 8 has_bits at a time if we have more than one field in
- // this chunk. Due to field layout ordering, we may check
- // _has_bits_[last_chunk * 8 / 32] multiple times.
- GOOGLE_DCHECK_LE(2, count);
- GOOGLE_DCHECK_GE(8, count);
+ if (memset_run_start != -1) {
+ if (memset_run_start == memset_run_end) {
+ // For clarity, do not memset a single field.
+ const FieldGenerator& generator =
+ field_generators_.get(chunk[memset_run_start]);
+ generator.GenerateMessageClearingCode(printer);
+ } else {
+ const string first_field_name = FieldName(chunk[memset_run_start]);
+ const string last_field_name = FieldName(chunk[memset_run_end]);
- if (cached_has_bit_index != last_chunk / 4) {
- cached_has_bit_index = last_chunk / 4;
- printer->Print(
- "cached_has_bits = _has_bits_[$idx$];\n",
- "idx", SimpleItoa(cached_has_bit_index));
- }
printer->Print(
- "if (cached_has_bits & $mask$u) {\n",
- "mask", SimpleItoa(last_chunk_mask));
- printer->Indent();
- }
-
- if (memset_run_start != -1) {
- if (memset_run_start == memset_run_end) {
- // For clarity, do not memset a single field.
- const FieldGenerator& generator =
- field_generators_.get(optimized_order_[memset_run_start]);
- generator.GenerateMessageClearingCode(printer);
- } else {
- const string first_field_name =
- FieldName(optimized_order_[memset_run_start]);
- const string last_field_name =
- FieldName(optimized_order_[memset_run_end]);
-
- printer->Print(
"::memset(&$first$_, 0, static_cast<size_t>(\n"
" reinterpret_cast<char*>(&$last$_) -\n"
" reinterpret_cast<char*>(&$first$_)) + sizeof($last$_));\n",
- "first", first_field_name,
- "last", last_field_name);
- }
-
- // Advance last_chunk_start to skip over the fields we zeroed/memset.
- last_chunk_start = memset_run_end + 1;
+ "first", first_field_name, "last", last_field_name);
}
- // Go back and emit clears for each of the fields we processed.
- for (int j = last_chunk_start; j <= last_chunk_end; j++) {
- const FieldDescriptor* field = optimized_order_[j];
- const string fieldname = FieldName(field);
- const FieldGenerator& generator = field_generators_.get(field);
+ // Advance last_chunk_start to skip over the fields we zeroed/memset.
+ last_chunk_start = memset_run_end + 1;
+ }
+
+ // Go back and emit clears for each of the fields we processed.
+ for (int j = last_chunk_start; j < chunk.size(); j++) {
+ const FieldDescriptor* field = chunk[j];
+ const string fieldname = FieldName(field);
+ const FieldGenerator& generator = field_generators_.get(field);
- // It's faster to just overwrite primitive types, but we should only
- // clear strings and messages if they were set.
- //
- // TODO(kenton): Let the CppFieldGenerator decide this somehow.
- bool should_check_bit =
+ // It's faster to just overwrite primitive types, but we should only
+ // clear strings and messages if they were set.
+ //
+ // TODO(kenton): Let the CppFieldGenerator decide this somehow.
+ bool should_check_bit =
field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
field->cpp_type() == FieldDescriptor::CPPTYPE_STRING;
- bool have_enclosing_if = false;
- if (should_check_bit &&
- // If no field presence, then always clear strings/messages as well.
- HasFieldPresence(descriptor_->file())) {
- if (!field->options().weak() &&
- cached_has_bit_index != (has_bit_indices_[field->index()] / 32)) {
- cached_has_bit_index = (has_bit_indices_[field->index()] / 32);
- printer->Print("cached_has_bits = _has_bits_[$new_index$];\n",
- "new_index", SimpleItoa(cached_has_bit_index));
- }
- if (!MaybeGenerateOptionalFieldCondition(printer, field,
- cached_has_bit_index)) {
- printer->Print(
- "if (has_$name$()) {\n",
- "name", fieldname);
- }
- printer->Indent();
- have_enclosing_if = true;
+ bool have_enclosing_if = false;
+ if (should_check_bit &&
+ // If no field presence, then always clear strings/messages as well.
+ HasFieldPresence(descriptor_->file())) {
+ if (!field->options().weak() &&
+ cached_has_bit_index != (has_bit_indices_[field->index()] / 32)) {
+ cached_has_bit_index = (has_bit_indices_[field->index()] / 32);
+ printer->Print("cached_has_bits = _has_bits_[$new_index$];\n",
+ "new_index", SimpleItoa(cached_has_bit_index));
}
-
- generator.GenerateMessageClearingCode(printer);
-
- if (have_enclosing_if) {
- printer->Outdent();
- printer->Print("}\n");
+ if (!MaybeGenerateOptionalFieldCondition(printer, field,
+ cached_has_bit_index)) {
+ printer->Print("if (has_$name$()) {\n", "name", fieldname);
}
+ printer->Indent();
+ have_enclosing_if = true;
}
- if (have_outer_if) {
+ generator.GenerateMessageClearingCode(printer);
+
+ if (have_enclosing_if) {
printer->Outdent();
printer->Print("}\n");
}
}
+
+ if (have_outer_if) {
+ printer->Outdent();
+ printer->Print("}\n");
+ }
}
// Step 4: Unions.
@@ -3033,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");
}
@@ -3349,7 +3275,6 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
"}\n");
return;
}
-
std::vector<const FieldDescriptor*> ordered_fields =
SortFieldsByNumber(descriptor_);
@@ -3379,9 +3304,22 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
return;
}
+ if (SupportsArenas(descriptor_)) {
+ for (int i = 0; i < ordered_fields.size(); i++) {
+ const FieldDescriptor* field = ordered_fields[i];
+ const FieldGenerator& field_generator = field_generators_.get(field);
+ if (field_generator.MergeFromCodedStreamNeedsArena()) {
+ printer->Print(
+ " ::google::protobuf::Arena* arena = GetArenaNoVirtual();\n");
+ break;
+ }
+ }
+ }
+
printer->Print(
- "#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure\n"
- " ::google::protobuf::uint32 tag;\n");
+ "#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto "
+ "failure\n"
+ " ::google::protobuf::uint32 tag;\n");
if (!UseUnknownFieldSet(descriptor_->file(), options_)) {
printer->Print(
@@ -3402,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
@@ -3421,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++) {
@@ -3432,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",
@@ -3531,7 +3482,6 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
printer->Outdent();
printer->Print("}\n\n");
}
-
printer->Print("default: {\n");
printer->Indent();
}
@@ -3922,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();) {
@@ -3934,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,
@@ -3951,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);
}
}
@@ -4013,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";
}
@@ -4027,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;
}
@@ -4141,28 +4091,30 @@ GenerateByteSize(io::Printer* printer) {
}
}
- int last_i = -1;
- for (int i = 0; i < optimized_order_.size(); ) {
- // Detect infinite loops.
- GOOGLE_CHECK_NE(i, last_i);
- last_i = i;
+ std::vector<std::vector<const FieldDescriptor*> > chunks = CollectFields(
+ optimized_order_,
+ MatchRepeatedAndHasByteAndRequired(
+ &has_bit_indices_, HasFieldPresence(descriptor_->file())));
- // Skip required fields.
- for (; i < optimized_order_.size() &&
- optimized_order_[i]->is_required(); i++) {
- }
+ // Remove chunks with required fields.
+ chunks.erase(std::remove_if(chunks.begin(), chunks.end(), IsRequired),
+ chunks.end());
+
+ for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) {
+ const std::vector<const FieldDescriptor*>& chunk = chunks[chunk_index];
+ GOOGLE_CHECK(!chunk.empty());
// Handle repeated fields.
- for (; i < optimized_order_.size(); i++) {
- const FieldDescriptor* field = optimized_order_[i];
- if (!field->is_repeated()) {
- break;
- }
+ if (chunk.front()->is_repeated()) {
+ for (int i = 0; i < chunk.size(); i++) {
+ const FieldDescriptor* field = chunk[i];
- PrintFieldComment(printer, field);
- const FieldGenerator& generator = field_generators_.get(field);
- generator.GenerateByteSize(printer);
- printer->Print("\n");
+ PrintFieldComment(printer, field);
+ const FieldGenerator& generator = field_generators_.get(field);
+ generator.GenerateByteSize(printer);
+ printer->Print("\n");
+ }
+ continue;
}
// Handle optional (non-repeated/oneof) fields.
@@ -4174,92 +4126,62 @@ GenerateByteSize(io::Printer* printer) {
// descriptor_->field(8), descriptor_->field(9), ...
// descriptor_->field(15),
// etc.
- int last_chunk = -1;
- int last_chunk_start = -1;
- int last_chunk_end = -1;
- uint32 last_chunk_mask = 0;
- for (; i < optimized_order_.size(); i++) {
- const FieldDescriptor* field = optimized_order_[i];
- if (field->is_repeated() || field->is_required()) {
- break;
- }
+ int last_chunk = HasFieldPresence(descriptor_->file())
+ ? has_bit_indices_[chunk.front()->index()] / 8
+ : 0;
+ GOOGLE_DCHECK_NE(-1, last_chunk);
- // "index" defines where in the _has_bits_ the field appears.
- // "i" is our loop counter within optimized_order_.
- int index = HasFieldPresence(descriptor_->file()) ?
- has_bit_indices_[field->index()] : 0;
- int chunk = index / 8;
+ const bool have_outer_if =
+ HasFieldPresence(descriptor_->file()) && chunk.size() > 1;
- if (last_chunk == -1) {
- last_chunk = chunk;
- last_chunk_start = i;
- } else if (chunk != last_chunk) {
- // Emit the fields for this chunk so far.
- break;
- }
+ if (have_outer_if) {
+ uint32 last_chunk_mask = GenChunkMask(chunk, has_bit_indices_);
+ const int count = popcnt(last_chunk_mask);
- last_chunk_end = i;
- last_chunk_mask |= static_cast<uint32>(1) << (index % 32);
- }
+ // Check (up to) 8 has_bits at a time if we have more than one field in
+ // this chunk. Due to field layout ordering, we may check
+ // _has_bits_[last_chunk * 8 / 32] multiple times.
+ GOOGLE_DCHECK_LE(2, count);
+ GOOGLE_DCHECK_GE(8, count);
- if (last_chunk != -1) {
- GOOGLE_DCHECK_NE(-1, last_chunk_start);
- GOOGLE_DCHECK_NE(-1, last_chunk_end);
- GOOGLE_DCHECK_NE(0, last_chunk_mask);
+ printer->Print("if (_has_bits_[$index$ / 32] & $mask$u) {\n", "index",
+ SimpleItoa(last_chunk * 8), "mask",
+ SimpleItoa(last_chunk_mask));
+ printer->Indent();
+ }
- const int count = popcnt(last_chunk_mask);
- const bool have_outer_if = HasFieldPresence(descriptor_->file()) &&
- (last_chunk_start != last_chunk_end);
+ // Go back and emit checks for each of the fields we processed.
+ for (int j = 0; j < chunk.size(); j++) {
+ const FieldDescriptor* field = chunk[j];
+ const FieldGenerator& generator = field_generators_.get(field);
- if (have_outer_if) {
- // Check (up to) 8 has_bits at a time if we have more than one field in
- // this chunk. Due to field layout ordering, we may check
- // _has_bits_[last_chunk * 8 / 32] multiple times.
- GOOGLE_DCHECK_LE(2, count);
- GOOGLE_DCHECK_GE(8, count);
+ PrintFieldComment(printer, field);
- printer->Print(
- "if (_has_bits_[$index$ / 32] & $mask$u) {\n",
- "index", SimpleItoa(last_chunk * 8),
- "mask", SimpleItoa(last_chunk_mask));
+ bool have_enclosing_if = false;
+ if (HasFieldPresence(descriptor_->file())) {
+ printer->Print("if (has_$name$()) {\n", "name", FieldName(field));
printer->Indent();
+ have_enclosing_if = true;
+ } else {
+ // Without field presence: field is serialized only if it has a
+ // non-default value.
+ have_enclosing_if =
+ EmitFieldNonDefaultCondition(printer, "this->", field);
}
- // Go back and emit checks for each of the fields we processed.
- for (int j = last_chunk_start; j <= last_chunk_end; j++) {
- const FieldDescriptor* field = optimized_order_[j];
- const FieldGenerator& generator = field_generators_.get(field);
-
- PrintFieldComment(printer, field);
-
- bool have_enclosing_if = false;
- if (HasFieldPresence(descriptor_->file())) {
- printer->Print(
- "if (has_$name$()) {\n",
- "name", FieldName(field));
- printer->Indent();
- have_enclosing_if = true;
- } else {
- // Without field presence: field is serialized only if it has a
- // non-default value.
- have_enclosing_if = EmitFieldNonDefaultCondition(
- printer, "this->", field);
- }
-
- generator.GenerateByteSize(printer);
+ generator.GenerateByteSize(printer);
- if (have_enclosing_if) {
- printer->Outdent();
- printer->Print(
+ if (have_enclosing_if) {
+ printer->Outdent();
+ printer->Print(
"}\n"
"\n");
- }
}
+ }
- if (have_outer_if) {
- printer->Outdent();
- printer->Print("}\n");
- }
+ if (have_outer_if) {
+ printer->Outdent();
+ printer->Print("}\n");
}
}
@@ -4300,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");
@@ -4359,10 +4282,17 @@ GenerateIsInitialized(io::Printer* printer) {
!ShouldIgnoreRequiredFieldCheck(field, options_) &&
scc_analyzer_->HasRequiredFields(field->message_type())) {
if (field->is_repeated()) {
- printer->Print(
- "if (!::google::protobuf::internal::AllAreInitialized(this->$name$()))"
- " return false;\n",
- "name", FieldName(field));
+ if (IsImplicitWeakField(field, options_, scc_analyzer_)) {
+ printer->Print(
+ "if (!::google::protobuf::internal::AllAreInitializedWeak(this->$name$_))"
+ " return false;\n",
+ "name", FieldName(field));
+ } else {
+ printer->Print(
+ "if (!::google::protobuf::internal::AllAreInitialized(this->$name$()))"
+ " return false;\n",
+ "name", FieldName(field));
+ }
} else if (field->options().weak()) {
continue;
} else {
diff --git a/src/google/protobuf/compiler/cpp/cpp_message.h b/src/google/protobuf/compiler/cpp/cpp_message.h
index 0387f0ca..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
@@ -106,12 +100,12 @@ class MessageGenerator {
// Generate all non-inline methods for this class.
void GenerateClassMethods(io::Printer* printer);
+ // Generate source file code that should go outside any namespace.
+ void GenerateSourceInProto2Namespace(io::Printer* printer);
+
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
@@ -219,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 fe60a283..c1e15c52 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_message_field.cc
@@ -70,21 +70,18 @@ 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"] =
- ReferenceFunctionName(descriptor->message_type());
- if (descriptor->options().weak() || !descriptor->containing_oneof()) {
- (*variables)["non_null_ptr_to_name"] =
- StrCat("this->", (*variables)["name"], "_");
- }
+ implicit_weak
+ ? (" " + ReferenceFunctionName(descriptor->message_type()) + "();\n")
+ : "";
(*variables)["stream_writer"] =
(*variables)["declared_type"] +
(HasFastArraySerialization(descriptor->message_type()->file(), options)
@@ -96,14 +93,6 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
SafeFunctionName(descriptor->containing_type(),
descriptor, "release_");
(*variables)["full_name"] = descriptor->full_name();
- if (options.proto_h && IsFieldDependent(descriptor)) {
- (*variables)["dependent_type"] = "T::" + DependentTypeName(descriptor);
- (*variables)["dependent_typename"] =
- "typename T::" + DependentTypeName(descriptor);
- } else {
- (*variables)["dependent_type"] = FieldMessageTypeName(descriptor);
- (*variables)["dependent_typename"] = FieldMessageTypeName(descriptor);
- }
}
} // namespace
@@ -111,12 +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),
- 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_);
}
MessageFieldGenerator::~MessageFieldGenerator() {}
@@ -124,38 +114,30 @@ 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");
}
}
void MessageFieldGenerator::
-GenerateDependentAccessorDeclarations(io::Printer* printer) const {
- if (!dependent_field_) {
- return;
- }
- printer->Print(variables_,
- "$deprecated_attr$$type$* ${$mutable_$name$$}$();\n");
- printer->Annotate("{", "}", descriptor_);
-}
-
-void MessageFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
- if (SupportsArenas(descriptor_) && !implicit_weak_field_) {
- printer->Print(variables_,
- "private:\n"
- "void _slow_mutable_$name$();\n"
- "public:\n");
- }
if (implicit_weak_field_) {
// These private accessors are used by MergeFrom and
// MergePartialFromCodedStream, and their purpose is to provide access to
// the field without creating a strong dependency on the message type.
printer->Print(variables_,
"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_,
@@ -163,11 +145,9 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Annotate("name", descriptor_);
printer->Print(variables_, "$deprecated_attr$$type$* $release_name$();\n");
printer->Annotate("release_name", descriptor_);
- if (!dependent_field_) {
- printer->Print(variables_,
- "$deprecated_attr$$type$* ${$mutable_$name$$}$();\n");
- printer->Annotate("{", "}", descriptor_);
- }
+ printer->Print(variables_,
+ "$deprecated_attr$$type$* ${$mutable_$name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"$deprecated_attr$void ${$set_allocated_$name$$}$"
"($type$* $name$);\n");
@@ -189,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"
@@ -212,26 +192,13 @@ 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"
- " return $name$_;\n");
- } else {
- printer->Print(variables_,
- "void $classname$::_slow_mutable_$name$() {\n");
- if (SupportsArenas(descriptor_->message_type())) {
- printer->Print(variables_,
- " $name$_ = ::google::protobuf::Arena::CreateMessage< $type$ >(\n"
- " GetArenaNoVirtual());\n");
- } else {
- printer->Print(variables_,
- " $name$_ = ::google::protobuf::Arena::Create< $type$ >(\n"
- " GetArenaNoVirtual());\n");
- }
+ " return $name$_;\n"
+ "}\n");
}
- printer->Print(variables_,
- "}\n");
printer->Print(variables_,
"void $classname$::unsafe_arena_set_allocated_$name$(\n"
@@ -252,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"
@@ -268,118 +235,43 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions(
}
void MessageFieldGenerator::
-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["casted_reference"] =
- ReinterpretCast(variables["dependent_typename"] + "*&",
- variables["this_message"] + variables["name"] + "_",
- implicit_weak_field_);
- if (!variables["set_hasbit"].empty()) {
- variables["set_hasbit"] =
- variables["this_message"] + variables["set_hasbit"];
- }
- if (!variables["clear_hasbit"].empty()) {
- variables["clear_hasbit"] =
- variables["this_message"] + variables["clear_hasbit"];
- }
-
- if (SupportsArenas(descriptor_)) {
- printer->Print(variables,
- "template <class T>\n"
- "inline $type$* $dependent_classname$::mutable_$name$() {\n");
- if (implicit_weak_field_) {
- printer->Print(variables, " $type_reference_function$();\n");
- }
- printer->Print(variables,
- " $set_hasbit$\n"
- " $dependent_typename$*& $name$_ = $casted_reference$;\n"
- " if ($name$_ == NULL) {\n");
- if (implicit_weak_field_) {
- printer->Print(variables,
- " $name$_ = reinterpret_cast<$dependent_typename$*>(\n"
- " reinterpret_cast<const google::protobuf::MessageLite*>(\n"
- " &$type_default_instance$)->New(\n"
- " $this_message$GetArenaNoVirtual()));\n");
- } else {
- printer->Print(variables,
- " $this_message$_slow_mutable_$name$();\n");
- }
- printer->Print(variables,
- " }\n"
- " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
- " return $name$_;\n"
- "}\n");
- } else {
- printer->Print(variables,
- "template <class T>\n"
- "inline $type$* $dependent_classname$::mutable_$name$() {\n"
- " $set_hasbit$\n"
- " $dependent_typename$*& $name$_ = $casted_reference$;\n"
- " if ($name$_ == NULL) {\n"
- " $name$_ = new $dependent_typename$;\n"
- " }\n"
- " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
- " return $name$_;\n"
- "}\n");
- }
-}
-
-void MessageFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
- std::map<string, string> variables(variables_);
- variables["const_member"] = ReinterpretCast(
- "const " + variables["type"] + "*", variables["name"] + "_",
- implicit_weak_field_);
- printer->Print(variables,
- "inline const $type$& $classname$::$name$() const {\n");
- if (implicit_weak_field_) {
- printer->Print(variables, " $type_reference_function$();\n");
+ if (!implicit_weak_field_) {
+ printer->Print(variables_,
+ "inline const $type$& $classname$::_internal_$name$() const {\n"
+ " return *$field_member$;\n"
+ "}\n");
}
- printer->Print(variables,
- " const $type$* p = $const_member$;\n"
+ printer->Print(variables_,
+ "inline const $type$& $classname$::$name$() const {\n"
+ " const $type$* p = $casted_member$;\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return p != NULL ? *p : *reinterpret_cast<const $type$*>(\n"
" &$type_default_instance$);\n"
"}\n");
- printer->Print(variables,
+ printer->Print(variables_,
"inline $type$* $classname$::$release_name$() {\n"
- " // @@protoc_insertion_point(field_release:$full_name$)\n");
- if (implicit_weak_field_) {
- printer->Print(variables, " $type_reference_function$();\n");
- }
- printer->Print(variables,
+ " // @@protoc_insertion_point(field_release:$full_name$)\n"
+ "$type_reference_function$"
" $clear_hasbit$\n"
" $type$* temp = $casted_member$;\n");
if (SupportsArenas(descriptor_)) {
- printer->Print(variables,
+ 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,
+ printer->Print(variables_,
" $name$_ = NULL;\n"
" return temp;\n"
"}\n");
if (SupportsArenas(descriptor_)) {
- printer->Print(variables,
+ printer->Print(variables_,
"inline $type$* $classname$::unsafe_arena_release_$name$() {\n"
- " // @@protoc_insertion_point("
- "field_unsafe_arena_release:$full_name$)\n");
- if (implicit_weak_field_) {
- printer->Print(variables, " $type_reference_function$();\n");
- }
- printer->Print(variables,
+ " // @@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
+ "$type_reference_function$"
" $clear_hasbit$\n"
" $type$* temp = $casted_member$;\n"
" $name$_ = NULL;\n"
@@ -387,71 +279,57 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"}\n");
}
- if (!dependent_field_) {
- if (SupportsArenas(descriptor_)) {
- printer->Print(variables,
- "inline $type$* $classname$::mutable_$name$() {\n"
- " $set_hasbit$\n"
- " if ($name$_ == NULL) {\n");
- if (implicit_weak_field_) {
- printer->Print(variables,
- " _internal_mutable_$name$();\n");
- } else {
- printer->Print(variables,
- " _slow_mutable_$name$();\n");
- }
- printer->Print(variables,
- " }\n"
- " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
- " return $casted_member$;\n"
- "}\n");
- } else {
- printer->Print(variables,
- "inline $type$* $classname$::mutable_$name$() {\n"
- " $set_hasbit$\n"
- " if ($name$_ == NULL) {\n"
- " $name$_ = new $type$;\n"
- " }\n"
- " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
- " return $casted_member$;\n"
- "}\n");
- }
+ printer->Print(variables_,
+ "inline $type$* $classname$::mutable_$name$() {\n"
+ " $set_hasbit$\n"
+ " if ($name$_ == NULL) {\n"
+ " auto* p = CreateMaybeMessage<$type$>(GetArenaNoVirtual());\n");
+ if (implicit_weak_field_) {
+ printer->Print(variables_,
+ " $name$_ = reinterpret_cast<::google::protobuf::MessageLite*>(p);\n");
+ } else {
+ printer->Print(variables_,
+ " $name$_ = p;\n");
}
-
+ printer->Print(variables_,
+ " }\n"
+ " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
+ " return $casted_member$;\n"
+ "}\n");
// We handle the most common case inline, and delegate less common cases to
// the slow fallback function.
- printer->Print(variables,
+ printer->Print(variables_,
"inline void $classname$::set_allocated_$name$($type$* $name$) {\n"
" ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();\n");
- printer->Print(variables,
+ printer->Print(variables_,
" if (message_arena == NULL) {\n");
if (IsCrossFileMessage(descriptor_)) {
- printer->Print(variables,
+ printer->Print(variables_,
" delete reinterpret_cast< ::google::protobuf::MessageLite*>($name$_);\n");
} else {
- printer->Print(variables,
+ printer->Print(variables_,
" delete $name$_;\n");
}
- printer->Print(variables,
+ printer->Print(variables_,
" }\n"
" if ($name$) {\n");
if (SupportsArenas(descriptor_->message_type()) &&
IsCrossFileMessage(descriptor_)) {
// We have to read the arena through the virtual method, because the type
// isn't defined in this file.
- printer->Print(variables,
+ 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,
+ printer->Print(variables_,
" ::google::protobuf::Arena* submessage_arena = NULL;\n");
} else {
- printer->Print(variables,
+ printer->Print(variables_,
" ::google::protobuf::Arena* submessage_arena =\n"
" ::google::protobuf::Arena::GetArena($name$);\n");
}
- printer->Print(variables,
+ printer->Print(variables_,
" if (message_arena != submessage_arena) {\n"
" $name$ = ::google::protobuf::internal::GetOwnedMessage(\n"
" message_arena, $name$, submessage_arena);\n"
@@ -461,13 +339,13 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" $clear_hasbit$\n"
" }\n");
if (implicit_weak_field_) {
- printer->Print(variables,
+ printer->Print(variables_,
" $name$_ = reinterpret_cast<MessageLite*>($name$);\n");
} else {
- printer->Print(variables,
+ printer->Print(variables_,
" $name$_ = $name$;\n");
}
- printer->Print(variables,
+ printer->Print(variables_,
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n");
}
@@ -540,34 +418,12 @@ GenerateConstructorCode(io::Printer* printer) const {
void MessageFieldGenerator::
GenerateCopyConstructorCode(io::Printer* printer) const {
- // For non-Arena enabled messages, everything always goes on the heap.
- //
- // For Arena enabled messages, the logic is a bit more convoluted.
- //
- // In the copy constructor, we call InternalMetadataWithArena::MergeFrom,
- // which does *not* copy the Arena pointer. In the generated MergeFrom
- // (see MessageFieldGenerator::GenerateMergingCode), we:
- // -> copy the has bits (but this is done in bulk by a memcpy in the copy
- // constructor)
- // -> check whether the destination field pointer is NULL (it will be, since
- // we're initializing it and would have called SharedCtor) and if so:
- // -> call _slow_mutable_$name$(), which calls either
- // ::google::protobuf::Arena::CreateMessage<>(GetArenaNoVirtual()), or
- // ::google::protobuf::Arena::Create<>(GetArenaNoVirtual())
- //
- // At this point, GetArenaNoVirtual returns NULL since the Arena pointer
- // wasn't copied, so both of these methods allocate the submessage on the
- // heap.
-
- string new_expression = (implicit_weak_field_ ? "from.$name$_->New()"
- : "new $type$(*from.$name$_)");
- string output =
- "if (from.has_$name$()) {\n"
- " $name$_ = " + new_expression + ";\n"
- "} else {\n"
- " $name$_ = NULL;\n"
- "}\n";
- printer->Print(variables_, output.c_str());
+ printer->Print(variables_,
+ "if (from.has_$name$()) {\n"
+ " $name$_ = new $type$(*from.$name$_);\n"
+ "} else {\n"
+ " $name$_ = NULL;\n"
+ "}\n");
}
void MessageFieldGenerator::
@@ -591,7 +447,7 @@ void MessageFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
printer->Print(variables_,
"::google::protobuf::internal::WireFormatLite::Write$stream_writer$(\n"
- " $number$, *$non_null_ptr_to_name$, output);\n");
+ " $number$, this->_internal_$name$(), output);\n");
}
void MessageFieldGenerator::
@@ -599,7 +455,7 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
printer->Print(variables_,
"target = ::google::protobuf::internal::WireFormatLite::\n"
" InternalWrite$declared_type$ToArray(\n"
- " $number$, *$non_null_ptr_to_name$, deterministic, target);\n");
+ " $number$, this->_internal_$name$(), deterministic, target);\n");
}
void MessageFieldGenerator::
@@ -607,16 +463,15 @@ GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"total_size += $tag_size$ +\n"
" ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"
- " *$non_null_ptr_to_name$);\n");
+ " *$field_member$);\n");
}
// ===================================================================
-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_);
}
@@ -635,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");
@@ -650,57 +505,33 @@ void MessageOneofFieldGenerator::GenerateNonInlineAccessorDefinitions(
" message_arena, $name$, submessage_arena);\n"
" }\n"
" set_has_$name$();\n"
- " $oneof_prefix$$name$_ = $name$;\n"
+ " $field_member$ = $name$;\n"
" }\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n");
}
void MessageOneofFieldGenerator::
-GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const {
- // For the CRTP base class, all mutation methods are dependent, and so
- // they must be in the header.
- if (!dependent_base_) {
- return;
- }
- std::map<string, string> variables(variables_);
- variables["dependent_classname"] =
- DependentBaseClassTemplateName(descriptor_->containing_type()) + "<T>";
- variables["this_message"] = "reinterpret_cast<T*>(this)->";
- // Const message access is needed for the dependent getter.
- variables["this_const_message"] = "reinterpret_cast<const T*>(this)->";
- variables["tmpl"] = "template <class T>\n";
- variables["field_member"] = variables["this_message"] +
- variables["oneof_prefix"] + variables["name"] +
- "_";
- InternalGenerateInlineAccessorDefinitions(variables, printer);
-}
-
-void MessageOneofFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
-
- std::map<string, string> variables(variables_);
- variables["dependent_classname"] = variables["classname"];
- variables["this_message"] = "";
- variables["this_const_message"] = "";
- variables["tmpl"] = "";
- variables["field_member"] =
- variables["oneof_prefix"] + variables["name"] + "_";
- variables["dependent_type"] = variables["type"];
-
- printer->Print(variables,
+ if (!implicit_weak_field_) {
+ printer->Print(variables_,
+ "inline const $type$& $classname$::_internal_$name$() const {\n"
+ " return *$field_member$;\n"
+ "}\n");
+ }
+ printer->Print(variables_,
"inline $type$* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
- " if ($this_message$has_$name$()) {\n"
- " $this_message$clear_has_$oneof_name$();\n"
+ " if (has_$name$()) {\n"
+ " clear_has_$oneof_name$();\n"
" $type$* temp = $field_member$;\n");
if (SupportsArenas(descriptor_)) {
- printer->Print(variables,
- " if ($this_message$GetArenaNoVirtual() != NULL) {\n"
- " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);\n"
+ printer->Print(variables_,
+ " if (GetArenaNoVirtual() != NULL) {\n"
+ " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);\n"
" }\n");
}
- printer->Print(variables,
+ printer->Print(variables_,
" $field_member$ = NULL;\n"
" return temp;\n"
" } else {\n"
@@ -708,23 +539,23 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" }\n"
"}\n");
- printer->Print(variables,
+ printer->Print(variables_,
"inline const $type$& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
- " return $this_const_message$has_$name$()\n"
- " ? *$this_const_message$$oneof_prefix$$name$_\n"
+ " return has_$name$()\n"
+ " ? *$field_member$\n"
" : *reinterpret_cast< $type$*>(&$type_default_instance$);\n"
"}\n");
if (SupportsArenas(descriptor_)) {
- printer->Print(variables,
- "inline $type$* $dependent_classname$::unsafe_arena_release_$name$() {\n"
+ printer->Print(variables_,
+ "inline $type$* $classname$::unsafe_arena_release_$name$() {\n"
" // @@protoc_insertion_point(field_unsafe_arena_release"
":$full_name$)\n"
- " if ($this_message$has_$name$()) {\n"
- " $this_message$clear_has_$oneof_name$();\n"
- " $type$* temp = $this_message$$oneof_prefix$$name$_;\n"
- " $this_message$$oneof_prefix$$name$_ = NULL;\n"
+ " if (has_$name$()) {\n"
+ " clear_has_$oneof_name$();\n"
+ " $type$* temp = $field_member$;\n"
+ " $field_member$ = NULL;\n"
" return temp;\n"
" } else {\n"
" return NULL;\n"
@@ -738,58 +569,24 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" clear_$oneof_name$();\n"
" if ($name$) {\n"
" set_has_$name$();\n"
- " $oneof_prefix$$name$_ = $name$;\n"
+ " $field_member$ = $name$;\n"
" }\n"
" // @@protoc_insertion_point(field_unsafe_arena_set_allocated:"
"$full_name$)\n"
"}\n");
}
- if (dependent_base_) {
- return;
- }
-
- InternalGenerateInlineAccessorDefinitions(variables, printer);
-}
-
-void MessageOneofFieldGenerator::InternalGenerateInlineAccessorDefinitions(
- const std::map<string, string>& variables, io::Printer* printer) const {
- if (SupportsArenas(descriptor_)) {
- printer->Print(variables,
- "$tmpl$"
- "inline $type$* $dependent_classname$::mutable_$name$() {\n"
- " if (!$this_message$has_$name$()) {\n"
- " $this_message$clear_$oneof_name$();\n"
- " $this_message$set_has_$name$();\n");
- if (SupportsArenas(descriptor_->message_type())) {
- printer->Print(variables,
- " $field_member$ = \n"
- " ::google::protobuf::Arena::CreateMessage< $dependent_typename$ >(\n"
- " $this_message$GetArenaNoVirtual());\n");
- } else {
- printer->Print(variables,
- " $this_message$$oneof_prefix$$name$_ = \n"
- " ::google::protobuf::Arena::Create< $dependent_typename$ >(\n"
- " $this_message$GetArenaNoVirtual());\n");
- }
- printer->Print(variables,
- " }\n"
- " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
- " return $field_member$;\n"
- "}\n");
- } else {
- printer->Print(variables,
- "$tmpl$"
- "inline $type$* $dependent_classname$::mutable_$name$() {\n"
- " if (!$this_message$has_$name$()) {\n"
- " $this_message$clear_$oneof_name$();\n"
- " $this_message$set_has_$name$();\n"
- " $field_member$ = new $dependent_typename$;\n"
- " }\n"
- " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
- " return $field_member$;\n"
- "}\n");
- }
+ printer->Print(variables_,
+ "inline $type$* $classname$::mutable_$name$() {\n"
+ " if (!has_$name$()) {\n"
+ " clear_$oneof_name$();\n"
+ " set_has_$name$();\n"
+ " $field_member$ = CreateMaybeMessage< $type$ >(\n"
+ " GetArenaNoVirtual());\n"
+ " }\n"
+ " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
+ " return $field_member$;\n"
+ "}\n");
}
void MessageOneofFieldGenerator::
@@ -797,11 +594,11 @@ GenerateClearingCode(io::Printer* printer) const {
if (SupportsArenas(descriptor_)) {
printer->Print(variables_,
"if (GetArenaNoVirtual() == NULL) {\n"
- " delete $oneof_prefix$$name$_;\n"
+ " delete $field_member$;\n"
"}\n");
} else {
printer->Print(variables_,
- "delete $oneof_prefix$$name$_;\n");
+ "delete $field_member$;\n");
}
}
@@ -830,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)),
- dependent_getter_(dependent_field_ && options.safe_boundary_check) {
- SetMessageVariables(descriptor, &variables_, options);
+ implicit_weak_field_(
+ IsImplicitWeakField(descriptor, options, scc_analyzer)) {
+ SetMessageVariables(descriptor, options, implicit_weak_field_, &variables_);
}
RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() {}
@@ -847,164 +645,103 @@ GeneratePrivateMembers(io::Printer* printer) const {
}
void RepeatedMessageFieldGenerator::
-InternalGenerateTypeDependentAccessorDeclarations(io::Printer* printer) const {
+GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
"$deprecated_attr$$type$* ${$mutable_$name$$}$(int index);\n");
printer->Annotate("{", "}", descriptor_);
- printer->Print(variables_, "$deprecated_attr$$type$* ${$add_$name$$}$();\n");
- printer->Annotate("{", "}", descriptor_);
- if (dependent_getter_) {
- printer->Print(variables_,
- "$deprecated_attr$const ::google::protobuf::RepeatedPtrField< $type$ >&\n"
- " $name$() const;\n");
- printer->Annotate("name", descriptor_);
- }
printer->Print(variables_,
"$deprecated_attr$::google::protobuf::RepeatedPtrField< $type$ >*\n"
" ${$mutable_$name$$}$();\n");
printer->Annotate("{", "}", descriptor_);
-}
-
-void RepeatedMessageFieldGenerator::
-GenerateDependentAccessorDeclarations(io::Printer* printer) const {
- if (dependent_getter_) {
- printer->Print(variables_,
- "$deprecated_attr$const $type$& $name$(int index) const;\n");
- printer->Annotate("name", descriptor_);
- }
- if (dependent_field_) {
- InternalGenerateTypeDependentAccessorDeclarations(printer);
- }
-}
-void RepeatedMessageFieldGenerator::
-GenerateAccessorDeclarations(io::Printer* printer) const {
- if (!dependent_getter_) {
- printer->Print(variables_,
- "$deprecated_attr$const $type$& $name$(int index) const;\n");
- printer->Annotate("name", descriptor_);
- }
- if (!dependent_field_) {
- InternalGenerateTypeDependentAccessorDeclarations(printer);
- }
- if (!dependent_getter_) {
- printer->Print(variables_,
- "$deprecated_attr$const ::google::protobuf::RepeatedPtrField< $type$ >&\n"
- " $name$() const;\n");
- printer->Annotate("name", descriptor_);
- }
+ printer->Print(variables_,
+ "$deprecated_attr$const $type$& $name$(int index) const;\n");
+ printer->Annotate("name", descriptor_);
+ printer->Print(variables_, "$deprecated_attr$$type$* ${$add_$name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(variables_,
+ "$deprecated_attr$const ::google::protobuf::RepeatedPtrField< $type$ >&\n"
+ " $name$() const;\n");
+ printer->Annotate("name", descriptor_);
}
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();
-
- if (dependent_getter_) {
- printer->Print(variables,
- "template <class T>\n"
- "inline const $type$& $dependent_classname$::$name$(int index) const {\n"
- " // @@protoc_insertion_point(field_get:$full_name$)\n"
- " return $this_const_message$$name$_.$cppget$(index);\n"
- "}\n");
- }
-
- // Generate per-element accessors:
- printer->Print(variables,
- "template <class T>\n"
- "inline $type$* $dependent_classname$::mutable_$name$(int index) {\n"
+GenerateInlineAccessorDefinitions(io::Printer* printer) const {
+ printer->Print(variables_,
+ "inline $type$* $classname$::mutable_$name$(int index) {\n"
// TODO(dlj): move insertion points
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
- " return $this_message$$name$_.Mutable(index);\n"
+ "$type_reference_function$"
+ " return $name$_.Mutable(index);\n"
"}\n"
- "template <class T>\n"
- "inline $type$* $dependent_classname$::add_$name$() {\n"
- " // @@protoc_insertion_point(field_add:$full_name$)\n"
- " return $this_message$$name$_.Add();\n"
- "}\n");
-
- if (dependent_getter_) {
- printer->Print(variables,
- "template <class T>\n"
- "inline const ::google::protobuf::RepeatedPtrField< $type$ >&\n"
- "$dependent_classname$::$name$() const {\n"
- " // @@protoc_insertion_point(field_list:$full_name$)\n"
- " return $this_const_message$$name$_;\n"
- "}\n");
- }
-
- // Generate mutable access to the entire list:
- printer->Print(variables,
- "template <class T>\n"
"inline ::google::protobuf::RepeatedPtrField< $type$ >*\n"
- "$dependent_classname$::mutable_$name$() {\n"
+ "$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
- " return &$this_message$$name$_;\n"
+ "$type_reference_function$"
+ " return &$name$_;\n"
"}\n");
-}
-void RepeatedMessageFieldGenerator::
-GenerateInlineAccessorDefinitions(io::Printer* printer) const {
- if (!dependent_getter_) {
+ if (options_.safe_boundary_check) {
printer->Print(variables_,
"inline const $type$& $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
- " return $name$_.$cppget$(index);\n"
+ " return $name$_.InternalCheckedGet(index,\n"
+ " *reinterpret_cast<const $type$*>(&$type_default_instance$));\n"
"}\n");
- }
-
- if (!dependent_field_) {
+ } else {
printer->Print(variables_,
- "inline $type$* $classname$::mutable_$name$(int index) {\n"
- // TODO(dlj): move insertion points
- " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
- " return $name$_.Mutable(index);\n"
- "}\n"
- "inline $type$* $classname$::add_$name$() {\n"
- " // @@protoc_insertion_point(field_add:$full_name$)\n"
- " return $name$_.Add();\n"
+ "inline const $type$& $classname$::$name$(int index) const {\n"
+ " // @@protoc_insertion_point(field_get:$full_name$)\n"
+ "$type_reference_function$"
+ " return $name$_.Get(index);\n"
"}\n");
}
- if (!dependent_field_) {
- printer->Print(variables_,
- "inline ::google::protobuf::RepeatedPtrField< $type$ >*\n"
- "$classname$::mutable_$name$() {\n"
- " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
- " return &$name$_;\n"
- "}\n");
- }
- if (!dependent_getter_) {
- printer->Print(variables_,
- "inline const ::google::protobuf::RepeatedPtrField< $type$ >&\n"
- "$classname$::$name$() const {\n"
- " // @@protoc_insertion_point(field_list:$full_name$)\n"
- " return $name$_;\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"
+ "$classname$::$name$() const {\n"
+ " // @@protoc_insertion_point(field_list:$full_name$)\n"
+ "$type_reference_function$"
+ " return $name$_;\n"
+ "}\n");
}
void RepeatedMessageFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.Clear();\n");
+ if (implicit_weak_field_) {
+ printer->Print(
+ variables_,
+ "CastToBase(&$name$_)->Clear<"
+ "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>();\n");
+ } else {
+ printer->Print(variables_, "$name$_.Clear();\n");
+ }
}
void RepeatedMessageFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n");
+ if (implicit_weak_field_) {
+ printer->Print(
+ variables_,
+ "CastToBase(&$name$_)->MergeFrom<"
+ "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>(CastToBase("
+ "from.$name$_));\n");
+ } else {
+ printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n");
+ }
}
void RepeatedMessageFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.InternalSwap(&other->$name$_);\n");
+ printer->Print(
+ variables_,
+ "CastToBase(&$name$_)->InternalSwap(CastToBase(&other->$name$_));\n");
}
void RepeatedMessageFieldGenerator::
@@ -1015,9 +752,18 @@ GenerateConstructorCode(io::Printer* printer) const {
void RepeatedMessageFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_MESSAGE) {
- printer->Print(variables_,
- "DO_(::google::protobuf::internal::WireFormatLite::"
- "ReadMessage(input, add_$name$()));\n");
+ if (implicit_weak_field_) {
+ printer->Print(variables_,
+ "DO_(::google::protobuf::internal::WireFormatLite::"
+ "ReadMessage(input, CastToBase(&$name$_)->AddWeak(\n"
+ " reinterpret_cast<const ::google::protobuf::MessageLite*>(\n"
+ " &$type_default_instance$))));\n");
+ } else {
+ printer->Print(variables_,
+ "DO_(::google::protobuf::internal::WireFormatLite::"
+ "ReadMessage(\n"
+ " input, add_$name$()));\n");
+ }
} else {
printer->Print(variables_,
"DO_(::google::protobuf::internal::WireFormatLite::"
@@ -1031,7 +777,19 @@ GenerateSerializeWithCachedSizes(io::Printer* printer) const {
"for (unsigned int i = 0,\n"
" n = static_cast<unsigned int>(this->$name$_size()); i < n; i++) {\n"
" ::google::protobuf::internal::WireFormatLite::Write$stream_writer$(\n"
- " $number$, this->$name$(static_cast<int>(i)), output);\n"
+ " $number$,\n");
+ if (implicit_weak_field_) {
+ printer->Print(
+ variables_,
+ " CastToBase($name$_).Get<"
+ "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>("
+ "static_cast<int>(i)),\n");
+ } else {
+ printer->Print(variables_,
+ " this->$name$(static_cast<int>(i)),\n");
+ }
+ printer->Print(variables_,
+ " output);\n"
"}\n");
}
@@ -1056,9 +814,18 @@ GenerateByteSize(io::Printer* printer) const {
"total_size += $tag_size$UL * count;\n"
"for (unsigned int i = 0; i < count; i++) {\n"
" total_size +=\n"
- " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"
- " this->$name$(static_cast<int>(i)));\n"
- "}\n");
+ " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n");
+ if (implicit_weak_field_) {
+ printer->Print(
+ variables_,
+ " CastToBase($name$_).Get<"
+ "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>("
+ "static_cast<int>(i)));\n");
+ } else {
+ printer->Print(variables_,
+ " this->$name$(static_cast<int>(i)));\n");
+ }
+ printer->Print(variables_, "}\n");
printer->Outdent();
printer->Print("}\n");
}
diff --git a/src/google/protobuf/compiler/cpp/cpp_message_field.h b/src/google/protobuf/compiler/cpp/cpp_message_field.h
index 3be505e3..6879539c 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_message_field.h
@@ -38,25 +38,22 @@
#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 ---------------------------------------
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 GenerateNonInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
@@ -73,7 +70,6 @@ class MessageFieldGenerator : public FieldGenerator {
protected:
const FieldDescriptor* descriptor_;
- const bool dependent_field_;
const bool implicit_weak_field_;
std::map<string, string> variables_;
@@ -84,11 +80,10 @@ 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 ---------------------------------------
- void GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
@@ -101,24 +96,19 @@ class MessageOneofFieldGenerator : public MessageFieldGenerator {
void GenerateConstructorCode(io::Printer* printer) const;
private:
- void InternalGenerateInlineAccessorDefinitions(
- const std::map<string, string>& variables, io::Printer* printer) const;
-
- 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;
@@ -131,12 +121,8 @@ 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 dependent_getter_;
+ const bool implicit_weak_field_;
std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator);
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 4a29ad0e..f09885be 100644
--- a/src/google/protobuf/compiler/cpp/cpp_options.h
+++ b/src/google/protobuf/compiler/cpp/cpp_options.h
@@ -54,6 +54,8 @@ 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) {}
string dllexport_decl;
@@ -65,6 +67,8 @@ 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;
const AccessInfoMap* access_info_map;
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_primitive_field.cc b/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc
index bc2d02ea..701f9d2d 100644
--- a/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc
@@ -215,7 +215,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"inline $type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
- " return $oneof_prefix$$name$_;\n"
+ " return $field_member$;\n"
" }\n"
" return $default$;\n"
"}\n"
@@ -224,14 +224,14 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" }\n"
- " $oneof_prefix$$name$_ = value;\n"
+ " $field_member$ = value;\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n");
}
void PrimitiveOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
- printer->Print(variables_, "$oneof_prefix$$name$_ = $default$;\n");
+ printer->Print(variables_, "$field_member$ = $default$;\n");
}
void PrimitiveOneofFieldGenerator::
@@ -251,7 +251,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
"clear_$oneof_name$();\n"
"DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
" $type$, $wire_format_field_type$>(\n"
- " input, &$oneof_prefix$$name$_)));\n"
+ " input, &$field_member$)));\n"
"set_has_$name$();\n");
}
diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.cc b/src/google/protobuf/compiler/cpp/cpp_string_field.cc
index 264f6124..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$_.Release($default_variable$, GetArenaNoVirtual());\n"
+ " return $name$_.ReleaseNonDefault("
+ "$default_variable$, GetArenaNoVirtual());\n");
+ } else {
+ printer->Print(variables_,
+ " $clear_hasbit$\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$_.ReleaseNonDefaultNoArena($default_variable$);\n");
+ } else {
+ printer->Print(variables_,
" $clear_hasbit$\n"
- " return $name$_.ReleaseNoArena($default_variable$);\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,11 +470,11 @@ 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$_.UnsafeRawStringPointer())->clear();\n");
+ printer->Print(variables_, "$name$_.ClearNonDefaultToEmptyNoArena();\n");
} else {
- printer->Print(variables_,
- "(*$name$_.UnsafeRawStringPointer())->assign(*$default_variable$);\n");
+ printer->Print(
+ variables_,
+ "$name$_.UnsafeMutablePointer()->assign(*$default_variable$);\n");
}
} else {
if (descriptor_->default_value_string().empty()) {
@@ -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::
@@ -504,6 +603,11 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
}
}
+bool StringFieldGenerator::
+MergeFromCodedStreamNeedsArena() const {
+ return false;
+}
+
void StringFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
@@ -539,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_);
}
@@ -559,7 +667,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"inline const ::std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
- " return $oneof_prefix$$name$_.Get();\n"
+ " return $field_member$.Get();\n"
" }\n"
" return *$default_variable$;\n"
"}\n"
@@ -567,9 +675,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
- " $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
- " $oneof_prefix$$name$_.Set$lite$($default_variable$, value,\n"
+ " $field_member$.Set$lite$($default_variable$, value,\n"
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
@@ -579,9 +687,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
- " $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
- " $oneof_prefix$$name$_.Set$lite$(\n"
+ " $field_member$.Set$lite$(\n"
" $default_variable$, ::std::move(value), GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
"}\n"
@@ -591,9 +699,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
- " $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
- " $oneof_prefix$$name$_.Set$lite$($default_variable$,\n"
+ " $field_member$.Set$lite$($default_variable$,\n"
" $string_piece$(value), GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
@@ -603,9 +711,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
- " $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
- " $oneof_prefix$$name$_.Set$lite$(\n"
+ " $field_member$.Set$lite$(\n"
" $default_variable$, $string_piece$(\n"
" reinterpret_cast<const char*>(value), size),\n"
" GetArenaNoVirtual());\n"
@@ -615,9 +723,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
- " $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
- " return $oneof_prefix$$name$_.Mutable($default_variable$,\n"
+ " return $field_member$.Mutable($default_variable$,\n"
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
"}\n"
@@ -625,7 +733,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
- " return $oneof_prefix$$name$_.Release($default_variable$,\n"
+ " return $field_member$.Release($default_variable$,\n"
" GetArenaNoVirtual());\n"
" } else {\n"
" return NULL;\n"
@@ -633,12 +741,12 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"}\n"
"inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if (!has_$name$()) {\n"
- " $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" clear_$oneof_name$();\n"
" if ($name$ != NULL) {\n"
" set_has_$name$();\n"
- " $oneof_prefix$$name$_.SetAllocated($default_variable$, $name$,\n"
+ " $field_member$.SetAllocated($default_variable$, $name$,\n"
" GetArenaNoVirtual());\n"
" }\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
@@ -649,7 +757,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
- " return $oneof_prefix$$name$_.UnsafeArenaRelease(\n"
+ " return $field_member$.UnsafeArenaRelease(\n"
" $default_variable$, GetArenaNoVirtual());\n"
" } else {\n"
" return NULL;\n"
@@ -659,12 +767,12 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"::std::string* $name$) {\n"
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" if (!has_$name$()) {\n"
- " $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" clear_$oneof_name$();\n"
" if ($name$) {\n"
" set_has_$name$();\n"
- " $oneof_prefix$$name$_.UnsafeArenaSetAllocated($default_variable$, "
+ " $field_member$.UnsafeArenaSetAllocated($default_variable$, "
"$name$, GetArenaNoVirtual());\n"
" }\n"
" // @@protoc_insertion_point(field_unsafe_arena_set_allocated:"
@@ -677,7 +785,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"inline const ::std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
- " return $oneof_prefix$$name$_.GetNoArena();\n"
+ " return $field_member$.GetNoArena();\n"
" }\n"
" return *$default_variable$;\n"
"}\n"
@@ -686,9 +794,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
- " $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
- " $oneof_prefix$$name$_.SetNoArena($default_variable$, value);\n"
+ " $field_member$.SetNoArena($default_variable$, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"#if LANG_CXX11\n"
@@ -697,10 +805,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
- " $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
- " $oneof_prefix$$name$_.SetNoArena(\n"
- " $default_variable$, ::std::move(value));\n"
+ " $field_member$.SetNoArena($default_variable$, ::std::move(value));\n"
" // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
"}\n"
"#endif\n"
@@ -709,9 +816,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
- " $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
- " $oneof_prefix$$name$_.SetNoArena($default_variable$,\n"
+ " $field_member$.SetNoArena($default_variable$,\n"
" $string_piece$(value));\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
@@ -721,10 +828,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
- " $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
- " $oneof_prefix$$name$_.SetNoArena($default_variable$, "
- "$string_piece$(\n"
+ " $field_member$.SetNoArena($default_variable$, $string_piece$(\n"
" reinterpret_cast<const char*>(value), size));\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
@@ -732,29 +838,28 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
- " $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
- " return $oneof_prefix$$name$_.MutableNoArena($default_variable$);\n"
+ " return $field_member$.MutableNoArena($default_variable$);\n"
"}\n"
"inline ::std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
- " return $oneof_prefix$$name$_.ReleaseNoArena($default_variable$);\n"
+ " return $field_member$.ReleaseNoArena($default_variable$);\n"
" } else {\n"
" return NULL;\n"
" }\n"
"}\n"
"inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if (!has_$name$()) {\n"
- " $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" clear_$oneof_name$();\n"
" if ($name$ != NULL) {\n"
" set_has_$name$();\n"
- " $oneof_prefix$$name$_.SetAllocatedNoArena($default_variable$,\n"
- " $name$);\n"
+ " $field_member$.SetAllocatedNoArena($default_variable$, $name$);\n"
" }\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n");
@@ -765,12 +870,11 @@ void StringOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
if (SupportsArenas(descriptor_)) {
printer->Print(variables_,
- "$oneof_prefix$$name$_.Destroy($default_variable$,\n"
+ "$field_member$.Destroy($default_variable$,\n"
" GetArenaNoVirtual());\n");
} else {
printer->Print(variables_,
- "$oneof_prefix$$name$_."
- "DestroyNoArena($default_variable$);\n");
+ "$field_member$.DestroyNoArena($default_variable$);\n");
}
}
@@ -796,7 +900,7 @@ void StringOneofFieldGenerator::
GenerateDestructorCode(io::Printer* printer) const {
printer->Print(variables_,
"if (has_$name$()) {\n"
- " $oneof_prefix$$name$_.DestroyNoArena($default_variable$);\n"
+ " $field_member$.DestroyNoArena($default_variable$);\n"
"}\n");
}
@@ -912,11 +1016,21 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
void RepeatedStringFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
+ if (options_.safe_boundary_check) {
+ printer->Print(variables_,
+ "inline const ::std::string& $classname$::$name$(int index) const {\n"
+ " // @@protoc_insertion_point(field_get:$full_name$)\n"
+ " return $name$_.InternalCheckedGet(\n"
+ " index, ::google::protobuf::internal::GetEmptyStringAlreadyInited());\n"
+ "}\n");
+ } else {
+ printer->Print(variables_,
+ "inline const ::std::string& $classname$::$name$(int index) const {\n"
+ " // @@protoc_insertion_point(field_get:$full_name$)\n"
+ " return $name$_.Get(index);\n"
+ "}\n");
+ }
printer->Print(variables_,
- "inline const ::std::string& $classname$::$name$(int index) const {\n"
- " // @@protoc_insertion_point(field_get:$full_name$)\n"
- " return $name$_.$cppget$(index);\n"
- "}\n"
"inline ::std::string* $classname$::mutable_$name$(int index) {\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.Mutable(index);\n"
@@ -991,7 +1105,8 @@ GenerateMergingCode(io::Printer* printer) const {
void RepeatedStringFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.InternalSwap(&other->$name$_);\n");
+ printer->Print(variables_,
+ "$name$_.InternalSwap(CastToBase(&other->$name$_));\n");
}
void RepeatedStringFieldGenerator::
diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.h b/src/google/protobuf/compiler/cpp/cpp_string_field.h
index f56f0721..6cbf722f 100644
--- a/src/google/protobuf/compiler/cpp/cpp_string_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_string_field.h
@@ -63,16 +63,22 @@ 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;
protected:
const FieldDescriptor* descriptor_;
std::map<string, string> variables_;
const bool lite_;
+ bool inlined_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringFieldGenerator);
@@ -97,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 61cc32a4..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,1365 +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 SpaceUsed().
- EXPECT_LE(sizeof(unittest::TestAllTypes), message1.SpaceUsed());
- const int empty_message_size = message1.SpaceUsed();
-
- // 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.SpaceUsed());
-
- // On some STL implementations, setting the string to a small value should
- // only increase SpaceUsed() 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.SpaceUsed());
-
- // Setting a string to a value larger than the string object itself should
- // increase SpaceUsed(), 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.SpaceUsed());
-
- int previous_size = message1.SpaceUsed();
- // 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().SpaceUsed());
- EXPECT_EQ(previous_size +
- sizeof(unittest::TestAllTypes::NestedMessage),
- message1.SpaceUsed());
-}
-
-TEST(GeneratedMessageTest, TestOneofSpaceUsed) {
- unittest::TestOneof2 message1;
- EXPECT_LE(sizeof(unittest::TestOneof2), message1.SpaceUsed());
-
- const int empty_message_size = message1.SpaceUsed();
- // 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.SpaceUsed());
-
- // Setting a string in oneof to a small value should only increase SpaceUsed()
- // by the size of a string object.
- message1.set_foo_string("abc");
- EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsed());
-
- // Setting a string in oneof to a value larger than the string object itself
- // should increase SpaceUsed(), 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.SpaceUsed());
-
- // 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().SpaceUsed());
- EXPECT_EQ(empty_message_size +
- sizeof(unittest::TestOneof2::NestedMessage),
- message1.SpaceUsed());
-}
-
-#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 d1bb3194..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>
@@ -72,9 +69,7 @@ class CppMetadataTest : public ::testing::Test {
TestTempDir();
const bool result =
- atu::CaptureMetadata(filename, cpp_out,
- /* meta_file_suffix */ "", &cli, file,
- /* outputs */ NULL);
+ atu::RunProtoCompiler(filename, cpp_out, &cli, file);
if (!result) {
return result;
diff --git a/src/google/protobuf/compiler/csharp/csharp_doc_comment.cc b/src/google/protobuf/compiler/csharp/csharp_doc_comment.cc
index 636a76a0..a21dc0a4 100644
--- a/src/google/protobuf/compiler/csharp/csharp_doc_comment.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_doc_comment.cc
@@ -56,7 +56,7 @@ void WriteDocCommentBodyImpl(io::Printer* printer, SourceLocation location) {
// node of a summary element, not part of an attribute.
comments = StringReplace(comments, "&", "&amp;", true);
comments = StringReplace(comments, "<", "&lt;", true);
- vector<string> lines = Split(comments, "\n", false /* skip_empty */);
+ std::vector<string> lines = Split(comments, "\n", false /* skip_empty */);
// TODO: We really should work out which part to put in the summary and which to put in the remarks...
// but that needs to be part of a bigger effort to understand the markdown better anyway.
printer->Print("/// <summary>\n");
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 c13ed65b..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 {
@@ -64,7 +62,7 @@ bool Generator::Generate(
GeneratorContext* generator_context,
string* error) const {
- vector<pair<string, string> > options;
+ std::vector<std::pair<string, string> > options;
ParseGeneratorParameter(parameter, &options);
// We only support proto3 - but we make an exception for descriptor.proto.
@@ -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..c3831e72 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
@@ -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_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 9f7bb349..0686ea0f 100644
--- a/src/google/protobuf/compiler/java/java_enum_field.cc
+++ b/src/google/protobuf/compiler/java/java_enum_field.cc
@@ -80,7 +80,7 @@ void SetEnumVariables(const FieldDescriptor* descriptor,
// Use deprecated valueOf() method to be compatible with old generated code
// for v2.5.0/v2.6.1.
// TODO(xiaofeng): Use "forNumber" when we no longer support compatibility
- // with v2.5.0/v2.6.1.
+ // with v2.5.0/v2.6.1, and remove the @SuppressWarnings annotations.
(*variables)["for_number"] = "valueOf";
if (SupportFieldPresence(descriptor->file())) {
@@ -199,6 +199,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
+ " @SuppressWarnings(\"deprecation\")\n"
" $type$ result = $type$.$for_number$($name$_);\n"
" return result == null ? $unknown$ : result;\n"
"}\n");
@@ -237,6 +238,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
+ " @SuppressWarnings(\"deprecation\")\n"
" $type$ result = $type$.$for_number$($name$_);\n"
" return result == null ? $unknown$ : result;\n"
"}\n");
@@ -320,6 +322,7 @@ GenerateParsingCode(io::Printer* printer) const {
} else {
printer->Print(variables_,
"int rawValue = input.readEnum();\n"
+ " @SuppressWarnings(\"deprecation\")\n"
"$type$ value = $type$.$for_number$(rawValue);\n"
"if (value == null) {\n"
" unknownFields.mergeVarintField($number$, rawValue);\n"
@@ -412,6 +415,7 @@ GenerateMembers(io::Printer* printer) const {
printer->Print(variables_,
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
+ " @SuppressWarnings(\"deprecation\")\n"
" $type$ result = $type$.$for_number$(\n"
" (java.lang.Integer) $oneof_name$_);\n"
" return result == null ? $unknown$ : result;\n"
@@ -456,6 +460,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
printer->Print(variables_,
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
+ " @SuppressWarnings(\"deprecation\")\n"
" $type$ result = $type$.$for_number$(\n"
" (java.lang.Integer) $oneof_name$_);\n"
" return result == null ? $unknown$ : result;\n"
@@ -517,6 +522,7 @@ GenerateParsingCode(io::Printer* printer) const {
} else {
printer->Print(variables_,
"int rawValue = input.readEnum();\n"
+ "@SuppressWarnings(\"deprecation\")\n"
"$type$ value = $type$.$for_number$(rawValue);\n"
"if (value == null) {\n"
" unknownFields.mergeVarintField($number$, rawValue);\n"
@@ -626,6 +632,7 @@ GenerateMembers(io::Printer* printer) const {
" new com.google.protobuf.Internal.ListAdapter.Converter<\n"
" java.lang.Integer, $type$>() {\n"
" public $type$ convert(java.lang.Integer from) {\n"
+ " @SuppressWarnings(\"deprecation\")\n"
" $type$ result = $type$.$for_number$(from);\n"
" return result == null ? $unknown$ : result;\n"
" }\n"
@@ -667,8 +674,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");
}
@@ -879,6 +885,7 @@ GenerateParsingCode(io::Printer* printer) const {
} else {
printer->Print(variables_,
"int rawValue = input.readEnum();\n"
+ "@SuppressWarnings(\"deprecation\")\n"
"$type$ value = $type$.$for_number$(rawValue);\n"
"if (value == null) {\n"
" unknownFields.mergeVarintField($number$, rawValue);\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_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 2486b739..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>
@@ -437,11 +434,11 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
printer->Print(
- "$field_name$($field_number$),\n",
- "field_name",
- ToUpper(field->name()),
- "field_number",
- SimpleItoa(field->number()));
+ "$deprecation$$field_name$($field_number$),\n",
+ "deprecation",
+ field->options().deprecated() ? "@java.lang.Deprecated " : "",
+ "field_name", ToUpper(field->name()),
+ "field_number", SimpleItoa(field->number()));
}
printer->Print(
"$cap_oneof_name$_NOT_SET(0);\n",
@@ -555,6 +552,7 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
GenerateParser(printer);
printer->Print(
+ "@java.lang.Override\n"
"public $classname$ getDefaultInstanceForType() {\n"
" return DEFAULT_INSTANCE;\n"
"}\n"
@@ -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;
@@ -588,6 +586,7 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
std::sort(sorted_extensions.begin(), sorted_extensions.end(),
ExtensionRangeOrdering());
printer->Print(
+ "@java.lang.Override\n"
"public void writeTo(com.google.protobuf.CodedOutputStream output)\n"
" throws java.io.IOException {\n");
printer->Indent();
@@ -648,6 +647,7 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
printer->Print(
"}\n"
"\n"
+ "@java.lang.Override\n"
"public int getSerializedSize() {\n"
" int size = memoizedSize;\n"
" if (size != -1) return size;\n"
@@ -789,6 +789,7 @@ void ImmutableMessageGenerator::GenerateSerializeOneExtensionRange(
void ImmutableMessageGenerator::GenerateBuilder(io::Printer* printer) {
// LITE_RUNTIME implements this at the GeneratedMessageLite level.
printer->Print(
+ "@java.lang.Override\n"
"public Builder newBuilderForType() { return newBuilder(); }\n");
printer->Print(
@@ -798,6 +799,7 @@ void ImmutableMessageGenerator::GenerateBuilder(io::Printer* printer) {
"public static Builder newBuilder($classname$ prototype) {\n"
" return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n"
"}\n"
+ "@java.lang.Override\n"
"public Builder toBuilder() {\n"
" return this == DEFAULT_INSTANCE\n"
" ? new Builder() : new Builder().mergeFrom(this);\n"
@@ -841,6 +843,7 @@ GenerateDescriptorMethods(io::Printer* printer) {
if (!map_fields.empty()) {
printer->Print(
"@SuppressWarnings({\"rawtypes\"})\n"
+ "@java.lang.Override\n"
"protected com.google.protobuf.MapField internalGetMapField(\n"
" int number) {\n"
" switch (number) {\n");
@@ -866,6 +869,7 @@ GenerateDescriptorMethods(io::Printer* printer) {
"}\n");
}
printer->Print(
+ "@java.lang.Override\n"
"protected com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n"
" internalGetFieldAccessorTable() {\n"
" return $fileclass$.internal_$identifier$_fieldAccessorTable\n"
@@ -889,6 +893,7 @@ void ImmutableMessageGenerator::GenerateIsInitialized(
printer->Print(
"private byte memoizedIsInitialized = -1;\n");
printer->Print(
+ "@java.lang.Override\n"
"public final boolean isInitialized() {\n");
printer->Indent();
@@ -1209,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(
@@ -1259,19 +1264,9 @@ GenerateParsingConstructor(io::Printer* printer) {
printer->Indent();
printer->Print(
- "case 0:\n" // zero signals EOF / limit reached
- " done = true;\n"
- " break;\n"
- "default: {\n"
- " if (!parseUnknownField$suffix$(\n"
- " input, unknownFields, extensionRegistry, tag)) {\n"
- " done = true;\n" // it's an endgroup tag
- " }\n"
- " break;\n"
- "}\n",
- "suffix",
- descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 ? "Proto3"
- : "");
+ "case 0:\n" // zero signals EOF / limit reached
+ " done = true;\n"
+ " break;\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = sorted_fields[i];
@@ -1309,6 +1304,18 @@ GenerateParsingConstructor(io::Printer* printer) {
}
}
+ printer->Print(
+ "default: {\n"
+ " if (!parseUnknownField$suffix$(\n"
+ " input, unknownFields, extensionRegistry, tag)) {\n"
+ " done = true;\n" // it's an endgroup tag
+ " }\n"
+ " break;\n"
+ "}\n",
+ "suffix",
+ descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 ? "Proto3"
+ : "");
+
printer->Outdent();
printer->Outdent();
printer->Print(
@@ -1356,6 +1363,7 @@ void ImmutableMessageGenerator::GenerateParser(io::Printer* printer) {
"classname", descriptor_->name());
printer->Indent();
printer->Print(
+ "@java.lang.Override\n"
"public $classname$ parsePartialFrom(\n"
" com.google.protobuf.CodedInputStream input,\n"
" com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
diff --git a/src/google/protobuf/compiler/java/java_message_builder.cc b/src/google/protobuf/compiler/java/java_message_builder.cc
index f9bbfbf4..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>
@@ -180,11 +177,13 @@ Generate(io::Printer* printer) {
// to subclass a different GeneratedMessage class (e.g., in v3.0.0 release
// we changed all generated code to subclass GeneratedMessageV3).
printer->Print(
+ "@java.lang.Override\n"
"public final Builder setUnknownFields(\n"
" final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
" return super.setUnknownFields$suffix$(unknownFields);\n"
"}\n"
"\n"
+ "@java.lang.Override\n"
"public final Builder mergeUnknownFields(\n"
" final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
" return super.mergeUnknownFields(unknownFields);\n"
@@ -277,6 +276,7 @@ GenerateDescriptorMethods(io::Printer* printer) {
"}\n");
}
printer->Print(
+ "@java.lang.Override\n"
"protected com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n"
" internalGetFieldAccessorTable() {\n"
" return $fileclass$.internal_$identifier$_fieldAccessorTable\n"
@@ -333,6 +333,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
"}\n");
printer->Print(
+ "@java.lang.Override\n"
"public Builder clear() {\n"
" super.clear();\n");
@@ -361,6 +362,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
"\n");
printer->Print(
+ "@java.lang.Override\n"
"public com.google.protobuf.Descriptors.Descriptor\n"
" getDescriptorForType() {\n"
" return $fileclass$.internal_$identifier$_descriptor;\n"
@@ -371,6 +373,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
// LITE runtime implements this in GeneratedMessageLite.
printer->Print(
+ "@java.lang.Override\n"
"public $classname$ getDefaultInstanceForType() {\n"
" return $classname$.getDefaultInstance();\n"
"}\n"
@@ -378,6 +381,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
"classname", name_resolver_->GetImmutableClassName(descriptor_));
printer->Print(
+ "@java.lang.Override\n"
"public $classname$ build() {\n"
" $classname$ result = buildPartial();\n"
" if (!result.isInitialized()) {\n"
@@ -389,6 +393,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
"classname", name_resolver_->GetImmutableClassName(descriptor_));
printer->Print(
+ "@java.lang.Override\n"
"public $classname$ buildPartial() {\n"
" $classname$ result = new $classname$(this);\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
@@ -457,27 +462,33 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
// to subclass a different GeneratedMessage class (e.g., in v3.0.0 release
// we changed all generated code to subclass GeneratedMessageV3).
printer->Print(
+ "@java.lang.Override\n"
"public Builder clone() {\n"
" return (Builder) super.clone();\n"
"}\n"
+ "@java.lang.Override\n"
"public Builder setField(\n"
" com.google.protobuf.Descriptors.FieldDescriptor field,\n"
" java.lang.Object value) {\n"
" return (Builder) super.setField(field, value);\n"
"}\n"
+ "@java.lang.Override\n"
"public Builder clearField(\n"
" com.google.protobuf.Descriptors.FieldDescriptor field) {\n"
" return (Builder) super.clearField(field);\n"
"}\n"
+ "@java.lang.Override\n"
"public Builder clearOneof(\n"
" com.google.protobuf.Descriptors.OneofDescriptor oneof) {\n"
" return (Builder) super.clearOneof(oneof);\n"
"}\n"
+ "@java.lang.Override\n"
"public Builder setRepeatedField(\n"
" com.google.protobuf.Descriptors.FieldDescriptor field,\n"
" int index, java.lang.Object value) {\n"
" return (Builder) super.setRepeatedField(field, index, value);\n"
"}\n"
+ "@java.lang.Override\n"
"public Builder addRepeatedField(\n"
" com.google.protobuf.Descriptors.FieldDescriptor field,\n"
" java.lang.Object value) {\n"
@@ -486,24 +497,28 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
if (descriptor_->extension_range_count() > 0) {
printer->Print(
+ "@java.lang.Override\n"
"public <Type> Builder setExtension(\n"
" com.google.protobuf.GeneratedMessage.GeneratedExtension<\n"
" $classname$, Type> extension,\n"
" Type value) {\n"
" return (Builder) super.setExtension(extension, value);\n"
"}\n"
+ "@java.lang.Override\n"
"public <Type> Builder setExtension(\n"
" com.google.protobuf.GeneratedMessage.GeneratedExtension<\n"
" $classname$, java.util.List<Type>> extension,\n"
" int index, Type value) {\n"
" return (Builder) super.setExtension(extension, index, value);\n"
"}\n"
+ "@java.lang.Override\n"
"public <Type> Builder addExtension(\n"
" com.google.protobuf.GeneratedMessage.GeneratedExtension<\n"
" $classname$, java.util.List<Type>> extension,\n"
" Type value) {\n"
" return (Builder) super.addExtension(extension, value);\n"
"}\n"
+ "@java.lang.Override\n"
"public <Type> Builder clearExtension(\n"
" com.google.protobuf.GeneratedMessage.GeneratedExtension<\n"
" $classname$, ?> extension) {\n"
@@ -516,6 +531,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
if (context_->HasGeneratedMethods(descriptor_)) {
printer->Print(
+ "@java.lang.Override\n"
"public Builder mergeFrom(com.google.protobuf.Message other) {\n"
" if (other instanceof $classname$) {\n"
" return mergeFrom(($classname$)other);\n"
@@ -602,6 +618,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
void MessageBuilderGenerator::
GenerateBuilderParsingMethods(io::Printer* printer) {
printer->Print(
+ "@java.lang.Override\n"
"public Builder mergeFrom(\n"
" com.google.protobuf.CodedInputStream input,\n"
" com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
@@ -627,6 +644,7 @@ GenerateBuilderParsingMethods(io::Printer* printer) {
void MessageBuilderGenerator::GenerateIsInitialized(
io::Printer* printer) {
printer->Print(
+ "@java.lang.Override\n"
"public final boolean isInitialized() {\n");
printer->Indent();
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_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 d828be43..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,38 +1022,7 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodMergeFromStream(
" done = true;\n"
" break;\n");
- if (descriptor_->extension_range_count() > 0) {
- if (descriptor_->options().message_set_wire_format()) {
- printer->Print(
- "default: {\n"
- " if (!parseUnknownFieldAsMessageSet(\n"
- " getDefaultInstanceForType(), input, extensionRegistry,\n"
- " tag)) {\n"
- " done = true;\n" // it's an endgroup tag
- " }\n"
- " break;\n"
- "}\n");
- } else {
- printer->Print(
- "default: {\n"
- " if (!parseUnknownField(getDefaultInstanceForType(),\n"
- " input, extensionRegistry, tag)) {\n"
- " done = true;\n" // it's an endgroup tag
- " }\n"
- " break;\n"
- "}\n");
- }
- } else {
- printer->Print(
- "default: {\n"
- " if (!parseUnknownField(tag, input)) {\n"
- " done = true;\n" // it's an endgroup tag
- " }\n"
- " break;\n"
- "}\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];
@@ -1073,6 +1059,37 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodMergeFromStream(
}
}
+ if (descriptor_->extension_range_count() > 0) {
+ if (descriptor_->options().message_set_wire_format()) {
+ printer->Print(
+ "default: {\n"
+ " if (!parseUnknownFieldAsMessageSet(\n"
+ " getDefaultInstanceForType(), input, extensionRegistry,\n"
+ " tag)) {\n"
+ " done = true;\n" // it's an endgroup tag
+ " }\n"
+ " break;\n"
+ "}\n");
+ } else {
+ printer->Print(
+ "default: {\n"
+ " if (!parseUnknownField(getDefaultInstanceForType(),\n"
+ " input, extensionRegistry, tag)) {\n"
+ " done = true;\n" // it's an endgroup tag
+ " }\n"
+ " break;\n"
+ "}\n");
+ }
+ } else {
+ printer->Print(
+ "default: {\n"
+ " if (!parseUnknownField(tag, input)) {\n"
+ " done = true;\n" // it's an endgroup tag
+ " }\n"
+ " break;\n"
+ "}\n");
+ }
+
printer->Outdent();
printer->Outdent();
printer->Print(
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..71ee0992 100644
--- a/src/google/protobuf/compiler/java/java_primitive_field.cc
+++ b/src/google/protobuf/compiler/java/java_primitive_field.cc
@@ -633,8 +633,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_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 10dd3648..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.
- vector<const EnumValueDescriptor*> canonical_values_;
-
- struct Alias {
- const EnumValueDescriptor* value;
- const EnumValueDescriptor* canonical_value;
- };
- 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 26bc7f85..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, 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 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 1be25d10..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_;
- 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_;
- 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_;
- 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 17f7386e..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;
-
- 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,
- 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,
- 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 217eafe2..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,
- 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 7c3a0421..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 {
- vector<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") {
- 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") {
- 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 += "/";
-
- 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
index a725b62e..f0f946e5 100644
--- a/src/google/protobuf/compiler/js/embed.cc
+++ b/src/google/protobuf/compiler/js/embed.cc
@@ -34,8 +34,6 @@
#include <iostream>
#include <string>
-const char output_file[] = "well_known_types_embed.cc";
-
static bool AsciiIsPrint(unsigned char c) {
return c >= 32 && c < 127;
}
diff --git a/src/google/protobuf/compiler/js/js_generator.cc b/src/google/protobuf/compiler/js/js_generator.cc
index 16fe19ad..d8282e40 100755
--- 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 {
@@ -195,9 +193,9 @@ string ModuleAlias(const string& filename) {
// We'll worry about this problem if/when we actually see it. This name isn't
// exposed to users so we can change it later if we need to.
string basename = StripProto(filename);
- StripString(&basename, "-", '$');
- StripString(&basename, "/", '_');
- StripString(&basename, ".", '_');
+ ReplaceCharacters(&basename, "-", '$');
+ ReplaceCharacters(&basename, "/", '_');
+ ReplaceCharacters(&basename, ".", '_');
return basename + "_pb";
}
@@ -1028,7 +1026,7 @@ string JSFieldTypeAnnotation(const GeneratorOptions& options,
if (!IsPrimitive(jstype)) {
jstype = "!" + jstype;
}
- jstype = "Array.<" + jstype + ">";
+ jstype = "Array<" + jstype + ">";
}
}
@@ -1558,6 +1556,22 @@ bool GenerateJspbAllowedSet(const GeneratorOptions& options,
return true;
}
+// Embeds base64 encoded GeneratedCodeInfo proto in a comment at the end of
+// file.
+void EmbedCodeAnnotations(const GeneratedCodeInfo& annotations,
+ io::Printer* printer) {
+ // Serialize annotations proto into base64 string.
+ string meta_content;
+ annotations.SerializeToString(&meta_content);
+ string meta_64;
+ Base64Escape(meta_content, &meta_64);
+
+ // Print base64 encoded annotations at the end of output file in
+ // a comment.
+ printer->Print("\n// Below is base64 encoded GeneratedCodeInfo proto");
+ printer->Print("\n// $encoded_proto$\n", "encoded_proto", meta_64);
+}
+
} // anonymous namespace
void Generator::GenerateHeader(const GeneratorOptions& options,
@@ -2046,6 +2060,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(
@@ -2752,28 +2767,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(
@@ -2822,7 +2842,7 @@ void Generator::GenerateClassExtensionFieldInfo(const GeneratorOptions& options,
"so that it\n"
" * works in OPTIMIZED mode.\n"
" *\n"
- " * @type {!Object.<number, jspb.ExtensionFieldInfo>}\n"
+ " * @type {!Object<number, jspb.ExtensionFieldInfo>}\n"
" */\n"
"$class$.extensions = {};\n"
"\n",
@@ -2843,7 +2863,7 @@ void Generator::GenerateClassExtensionFieldInfo(const GeneratorOptions& options,
"so that it\n"
" * works in OPTIMIZED mode.\n"
" *\n"
- " * @type {!Object.<number, jspb.ExtensionFieldBinaryInfo>}\n"
+ " * @type {!Object<number, jspb.ExtensionFieldBinaryInfo>}\n"
" */\n"
"$class$.extensionsBinary = {};\n"
"\n",
@@ -3190,21 +3210,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"
- " * @type {!jspb.ExtensionFieldInfo.<$extensionType$>}\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"
@@ -3214,7 +3237,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 ?
@@ -3233,7 +3256,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)
@@ -3256,7 +3279,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(
@@ -3484,7 +3507,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(), '$');
@@ -3533,7 +3556,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(), '$');
@@ -3559,7 +3582,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(), '$');
@@ -3582,7 +3605,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(), '$');
@@ -3618,7 +3641,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(
@@ -3634,10 +3657,7 @@ bool Generator::GenerateAll(const std::vector<const FileDescriptor*>& files,
}
if (options.annotate_code) {
- const string meta_file = filename + ".meta";
- google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output(
- context->Open(meta_file));
- annotations.SerializeToZeroCopyStream(info_output.get());
+ EmbedCodeAnnotations(annotations, &printer);
}
}
}
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 bfcb83df..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>
@@ -70,7 +67,7 @@ namespace compiler {
// Returns the list of the names of files in all_files in the form of a
// comma-separated string.
-string CommaSeparatedList(const std::vector<const FileDescriptor*> all_files) {
+string CommaSeparatedList(const std::vector<const FileDescriptor*>& all_files) {
std::vector<string> names;
for (size_t i = 0; i < all_files.size(); i++) {
names.push_back(all_files[i]->name());
@@ -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_enum.cc b/src/google/protobuf/compiler/objectivec/objectivec_enum.cc
index 02d60b3e..978e985c 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_enum.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_enum.cc
@@ -149,7 +149,7 @@ void EnumGenerator::GenerateSource(io::Printer* printer) {
printer->Print(
"GPBEnumDescriptor *$name$_EnumDescriptor(void) {\n"
- " static GPBEnumDescriptor *descriptor = NULL;\n"
+ " static _Atomic(GPBEnumDescriptor*) descriptor = nil;\n"
" if (!descriptor) {\n",
"name", name_);
@@ -192,7 +192,8 @@ void EnumGenerator::GenerateSource(io::Printer* printer) {
"extraTextFormatInfo", CEscape(text_format_decode_data.Data()));
}
printer->Print(
- " if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) {\n"
+ " GPBEnumDescriptor *expected = nil;\n"
+ " if (!atomic_compare_exchange_strong(&descriptor, &expected, worker)) {\n"
" [worker release];\n"
" }\n"
" }\n"
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_enum.h b/src/google/protobuf/compiler/objectivec/objectivec_enum.h
index 0b41cf73..f52e9e68 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_enum.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_enum.h
@@ -59,8 +59,8 @@ class EnumGenerator {
private:
const EnumDescriptor* descriptor_;
- vector<const EnumValueDescriptor*> base_values_;
- vector<const EnumValueDescriptor*> all_values_;
+ std::vector<const EnumValueDescriptor*> base_values_;
+ std::vector<const EnumValueDescriptor*> all_values_;
const string name_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator);
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 954b2688..f0d9b4d5 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_file.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_file.cc
@@ -56,6 +56,20 @@ const int32 GOOGLE_PROTOBUF_OBJC_VERSION = 30002;
const char* kHeaderExtension = ".pbobjc.h";
+// Checks if a message contains any enums definitions (on the message or
+// a nested message under it).
+bool MessageContainsEnums(const Descriptor* message) {
+ if (message->enum_type_count() > 0) {
+ return true;
+ }
+ for (int i = 0; i < message->nested_type_count(); i++) {
+ if (MessageContainsEnums(message->nested_type(i))) {
+ return true;
+ }
+ }
+ return false;
+}
+
// Checks if a message contains any extension definitions (on the message or
// a nested message under it).
bool MessageContainsExtensions(const Descriptor* message) {
@@ -70,6 +84,20 @@ bool MessageContainsExtensions(const Descriptor* message) {
return false;
}
+// Checks if the file contains any enum definitions (at the root or
+// nested under a message).
+bool FileContainsEnums(const FileDescriptor* file) {
+ if (file->enum_type_count() > 0) {
+ return true;
+ }
+ for (int i = 0; i < file->message_type_count(); i++) {
+ if (MessageContainsEnums(file->message_type(i))) {
+ return true;
+ }
+ }
+ return false;
+}
+
// Checks if the file contains any extensions definitions (at the root or
// nested under a message).
bool FileContainsExtensions(const FileDescriptor* file) {
@@ -88,9 +116,9 @@ bool FileContainsExtensions(const FileDescriptor* file) {
// deps as visited and prunes them from the needed files list.
void PruneFileAndDepsMarkingAsVisited(
const FileDescriptor* file,
- vector<const FileDescriptor*>* files,
+ std::vector<const FileDescriptor*>* files,
std::set<const FileDescriptor*>* files_visited) {
- vector<const FileDescriptor*>::iterator iter =
+ std::vector<const FileDescriptor*>::iterator iter =
std::find(files->begin(), files->end(), file);
if (iter != files->end()) {
files->erase(iter);
@@ -104,7 +132,7 @@ void PruneFileAndDepsMarkingAsVisited(
// Helper for CollectMinimalFileDepsContainingExtensions.
void CollectMinimalFileDepsContainingExtensionsWorker(
const FileDescriptor* file,
- vector<const FileDescriptor*>* files,
+ std::vector<const FileDescriptor*>* files,
std::set<const FileDescriptor*>* files_visited) {
if (files_visited->find(file) != files_visited->end()) {
return;
@@ -137,7 +165,7 @@ void CollectMinimalFileDepsContainingExtensionsWorker(
// specifically).
void CollectMinimalFileDepsContainingExtensions(
const FileDescriptor* file,
- vector<const FileDescriptor*>* files) {
+ std::vector<const FileDescriptor*>* files) {
std::set<const FileDescriptor*> files_visited;
for (int i = 0; i < file->dependency_count(); i++) {
const FileDescriptor* dep = file->dependency(i);
@@ -160,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));
@@ -186,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.
@@ -208,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);
@@ -230,7 +270,7 @@ void FileGenerator::GenerateHeader(io::Printer *printer) {
"\n");
std::set<string> fwd_decls;
- for (vector<MessageGenerator *>::iterator iter = message_generators_.begin();
+ for (std::vector<MessageGenerator *>::iterator iter = message_generators_.begin();
iter != message_generators_.end(); ++iter) {
(*iter)->DetermineForwardDeclarations(&fwd_decls);
}
@@ -247,12 +287,12 @@ void FileGenerator::GenerateHeader(io::Printer *printer) {
"\n");
// need to write out all enums first
- for (vector<EnumGenerator *>::iterator iter = enum_generators_.begin();
+ for (std::vector<EnumGenerator *>::iterator iter = enum_generators_.begin();
iter != enum_generators_.end(); ++iter) {
(*iter)->GenerateHeader(printer);
}
- for (vector<MessageGenerator *>::iterator iter = message_generators_.begin();
+ for (std::vector<MessageGenerator *>::iterator iter = message_generators_.begin();
iter != message_generators_.end(); ++iter) {
(*iter)->GenerateEnumHeader(printer);
}
@@ -283,7 +323,7 @@ void FileGenerator::GenerateHeader(io::Printer *printer) {
"@interface $root_class_name$ (DynamicMethods)\n",
"root_class_name", root_class_name_);
- for (vector<ExtensionGenerator *>::iterator iter =
+ for (std::vector<ExtensionGenerator *>::iterator iter =
extension_generators_.begin();
iter != extension_generators_.end(); ++iter) {
(*iter)->GenerateMembersHeader(printer);
@@ -292,7 +332,7 @@ void FileGenerator::GenerateHeader(io::Printer *printer) {
printer->Print("@end\n\n");
} // extension_generators_.size() > 0
- for (vector<MessageGenerator *>::iterator iter = message_generators_.begin();
+ for (std::vector<MessageGenerator *>::iterator iter = message_generators_.begin();
iter != message_generators_.end(); ++iter) {
(*iter)->GenerateMessageHeader(printer);
}
@@ -309,15 +349,25 @@ 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_)) {
+ printer->Print(
+ "#import <stdatomic.h>\n"
+ "\n");
+ }
- vector<const FileDescriptor*> deps_with_extensions;
+ std::vector<const FileDescriptor*> deps_with_extensions;
CollectMinimalFileDepsContainingExtensions(file_, &deps_with_extensions);
{
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.
@@ -341,7 +391,7 @@ void FileGenerator::GenerateSource(io::Printer *printer) {
// imported so it can get merged into the root's extensions registry.
// See the Note by CollectMinimalFileDepsContainingExtensions before
// changing this.
- for (vector<const FileDescriptor *>::iterator iter =
+ for (std::vector<const FileDescriptor *>::iterator iter =
deps_with_extensions.begin();
iter != deps_with_extensions.end(); ++iter) {
if (!IsDirectDependency(*iter, file_)) {
@@ -353,7 +403,7 @@ void FileGenerator::GenerateSource(io::Printer *printer) {
}
bool includes_oneof = false;
- for (vector<MessageGenerator *>::iterator iter = message_generators_.begin();
+ for (std::vector<MessageGenerator *>::iterator iter = message_generators_.begin();
iter != message_generators_.end(); ++iter) {
if ((*iter)->IncludesOneOfDefinition()) {
includes_oneof = true;
@@ -406,12 +456,12 @@ void FileGenerator::GenerateSource(io::Printer *printer) {
printer->Print(
"static GPBExtensionDescription descriptions[] = {\n");
printer->Indent();
- for (vector<ExtensionGenerator *>::iterator iter =
+ for (std::vector<ExtensionGenerator *>::iterator iter =
extension_generators_.begin();
iter != extension_generators_.end(); ++iter) {
(*iter)->GenerateStaticVariablesInitialization(printer);
}
- for (vector<MessageGenerator *>::iterator iter =
+ for (std::vector<MessageGenerator *>::iterator iter =
message_generators_.begin();
iter != message_generators_.end(); ++iter) {
(*iter)->GenerateStaticVariablesInitialization(printer);
@@ -435,7 +485,7 @@ void FileGenerator::GenerateSource(io::Printer *printer) {
} else {
printer->Print(
"// Merge in the imports (direct or indirect) that defined extensions.\n");
- for (vector<const FileDescriptor *>::iterator iter =
+ for (std::vector<const FileDescriptor *>::iterator iter =
deps_with_extensions.begin();
iter != deps_with_extensions.end(); ++iter) {
const string root_class_name(FileClassName((*iter)));
@@ -511,11 +561,11 @@ void FileGenerator::GenerateSource(io::Printer *printer) {
"\n");
}
- for (vector<EnumGenerator *>::iterator iter = enum_generators_.begin();
+ for (std::vector<EnumGenerator *>::iterator iter = enum_generators_.begin();
iter != enum_generators_.end(); ++iter) {
(*iter)->GenerateSource(printer);
}
- for (vector<MessageGenerator *>::iterator iter = message_generators_.begin();
+ for (std::vector<MessageGenerator *>::iterator iter = message_generators_.begin();
iter != message_generators_.end(); ++iter) {
(*iter)->GenerateSource(printer);
}
@@ -531,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"
@@ -540,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"
@@ -547,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 a60a6885..1754fc0a 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_file.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_file.h
@@ -66,15 +66,16 @@ class FileGenerator {
private:
const FileDescriptor* file_;
string root_class_name_;
+ bool is_bundled_proto_;
- vector<EnumGenerator*> enum_generators_;
- vector<MessageGenerator*> message_generators_;
- vector<ExtensionGenerator*> extension_generators_;
+ std::vector<EnumGenerator*> enum_generators_;
+ std::vector<MessageGenerator*> message_generators_;
+ std::vector<ExtensionGenerator*> extension_generators_;
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 36407467..e0597cc7 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_generator.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_generator.cc
@@ -57,7 +57,7 @@ bool ObjectiveCGenerator::Generate(const FileDescriptor* file,
return false;
}
-bool ObjectiveCGenerator::GenerateAll(const vector<const FileDescriptor*>& files,
+bool ObjectiveCGenerator::GenerateAll(const std::vector<const FileDescriptor*>& files,
const string& parameter,
GeneratorContext* context,
string* error) const {
@@ -71,7 +71,7 @@ bool ObjectiveCGenerator::GenerateAll(const vector<const FileDescriptor*>& files
Options generation_options;
- vector<pair<string, string> > options;
+ std::vector<std::pair<string, string> > options;
ParseGeneratorParameter(parameter, &options);
for (int i = 0; i < options.size(); i++) {
if (options[i].first == "expected_prefixes_path") {
@@ -142,7 +142,7 @@ bool ObjectiveCGenerator::GenerateAll(const vector<const FileDescriptor*>& files
// 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 vector<const FileDescriptor*>& files
// 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_generator.h b/src/google/protobuf/compiler/objectivec/objectivec_generator.h
index b1723318..3e43f732 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_generator.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_generator.h
@@ -56,7 +56,7 @@ class LIBPROTOC_EXPORT ObjectiveCGenerator : public CodeGenerator {
const string& parameter,
GeneratorContext* context,
string* error) const;
- bool GenerateAll(const vector<const FileDescriptor*>& files,
+ bool GenerateAll(const std::vector<const FileDescriptor*>& files,
const string& parameter,
GeneratorContext* context,
string* error) const;
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
index 14715ef6..df71c8bb 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
@@ -100,7 +100,7 @@ bool ascii_isnewline(char c) {
// Do not expose this outside of helpers, stick to having functions for specific
// cases (ClassName(), FieldName()), so there is always consistent suffix rules.
string UnderscoresToCamelCase(const string& input, bool first_capitalized) {
- vector<string> values;
+ std::vector<string> values;
string current;
bool last_char_was_number = false;
@@ -141,7 +141,7 @@ string UnderscoresToCamelCase(const string& input, bool first_capitalized) {
string result;
bool first_segment_forces_upper = false;
- for (vector<string>::iterator i = values.begin(); i != values.end(); ++i) {
+ for (std::vector<string>::iterator i = values.begin(); i != values.end(); ++i) {
string value = *i;
bool all_upper = (kUpperSegments.count(value) > 0);
if (all_upper && (result.length() == 0)) {
@@ -864,7 +864,7 @@ bool HasNonZeroDefaultValue(const FieldDescriptor* field) {
}
string BuildFlagsString(const FlagType flag_type,
- const vector<string>& strings) {
+ const std::vector<string>& strings) {
if (strings.size() == 0) {
return GetZeroEnumNameForFlagType(flag_type);
} else if (strings.size() == 1) {
@@ -886,7 +886,7 @@ string BuildCommentsString(const SourceLocation& location,
const string& comments = location.leading_comments.empty()
? location.trailing_comments
: location.leading_comments;
- vector<string> lines;
+ std::vector<string> lines;
SplitStringAllowEmpty(comments, "\n", &lines);
while (!lines.empty() && lines.back().empty()) {
lines.pop_back();
@@ -1156,7 +1156,7 @@ bool ValidateObjCClassPrefix(
} // namespace
-bool ValidateObjCClassPrefixes(const vector<const FileDescriptor*>& files,
+bool ValidateObjCClassPrefixes(const std::vector<const FileDescriptor*>& files,
const Options& generation_options,
string* out_error) {
// Load the expected package prefixes, if available, to validate against.
@@ -1187,7 +1187,7 @@ TextFormatDecodeData::~TextFormatDecodeData() { }
void TextFormatDecodeData::AddString(int32 key,
const string& input_for_decode,
const string& desired_output) {
- for (vector<DataEntry>::const_iterator i = entries_.begin();
+ for (std::vector<DataEntry>::const_iterator i = entries_.begin();
i != entries_.end(); ++i) {
if (i->first == key) {
std::cerr << "error: duplicate key (" << key
@@ -1211,7 +1211,7 @@ string TextFormatDecodeData::Data() const {
io::CodedOutputStream output_stream(&data_outputstream);
output_stream.WriteVarint32(num_entries());
- for (vector<DataEntry>::const_iterator i = entries_.begin();
+ for (std::vector<DataEntry>::const_iterator i = entries_.begin();
i != entries_.end(); ++i) {
output_stream.WriteVarint32(i->first);
output_stream.WriteString(i->second);
@@ -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;
}
@@ -1561,7 +1568,7 @@ void ImportWriter::Print(io::Printer* printer) const {
printer->Print(
"#if $cpp_symbol$\n",
"cpp_symbol", cpp_symbol);
- for (vector<string>::const_iterator iter = protobuf_framework_imports_.begin();
+ for (std::vector<string>::const_iterator iter = protobuf_framework_imports_.begin();
iter != protobuf_framework_imports_.end(); ++iter) {
printer->Print(
" #import <$framework_name$/$header$>\n",
@@ -1570,7 +1577,7 @@ void ImportWriter::Print(io::Printer* printer) const {
}
printer->Print(
"#else\n");
- for (vector<string>::const_iterator iter = protobuf_non_framework_imports_.begin();
+ for (std::vector<string>::const_iterator iter = protobuf_non_framework_imports_.begin();
iter != protobuf_non_framework_imports_.end(); ++iter) {
printer->Print(
" #import \"$header$\"\n",
@@ -1587,10 +1594,10 @@ void ImportWriter::Print(io::Printer* printer) const {
printer->Print("\n");
}
- for (vector<string>::const_iterator iter = other_framework_imports_.begin();
+ for (std::vector<string>::const_iterator iter = other_framework_imports_.begin();
iter != other_framework_imports_.end(); ++iter) {
printer->Print(
- " #import <$header$>\n",
+ "#import <$header$>\n",
"header", *iter);
}
@@ -1602,10 +1609,10 @@ void ImportWriter::Print(io::Printer* printer) const {
printer->Print("\n");
}
- for (vector<string>::const_iterator iter = other_imports_.begin();
+ for (std::vector<string>::const_iterator iter = other_imports_.begin();
iter != other_imports_.end(); ++iter) {
printer->Print(
- " #import \"$header$\"\n",
+ "#import \"$header$\"\n",
"header", *iter);
}
}
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
index daea7609..8999aa59 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
@@ -190,7 +190,7 @@ string LIBPROTOC_EXPORT GPBGenericValueFieldName(const FieldDescriptor* field);
string LIBPROTOC_EXPORT DefaultValue(const FieldDescriptor* field);
bool LIBPROTOC_EXPORT HasNonZeroDefaultValue(const FieldDescriptor* field);
-string LIBPROTOC_EXPORT BuildFlagsString(const FlagType type, const vector<string>& strings);
+string LIBPROTOC_EXPORT BuildFlagsString(const FlagType type, const std::vector<string>& strings);
// Builds HeaderDoc/appledoc style comments out of the comments in the .proto
// file.
@@ -210,7 +210,7 @@ bool LIBPROTOC_EXPORT IsProtobufLibraryBundledProtoFile(const FileDescriptor* fi
// Checks the prefix for the given files and outputs any warnings as needed. If
// there are flat out errors, then out_error is filled in with the first error
// and the result is false.
-bool LIBPROTOC_EXPORT ValidateObjCClassPrefixes(const vector<const FileDescriptor*>& files,
+bool LIBPROTOC_EXPORT ValidateObjCClassPrefixes(const std::vector<const FileDescriptor*>& files,
const Options& generation_options,
string* out_error);
@@ -233,7 +233,7 @@ class LIBPROTOC_EXPORT TextFormatDecodeData {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TextFormatDecodeData);
typedef std::pair<int32, string> DataEntry;
- vector<DataEntry> entries_;
+ std::vector<DataEntry> entries_;
};
// Helper for parsing simple files.
@@ -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,13 +276,14 @@ 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_;
- vector<string> protobuf_framework_imports_;
- vector<string> protobuf_non_framework_imports_;
- vector<string> other_framework_imports_;
- vector<string> other_imports_;
+ std::vector<string> protobuf_framework_imports_;
+ std::vector<string> protobuf_non_framework_imports_;
+ std::vector<string> other_framework_imports_;
+ std::vector<string> other_imports_;
};
} // namespace objectivec
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 4f22e290..83888854 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_message.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_message.cc
@@ -220,13 +220,13 @@ MessageGenerator::~MessageGenerator() {
void MessageGenerator::GenerateStaticVariablesInitialization(
io::Printer* printer) {
- for (vector<ExtensionGenerator*>::iterator iter =
+ for (std::vector<ExtensionGenerator*>::iterator iter =
extension_generators_.begin();
iter != extension_generators_.end(); ++iter) {
(*iter)->GenerateStaticVariablesInitialization(printer);
}
- for (vector<MessageGenerator*>::iterator iter =
+ for (std::vector<MessageGenerator*>::iterator iter =
nested_message_generators_.begin();
iter != nested_message_generators_.end(); ++iter) {
(*iter)->GenerateStaticVariablesInitialization(printer);
@@ -242,7 +242,7 @@ void MessageGenerator::DetermineForwardDeclarations(std::set<string>* fwd_decls)
}
}
- for (vector<MessageGenerator*>::iterator iter =
+ for (std::vector<MessageGenerator*>::iterator iter =
nested_message_generators_.begin();
iter != nested_message_generators_.end(); ++iter) {
(*iter)->DetermineForwardDeclarations(fwd_decls);
@@ -254,7 +254,7 @@ bool MessageGenerator::IncludesOneOfDefinition() const {
return true;
}
- for (vector<MessageGenerator*>::const_iterator iter =
+ for (std::vector<MessageGenerator*>::const_iterator iter =
nested_message_generators_.begin();
iter != nested_message_generators_.end(); ++iter) {
if ((*iter)->IncludesOneOfDefinition()) {
@@ -266,12 +266,12 @@ bool MessageGenerator::IncludesOneOfDefinition() const {
}
void MessageGenerator::GenerateEnumHeader(io::Printer* printer) {
- for (vector<EnumGenerator*>::iterator iter = enum_generators_.begin();
+ for (std::vector<EnumGenerator*>::iterator iter = enum_generators_.begin();
iter != enum_generators_.end(); ++iter) {
(*iter)->GenerateHeader(printer);
}
- for (vector<MessageGenerator*>::iterator iter =
+ for (std::vector<MessageGenerator*>::iterator iter =
nested_message_generators_.begin();
iter != nested_message_generators_.end(); ++iter) {
(*iter)->GenerateEnumHeader(printer);
@@ -280,13 +280,13 @@ void MessageGenerator::GenerateEnumHeader(io::Printer* printer) {
void MessageGenerator::GenerateExtensionRegistrationSource(
io::Printer* printer) {
- for (vector<ExtensionGenerator*>::iterator iter =
+ for (std::vector<ExtensionGenerator*>::iterator iter =
extension_generators_.begin();
iter != extension_generators_.end(); ++iter) {
(*iter)->GenerateRegistrationSource(printer);
}
- for (vector<MessageGenerator*>::iterator iter =
+ for (std::vector<MessageGenerator*>::iterator iter =
nested_message_generators_.begin();
iter != nested_message_generators_.end(); ++iter) {
(*iter)->GenerateExtensionRegistrationSource(printer);
@@ -296,7 +296,7 @@ void MessageGenerator::GenerateExtensionRegistrationSource(
void MessageGenerator::GenerateMessageHeader(io::Printer* printer) {
// This a a map entry message, just recurse and do nothing directly.
if (IsMapEntryMessage(descriptor_)) {
- for (vector<MessageGenerator*>::iterator iter =
+ for (std::vector<MessageGenerator*>::iterator iter =
nested_message_generators_.begin();
iter != nested_message_generators_.end(); ++iter) {
(*iter)->GenerateMessageHeader(printer);
@@ -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",
@@ -326,7 +326,7 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) {
printer->Print("};\n\n");
}
- for (vector<OneofGenerator*>::iterator iter = oneof_generators_.begin();
+ for (std::vector<OneofGenerator*>::iterator iter = oneof_generators_.begin();
iter != oneof_generators_.end(); ++iter) {
(*iter)->GenerateCaseEnum(printer);
}
@@ -345,7 +345,7 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) {
"deprecated_attribute", deprecated_attribute_,
"comments", message_comments);
- vector<char> seen_oneofs(descriptor_->oneof_decl_count(), 0);
+ std::vector<char> seen_oneofs(descriptor_->oneof_decl_count(), 0);
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
if (field->containing_oneof() != NULL) {
@@ -367,7 +367,7 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) {
}
if (!oneof_generators_.empty()) {
- for (vector<OneofGenerator*>::iterator iter = oneof_generators_.begin();
+ for (std::vector<OneofGenerator*>::iterator iter = oneof_generators_.begin();
iter != oneof_generators_.end(); ++iter) {
(*iter)->GenerateClearFunctionDeclaration(printer);
}
@@ -377,7 +377,7 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) {
if (descriptor_->extension_count() > 0) {
printer->Print("@interface $classname$ (DynamicMethods)\n\n",
"classname", class_name_);
- for (vector<ExtensionGenerator*>::iterator iter =
+ for (std::vector<ExtensionGenerator*>::iterator iter =
extension_generators_.begin();
iter != extension_generators_.end(); ++iter) {
(*iter)->GenerateMembersHeader(printer);
@@ -385,7 +385,7 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) {
printer->Print("@end\n\n");
}
- for (vector<MessageGenerator*>::iterator iter =
+ for (std::vector<MessageGenerator*>::iterator iter =
nested_message_generators_.begin();
iter != nested_message_generators_.end(); ++iter) {
(*iter)->GenerateMessageHeader(printer);
@@ -410,7 +410,7 @@ void MessageGenerator::GenerateSource(io::Printer* printer) {
printer->Print("@implementation $classname$\n\n",
"classname", class_name_);
- for (vector<OneofGenerator*>::iterator iter = oneof_generators_.begin();
+ for (std::vector<OneofGenerator*>::iterator iter = oneof_generators_.begin();
iter != oneof_generators_.end(); ++iter) {
(*iter)->GeneratePropertyImplementation(printer);
}
@@ -420,12 +420,12 @@ 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_));
- vector<const Descriptor::ExtensionRange*> sorted_extensions;
+ std::vector<const Descriptor::ExtensionRange*> sorted_extensions;
for (int i = 0; i < descriptor_->extension_range_count(); ++i) {
sorted_extensions.push_back(descriptor_->extension_range(i));
}
@@ -448,7 +448,7 @@ void MessageGenerator::GenerateSource(io::Printer* printer) {
sizeof_has_storage = 1;
}
// Tell all the fields the oneof base.
- for (vector<OneofGenerator*>::iterator iter = oneof_generators_.begin();
+ for (std::vector<OneofGenerator*>::iterator iter = oneof_generators_.begin();
iter != oneof_generators_.end(); ++iter) {
(*iter)->SetOneofIndexBase(sizeof_has_storage);
}
@@ -548,7 +548,7 @@ void MessageGenerator::GenerateSource(io::Printer* printer) {
if (oneof_generators_.size() != 0) {
printer->Print(
" static const char *oneofs[] = {\n");
- for (vector<OneofGenerator*>::iterator iter = oneof_generators_.begin();
+ for (std::vector<OneofGenerator*>::iterator iter = oneof_generators_.begin();
iter != oneof_generators_.end(); ++iter) {
printer->Print(
" \"$name$\",\n",
@@ -623,18 +623,18 @@ void MessageGenerator::GenerateSource(io::Printer* printer) {
.GenerateCFunctionImplementations(printer);
}
- for (vector<OneofGenerator*>::iterator iter = oneof_generators_.begin();
+ for (std::vector<OneofGenerator*>::iterator iter = oneof_generators_.begin();
iter != oneof_generators_.end(); ++iter) {
(*iter)->GenerateClearFunctionImplementation(printer);
}
}
- for (vector<EnumGenerator*>::iterator iter = enum_generators_.begin();
+ for (std::vector<EnumGenerator*>::iterator iter = enum_generators_.begin();
iter != enum_generators_.end(); ++iter) {
(*iter)->GenerateSource(printer);
}
- for (vector<MessageGenerator*>::iterator iter =
+ for (std::vector<MessageGenerator*>::iterator iter =
nested_message_generators_.begin();
iter != nested_message_generators_.end(); ++iter) {
(*iter)->GenerateSource(printer);
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_message.h b/src/google/protobuf/compiler/objectivec/objectivec_message.h
index 8f317ac0..2de03f12 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_message.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_message.h
@@ -86,10 +86,10 @@ class MessageGenerator {
FieldGeneratorMap field_generators_;
const string class_name_;
const string deprecated_attribute_;
- vector<ExtensionGenerator*> extension_generators_;
- vector<EnumGenerator*> enum_generators_;
- vector<MessageGenerator*> nested_message_generators_;
- vector<OneofGenerator*> oneof_generators_;
+ std::vector<ExtensionGenerator*> extension_generators_;
+ std::vector<EnumGenerator*> enum_generators_;
+ std::vector<MessageGenerator*> nested_message_generators_;
+ std::vector<OneofGenerator*> oneof_generators_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator);
};
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 dd4392c2..a37380e3 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);
@@ -270,11 +268,12 @@ 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 = "";
if (proto_file == kEmptyFile) {
return kEmptyMetadataFile;
@@ -292,17 +291,36 @@ 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) {
+ 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);
+ }
}
// Append file name.
+ 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;
+ }
result += RenameEmpty(UnderscoresToCamelCase(
- file_no_suffix.substr(start_index, first_index - start_index), true));
+ file_no_suffix.substr(file_name_start, first_index - file_name_start), true));
return result += ".php";
}
@@ -853,7 +871,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 +965,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 +975,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));
@@ -983,7 +1001,7 @@ void GenerateMetadataFile(const FileDescriptor* file,
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::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(filename));
io::Printer printer(output.get(), '^');
@@ -1042,7 +1060,7 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message,
}
std::string filename = GeneratedMessageFileName(message, is_descriptor);
- scoped_ptr<io::ZeroCopyOutputStream> output(
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(filename));
io::Printer printer(output.get(), '^');
@@ -1096,7 +1114,7 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message,
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"
@@ -1143,7 +1161,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(), '^');
@@ -1265,7 +1283,7 @@ static void GenerateDocCommentBodyForLocation(
// HTML-escape them so that they don't accidentally close the doc comment.
comments = EscapePhpdoc(comments);
- vector<string> lines = Split(comments, "\n");
+ std::vector<string> lines = Split(comments, "\n");
while (!lines.empty() && lines.back().empty()) {
lines.pop_back();
}
diff --git a/src/google/protobuf/compiler/php/php_generator.h b/src/google/protobuf/compiler/php/php_generator.h
index 67e70bc7..54a95ef5 100644
--- a/src/google/protobuf/compiler/php/php_generator.h
+++ b/src/google/protobuf/compiler/php/php_generator.h
@@ -54,9 +54,12 @@ class LIBPROTOC_EXPORT Generator
// To skip reserved keywords in php, some generated classname are prefixed.
// Other code generators may need following API to figure out the actual
// classname.
-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 80c8c625..ef52def3 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];
@@ -199,15 +185,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
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 ::google::protobuf::internal::once_flag once;
+ ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
@@ -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,17 +301,10 @@ 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();
}
-Version* Version::New(::google::protobuf::Arena* arena) const {
- Version* n = new Version;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
-}
void Version::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.Version)
@@ -341,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_.UnsafeRawStringPointer())->clear();
+ suffix_.ClearNonDefaultToEmptyNoArena();
}
if (cached_has_bits & 14u) {
::memset(&major_, 0, static_cast<size_t>(
@@ -359,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)) {
@@ -562,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;
}
@@ -633,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 {
@@ -666,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)
}
@@ -676,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_);
@@ -693,7 +661,6 @@ CodeGeneratorRequest::CodeGeneratorRequest(const CodeGeneratorRequest& from)
}
void CodeGeneratorRequest::SharedCtor() {
- _cached_size_ = 0;
parameter_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
compiler_version_ = NULL;
}
@@ -709,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();
@@ -719,17 +684,10 @@ 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();
}
-CodeGeneratorRequest* CodeGeneratorRequest::New(::google::protobuf::Arena* arena) const {
- CodeGeneratorRequest* n = new CodeGeneratorRequest;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
-}
void CodeGeneratorRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.CodeGeneratorRequest)
@@ -742,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_.UnsafeRawStringPointer())->clear();
+ parameter_.ClearNonDefaultToEmptyNoArena();
}
if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(compiler_version_ != NULL);
@@ -760,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)) {
@@ -813,7 +770,8 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream(
case 15: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_proto_file()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_proto_file()));
} else {
goto handle_unusual;
}
@@ -870,14 +828,16 @@ void CodeGeneratorRequest::SerializeWithCachedSizes(
// optional .google.protobuf.compiler.Version compiler_version = 3;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, *this->compiler_version_, output);
+ 3, this->_internal_compiler_version(), output);
}
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->proto_file_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 15, this->proto_file(static_cast<int>(i)), output);
+ 15,
+ this->proto_file(static_cast<int>(i)),
+ output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -920,7 +880,7 @@ void CodeGeneratorRequest::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 3, *this->compiler_version_, deterministic, target);
+ 3, this->_internal_compiler_version(), deterministic, target);
}
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
@@ -979,14 +939,12 @@ size_t CodeGeneratorRequest::ByteSizeLong() const {
if (has_compiler_version()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
- *this->compiler_version_);
+ *compiler_version_);
}
}
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;
}
@@ -1051,13 +1009,13 @@ void CodeGeneratorRequest::Swap(CodeGeneratorRequest* other) {
}
void CodeGeneratorRequest::InternalSwap(CodeGeneratorRequest* other) {
using std::swap;
- file_to_generate_.InternalSwap(&other->file_to_generate_);
- proto_file_.InternalSwap(&other->proto_file_);
- parameter_.Swap(&other->parameter_);
+ file_to_generate_.InternalSwap(CastToBase(&other->file_to_generate_));
+ CastToBase(&proto_file_)->InternalSwap(CastToBase(&other->proto_file_));
+ parameter_.Swap(&other->parameter_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
swap(compiler_version_, other->compiler_version_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata CodeGeneratorRequest::GetMetadata() const {
@@ -1078,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()) {
@@ -1106,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());
@@ -1124,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();
@@ -1134,17 +1087,10 @@ 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();
}
-CodeGeneratorResponse_File* CodeGeneratorResponse_File::New(::google::protobuf::Arena* arena) const {
- CodeGeneratorResponse_File* n = new CodeGeneratorResponse_File;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
-}
void CodeGeneratorResponse_File::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.CodeGeneratorResponse.File)
@@ -1155,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_.UnsafeRawStringPointer())->clear();
+ name_.ClearNonDefaultToEmptyNoArena();
}
if (cached_has_bits & 0x00000002u) {
- GOOGLE_DCHECK(!insertion_point_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*insertion_point_.UnsafeRawStringPointer())->clear();
+ insertion_point_.ClearNonDefaultToEmptyNoArena();
}
if (cached_has_bits & 0x00000004u) {
- GOOGLE_DCHECK(!content_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*content_.UnsafeRawStringPointer())->clear();
+ content_.ClearNonDefaultToEmptyNoArena();
}
}
_has_bits_.Clear();
@@ -1177,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)) {
@@ -1375,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;
}
@@ -1444,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 {
@@ -1469,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)
}
@@ -1479,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());
@@ -1490,7 +1431,6 @@ CodeGeneratorResponse::CodeGeneratorResponse(const CodeGeneratorResponse& from)
}
void CodeGeneratorResponse::SharedCtor() {
- _cached_size_ = 0;
error_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -1504,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();
@@ -1514,17 +1452,10 @@ 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();
}
-CodeGeneratorResponse* CodeGeneratorResponse::New(::google::protobuf::Arena* arena) const {
- CodeGeneratorResponse* n = new CodeGeneratorResponse;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
-}
void CodeGeneratorResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.CodeGeneratorResponse)
@@ -1535,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_.UnsafeRawStringPointer())->clear();
+ error_.ClearNonDefaultToEmptyNoArena();
}
_has_bits_.Clear();
_internal_metadata_.Clear();
@@ -1548,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)) {
@@ -1572,7 +1502,8 @@ bool CodeGeneratorResponse::MergePartialFromCodedStream(
case 15: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_file()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_file()));
} else {
goto handle_unusual;
}
@@ -1620,7 +1551,9 @@ void CodeGeneratorResponse::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->file_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 15, this->file(static_cast<int>(i)), output);
+ 15,
+ this->file(static_cast<int>(i)),
+ output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -1693,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;
}
@@ -1752,11 +1683,11 @@ void CodeGeneratorResponse::Swap(CodeGeneratorResponse* other) {
}
void CodeGeneratorResponse::InternalSwap(CodeGeneratorResponse* other) {
using std::swap;
- file_.InternalSwap(&other->file_);
- error_.Swap(&other->error_);
+ CastToBase(&file_)->InternalSwap(CastToBase(&other->file_));
+ error_.Swap(&other->error_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata CodeGeneratorResponse::GetMetadata() const {
@@ -1769,5 +1700,21 @@ void CodeGeneratorResponse::InternalSwap(CodeGeneratorResponse* other) {
} // namespace compiler
} // namespace protobuf
} // namespace google
+namespace google {
+namespace protobuf {
+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::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorRequest >(Arena* arena) {
+ return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorRequest >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse_File >(Arena* arena) {
+ return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorResponse_File >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse >(Arena* arena) {
+ return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorResponse >(arena);
+}
+} // namespace protobuf
+} // namespace google
// @@protoc_insertion_point(global_scope)
diff --git a/src/google/protobuf/compiler/plugin.pb.h b/src/google/protobuf/compiler/plugin.pb.h
index ef1cfb93..5ad6b4d3 100644
--- a/src/google/protobuf/compiler/plugin.pb.h
+++ b/src/google/protobuf/compiler/plugin.pb.h
@@ -1,8 +1,8 @@
// 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>
@@ -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,6 +72,14 @@ LIBPROTOC_EXPORT extern VersionDefaultTypeInternal _Version_default_instance_;
} // namespace google
namespace google {
namespace protobuf {
+template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorRequest>(Arena*);
+template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse>(Arena*);
+template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse_File>(Arena*);
+template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage<::google::protobuf::compiler::Version>(Arena*);
+} // namespace protobuf
+} // namespace google
+namespace google {
+namespace protobuf {
namespace compiler {
// ===================================================================
@@ -129,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);
@@ -139,28 +135,33 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_
// implements Message ----------------------------------------------
- inline Version* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Version* New() const final {
+ return CreateMaybeMessage<Version>(NULL);
+ }
- Version* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Version* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Version>(arena);
+ }
+ 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 {
@@ -171,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 ----------------------------------------------------
@@ -226,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();
};
// -------------------------------------------------------------------
@@ -277,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);
@@ -287,28 +287,33 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
// implements Message ----------------------------------------------
- inline CodeGeneratorRequest* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline CodeGeneratorRequest* New() const final {
+ return CreateMaybeMessage<CodeGeneratorRequest>(NULL);
+ }
- CodeGeneratorRequest* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ CodeGeneratorRequest* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<CodeGeneratorRequest>(arena);
+ }
+ 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 {
@@ -319,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 ----------------------------------------------------
@@ -351,11 +356,11 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
int proto_file_size() const;
void clear_proto_file();
static const int kProtoFileFieldNumber = 15;
- const ::google::protobuf::FileDescriptorProto& proto_file(int index) const;
::google::protobuf::FileDescriptorProto* mutable_proto_file(int index);
- ::google::protobuf::FileDescriptorProto* add_proto_file();
::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >*
mutable_proto_file();
+ const ::google::protobuf::FileDescriptorProto& proto_file(int index) const;
+ ::google::protobuf::FileDescriptorProto* add_proto_file();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >&
proto_file() const;
@@ -378,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();
@@ -392,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();
};
// -------------------------------------------------------------------
@@ -443,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);
@@ -453,28 +460,33 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
// implements Message ----------------------------------------------
- inline CodeGeneratorResponse_File* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline CodeGeneratorResponse_File* New() const final {
+ return CreateMaybeMessage<CodeGeneratorResponse_File>(NULL);
+ }
- CodeGeneratorResponse_File* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ CodeGeneratorResponse_File* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<CodeGeneratorResponse_File>(arena);
+ }
+ 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 {
@@ -485,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 ----------------------------------------------------
@@ -547,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();
};
// -------------------------------------------------------------------
@@ -597,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);
@@ -607,28 +618,33 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
// implements Message ----------------------------------------------
- inline CodeGeneratorResponse* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline CodeGeneratorResponse* New() const final {
+ return CreateMaybeMessage<CodeGeneratorResponse>(NULL);
+ }
- CodeGeneratorResponse* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ CodeGeneratorResponse* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<CodeGeneratorResponse>(arena);
+ }
+ 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 {
@@ -639,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 ----------------------------------------------------
@@ -651,11 +667,11 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
int file_size() const;
void clear_file();
static const int kFileFieldNumber = 15;
- const ::google::protobuf::compiler::CodeGeneratorResponse_File& file(int index) const;
::google::protobuf::compiler::CodeGeneratorResponse_File* mutable_file(int index);
- ::google::protobuf::compiler::CodeGeneratorResponse_File* add_file();
::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File >*
mutable_file();
+ const ::google::protobuf::compiler::CodeGeneratorResponse_File& file(int index) const;
+ ::google::protobuf::compiler::CodeGeneratorResponse_File* add_file();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File >&
file() const;
@@ -681,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();
};
// ===================================================================
@@ -820,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) {
@@ -956,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) {
@@ -973,23 +994,23 @@ inline void CodeGeneratorRequest::set_allocated_parameter(::std::string* paramet
inline int CodeGeneratorRequest::proto_file_size() const {
return proto_file_.size();
}
-inline const ::google::protobuf::FileDescriptorProto& CodeGeneratorRequest::proto_file(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.proto_file)
- return proto_file_.Get(index);
-}
inline ::google::protobuf::FileDescriptorProto* CodeGeneratorRequest::mutable_proto_file(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.proto_file)
return proto_file_.Mutable(index);
}
-inline ::google::protobuf::FileDescriptorProto* CodeGeneratorRequest::add_proto_file() {
- // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.proto_file)
- return proto_file_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >*
CodeGeneratorRequest::mutable_proto_file() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.compiler.CodeGeneratorRequest.proto_file)
return &proto_file_;
}
+inline const ::google::protobuf::FileDescriptorProto& CodeGeneratorRequest::proto_file(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.proto_file)
+ return proto_file_.Get(index);
+}
+inline ::google::protobuf::FileDescriptorProto* CodeGeneratorRequest::add_proto_file() {
+ // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.proto_file)
+ return proto_file_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >&
CodeGeneratorRequest::proto_file() const {
// @@protoc_insertion_point(field_list:google.protobuf.compiler.CodeGeneratorRequest.proto_file)
@@ -1010,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)
@@ -1026,7 +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_ = new ::google::protobuf::compiler::Version;
+ 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_;
@@ -1104,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) {
@@ -1167,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) {
@@ -1230,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) {
@@ -1297,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) {
@@ -1317,23 +1354,23 @@ inline int CodeGeneratorResponse::file_size() const {
inline void CodeGeneratorResponse::clear_file() {
file_.Clear();
}
-inline const ::google::protobuf::compiler::CodeGeneratorResponse_File& CodeGeneratorResponse::file(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.file)
- return file_.Get(index);
-}
inline ::google::protobuf::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::mutable_file(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.file)
return file_.Mutable(index);
}
-inline ::google::protobuf::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::add_file() {
- // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorResponse.file)
- return file_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File >*
CodeGeneratorResponse::mutable_file() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.compiler.CodeGeneratorResponse.file)
return &file_;
}
+inline const ::google::protobuf::compiler::CodeGeneratorResponse_File& CodeGeneratorResponse::file(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.file)
+ return file_.Get(index);
+}
+inline ::google::protobuf::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::add_file() {
+ // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorResponse.file)
+ return file_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File >&
CodeGeneratorResponse::file() const {
// @@protoc_insertion_point(field_list:google.protobuf.compiler.CodeGeneratorResponse.file)
@@ -1358,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..02aa61d1 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 {
@@ -488,7 +486,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 3f54b848..dae24f9e 100644
--- a/src/google/protobuf/descriptor.cc
+++ b/src/google/protobuf/descriptor.cc
@@ -32,29 +32,28 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
+#include <algorithm>
+#include <functional>
#include <google/protobuf/stubs/hash.h>
+#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 <algorithm>
-#include <limits>
+#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/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>
@@ -64,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>
@@ -346,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.
@@ -363,27 +363,25 @@ 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:
string prefix_;
};
-// A DescriptorPool contains a bunch of hash_maps to implement the
+// A DescriptorPool contains a bunch of hash-maps to implement the
// various Find*By*() methods. Since hashtable lookups are O(1), it's
-// most efficient to construct a fixed set of large hash_maps used by
+// most efficient to construct a fixed set of large hash-maps used by
// all objects in the pool rather than construct one or more small
-// hash_maps for each object.
+// hash-maps for each object.
//
-// The keys to these hash_maps are (parent, name) or (parent, number)
-// pairs. Unfortunately STL doesn't provide hash functions for pair<>,
-// so we must invent our own.
+// The keys to these hash-maps are (parent, name) or (parent, number) pairs.
//
// TODO(kenton): Use StringPiece rather than const char* in keys? It would
// be a lot cleaner but we'd just have to convert it back to const char*
@@ -398,12 +396,20 @@ struct PointerStringPairEqual {
}
};
+typedef std::pair<const Descriptor*, int> DescriptorIntPair;
+typedef std::pair<const EnumDescriptor*, int> EnumIntPair;
+
+#define HASH_MAP hash_map
+#define HASH_SET hash_set
+#define HASH_FXN hash
+
template<typename PairType>
struct PointerIntegerPairHash {
size_t operator()(const PairType& p) const {
- // FIXME(kenton): What is the best way to compute this hash? I have
- // no idea! This seems a bit better than an XOR.
- return reinterpret_cast<intptr_t>(p.first) * ((1 << 16) - 1) + p.second;
+ static const size_t prime1 = 16777499;
+ static const size_t prime2 = 16777619;
+ return reinterpret_cast<size_t>(p.first) * prime1 ^
+ static_cast<size_t>(p.second) * prime2;
}
#ifdef _MSC_VER
@@ -417,16 +423,12 @@ struct PointerIntegerPairHash {
}
};
-typedef std::pair<const Descriptor*, int> DescriptorIntPair;
-typedef std::pair<const EnumDescriptor*, int> EnumIntPair;
-
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
@@ -445,31 +447,37 @@ struct PointerStringPairHash {
const Symbol kNullSymbol;
-typedef hash_map<const char*, Symbol,
- hash<const char*>, streq>
- SymbolsByNameMap;
-typedef hash_map<PointerStringPair, Symbol,
- PointerStringPairHash, PointerStringPairEqual>
- SymbolsByParentMap;
-typedef hash_map<const char*, const FileDescriptor*,
- hash<const char*>, streq>
- FilesByNameMap;
-typedef hash_map<PointerStringPair, const FieldDescriptor*,
+typedef HASH_MAP<const char*, Symbol, HASH_FXN<const char*>, streq>
+ SymbolsByNameMap;
+
+typedef HASH_MAP<PointerStringPair, Symbol, PointerStringPairHash,
+ PointerStringPairEqual>
+ SymbolsByParentMap;
+
+typedef HASH_MAP<const char*, const FileDescriptor*, HASH_FXN<const char*>,
+ streq>
+ FilesByNameMap;
+
+typedef HASH_MAP<PointerStringPair, const FieldDescriptor*,
PointerStringPairHash, PointerStringPairEqual>
- FieldsByNameMap;
-typedef hash_map<DescriptorIntPair, const FieldDescriptor*,
- PointerIntegerPairHash<DescriptorIntPair> >
- FieldsByNumberMap;
-typedef hash_map<EnumIntPair, const EnumValueDescriptor*,
- PointerIntegerPairHash<EnumIntPair> >
- EnumValuesByNumberMap;
-// This is a map rather than a hash_map, since we use it to iterate
+ FieldsByNameMap;
+
+typedef HASH_MAP<DescriptorIntPair, const FieldDescriptor*,
+ PointerIntegerPairHash<DescriptorIntPair>,
+ std::equal_to<DescriptorIntPair> >
+ FieldsByNumberMap;
+
+typedef HASH_MAP<EnumIntPair, const EnumValueDescriptor*,
+ PointerIntegerPairHash<EnumIntPair>,
+ std::equal_to<EnumIntPair> >
+ EnumValuesByNumberMap;
+// This is a map rather than a hash-map, since we use it to iterate
// through all the extensions that extend a given Descriptor, and an
// ordered data structure that implements lower_bound is convenient
// for that.
typedef std::map<DescriptorIntPair, const FieldDescriptor*>
ExtensionsGroupedByDescriptorMap;
-typedef hash_map<string, const SourceCodeInfo_Location*> LocationsByPathMap;
+typedef HASH_MAP<string, const SourceCodeInfo_Location*> LocationsByPathMap;
std::set<string>* allowed_proto3_extendees_ = NULL;
GOOGLE_PROTOBUF_DECLARE_ONCE(allowed_proto3_extendees_init_);
@@ -564,17 +572,17 @@ class DescriptorPool::Tables {
// execution of the current public API call, but for compatibility with
// legacy clients, this is cleared at the beginning of each public API call.
// Not used when fallback_database_ == NULL.
- hash_set<string> known_bad_files_;
+ HASH_SET<string> known_bad_files_;
// A set of symbols which we have tried to load from the fallback database
// and encountered errors. We will not attempt to load them again during
// execution of the current public API call, but for compatibility with
// legacy clients, this is cleared at the beginning of each public API call.
- hash_set<string> known_bad_symbols_;
+ HASH_SET<string> known_bad_symbols_;
// The set of descriptors for which we've already loaded the full
// set of extensions numbers from fallback_database_.
- hash_set<const Descriptor*> extensions_loaded_from_db_;
+ HASH_SET<const Descriptor*> extensions_loaded_from_db_;
// -----------------------------------------------------------------
// Finding items.
@@ -787,14 +795,13 @@ class FileDescriptorTables {
};
DescriptorPool::Tables::Tables()
- // Start some hash_map and hash_set objects with a small # of buckets
+ // Start some hash-map and hash-set objects with a small # of buckets
: known_bad_files_(3),
known_bad_symbols_(3),
extensions_loaded_from_db_(3),
symbols_by_name_(3),
files_by_name_(3) {}
-
DescriptorPool::Tables::~Tables() {
GOOGLE_DCHECK(checkpoints_.empty());
// Note that the deletion order is important, since the destructors of some
@@ -948,8 +955,10 @@ inline Symbol FileDescriptorTables::FindNestedSymbolOfType(
Symbol DescriptorPool::Tables::FindByNameHelper(
const DescriptorPool* pool, const string& name) {
MutexLockMaybe lock(pool->mutex_);
- known_bad_symbols_.clear();
- known_bad_files_.clear();
+ if (pool->fallback_database_ != NULL) {
+ known_bad_symbols_.clear();
+ known_bad_files_.clear();
+ }
Symbol result = FindSymbol(name);
if (result.IsNull() && pool->underlay_ != NULL) {
@@ -1403,8 +1412,10 @@ void DescriptorPool::InternalAddGeneratedFile(
const FileDescriptor* DescriptorPool::FindFileByName(const string& name) const {
MutexLockMaybe lock(mutex_);
- tables_->known_bad_symbols_.clear();
- tables_->known_bad_files_.clear();
+ if (fallback_database_ != NULL) {
+ tables_->known_bad_symbols_.clear();
+ tables_->known_bad_files_.clear();
+ }
const FileDescriptor* result = tables_->FindFile(name);
if (result != NULL) return result;
if (underlay_ != NULL) {
@@ -1421,8 +1432,10 @@ const FileDescriptor* DescriptorPool::FindFileByName(const string& name) const {
const FileDescriptor* DescriptorPool::FindFileContainingSymbol(
const string& symbol_name) const {
MutexLockMaybe lock(mutex_);
- tables_->known_bad_symbols_.clear();
- tables_->known_bad_files_.clear();
+ if (fallback_database_ != NULL) {
+ tables_->known_bad_symbols_.clear();
+ tables_->known_bad_files_.clear();
+ }
Symbol result = tables_->FindSymbol(symbol_name);
if (!result.IsNull()) return result.GetFile();
if (underlay_ != NULL) {
@@ -1508,8 +1521,10 @@ const FieldDescriptor* DescriptorPool::FindExtensionByNumber(
}
}
MutexLockMaybe lock(mutex_);
- tables_->known_bad_symbols_.clear();
- tables_->known_bad_files_.clear();
+ if (fallback_database_ != NULL) {
+ tables_->known_bad_symbols_.clear();
+ tables_->known_bad_files_.clear();
+ }
const FieldDescriptor* result = tables_->FindExtension(extendee, number);
if (result != NULL) {
return result;
@@ -1531,8 +1546,10 @@ void DescriptorPool::FindAllExtensions(
const Descriptor* extendee,
std::vector<const FieldDescriptor*>* out) const {
MutexLockMaybe lock(mutex_);
- tables_->known_bad_symbols_.clear();
- tables_->known_bad_files_.clear();
+ if (fallback_database_ != NULL) {
+ tables_->known_bad_symbols_.clear();
+ tables_->known_bad_files_.clear();
+ }
// Initialize tables_->extensions_ from the fallback database first
// (but do this only once per descriptor).
@@ -1784,6 +1801,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
@@ -2051,13 +2077,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());
@@ -2288,7 +2308,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,
@@ -3098,15 +3118,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;
};
@@ -3273,7 +3296,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);
@@ -3283,7 +3306,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.
@@ -3372,13 +3396,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
@@ -3453,6 +3485,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_;
@@ -4070,24 +4112,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 =
@@ -4110,7 +4158,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));
}
}
@@ -4248,8 +4297,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 {
@@ -4447,6 +4497,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
@@ -4518,7 +4572,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(),
@@ -4539,7 +4594,7 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto,
}
}
- hash_set<string> reserved_name_set;
+ HASH_SET<string> reserved_name_set;
for (int i = 0; i < proto.reserved_name_size(); i++) {
const string& name = proto.reserved_name(i);
if (reserved_name_set.find(name) == reserved_name_set.end()) {
@@ -4898,7 +4953,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);
}
@@ -4932,8 +4988,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);
}
}
@@ -4985,7 +5049,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(),
@@ -5102,7 +5167,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(),
@@ -5114,18 +5180,18 @@ 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()));
}
}
}
- hash_set<string> reserved_name_set;
+ HASH_SET<string> reserved_name_set;
for (int i = 0; i < proto.reserved_name_size(); i++) {
const string& name = proto.reserved_name(i);
if (reserved_name_set.find(name) == reserved_name_set.end()) {
@@ -5179,7 +5245,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
@@ -5246,7 +5313,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(),
@@ -5274,7 +5342,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();
@@ -5643,13 +5712,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.
@@ -6244,6 +6315,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()->
@@ -6254,14 +6328,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;
@@ -6294,7 +6371,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
@@ -6340,6 +6417,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) {
@@ -6402,19 +6481,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();
+ }
}
}
}
@@ -6435,10 +6519,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.
}
@@ -6448,7 +6531,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: {
@@ -6481,9 +6564,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 =
@@ -6836,7 +7020,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 ab1b4992..59b04aba 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[] = {
@@ -1207,15 +1079,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
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 ::google::protobuf::internal::once_flag once;
+ ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
@@ -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() {
@@ -1621,9 +1490,7 @@ void FileDescriptorSet::ArenaDtor(void* object) {
void FileDescriptorSet::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void FileDescriptorSet::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* FileDescriptorSet::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -1631,13 +1498,10 @@ 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();
}
-FileDescriptorSet* FileDescriptorSet::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<FileDescriptorSet>(arena);
-}
void FileDescriptorSet::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FileDescriptorSet)
@@ -1656,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)) {
@@ -1664,7 +1528,8 @@ bool FileDescriptorSet::MergePartialFromCodedStream(
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_file()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_file()));
} else {
goto handle_unusual;
}
@@ -1701,7 +1566,9 @@ void FileDescriptorSet::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->file_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 1, this->file(static_cast<int>(i)), output);
+ 1,
+ this->file(static_cast<int>(i)),
+ output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -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;
}
@@ -1826,10 +1691,9 @@ void FileDescriptorSet::UnsafeArenaSwap(FileDescriptorSet* other) {
}
void FileDescriptorSet::InternalSwap(FileDescriptorSet* other) {
using std::swap;
- file_.InternalSwap(&other->file_);
+ 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 {
@@ -1846,10 +1710,6 @@ void FileDescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_FileDescriptorProto_default_instance_._instance.get_mutable()->source_code_info_ = const_cast< ::google::protobuf::SourceCodeInfo*>(
::google::protobuf::SourceCodeInfo::internal_default_instance());
}
-void FileDescriptorProto::_slow_mutable_options() {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::FileOptions >(
- GetArenaNoVirtual());
-}
void FileDescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::FileOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -1863,10 +1723,6 @@ void FileDescriptorProto::unsafe_arena_set_allocated_options(
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.options)
}
-void FileDescriptorProto::_slow_mutable_source_code_info() {
- source_code_info_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::SourceCodeInfo >(
- GetArenaNoVirtual());
-}
void FileDescriptorProto::unsafe_arena_set_allocated_source_code_info(
::google::protobuf::SourceCodeInfo* source_code_info) {
if (GetArenaNoVirtual() == NULL) {
@@ -1897,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)
}
@@ -1913,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)
@@ -1922,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_),
@@ -1960,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());
@@ -1990,9 +1843,7 @@ void FileDescriptorProto::ArenaDtor(void* object) {
void FileDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void FileDescriptorProto::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* FileDescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -2000,13 +1851,10 @@ 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();
}
-FileDescriptorProto* FileDescriptorProto::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<FileDescriptorProto>(arena);
-}
void FileDescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FileDescriptorProto)
@@ -2024,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);
@@ -2054,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)) {
@@ -2111,7 +1956,8 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_message_type()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_message_type()));
} else {
goto handle_unusual;
}
@@ -2122,7 +1968,8 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_enum_type()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_enum_type()));
} else {
goto handle_unusual;
}
@@ -2133,7 +1980,8 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_service()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_service()));
} else {
goto handle_unusual;
}
@@ -2144,7 +1992,8 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
case 7: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_extension()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_extension()));
} else {
goto handle_unusual;
}
@@ -2290,40 +2139,48 @@ void FileDescriptorProto::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->message_type_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 4, this->message_type(static_cast<int>(i)), output);
+ 4,
+ this->message_type(static_cast<int>(i)),
+ output);
}
// repeated .google.protobuf.EnumDescriptorProto enum_type = 5;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->enum_type_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 5, this->enum_type(static_cast<int>(i)), output);
+ 5,
+ this->enum_type(static_cast<int>(i)),
+ output);
}
// repeated .google.protobuf.ServiceDescriptorProto service = 6;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->service_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 6, this->service(static_cast<int>(i)), output);
+ 6,
+ this->service(static_cast<int>(i)),
+ output);
}
// repeated .google.protobuf.FieldDescriptorProto extension = 7;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->extension_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 7, this->extension(static_cast<int>(i)), output);
+ 7,
+ this->extension(static_cast<int>(i)),
+ output);
}
// optional .google.protobuf.FileOptions options = 8;
if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 8, *this->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, *this->source_code_info_, output);
+ 9, this->_internal_source_code_info(), output);
}
// repeated int32 public_dependency = 10;
@@ -2431,14 +2288,14 @@ void FileDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 8, *this->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, *this->source_code_info_, deterministic, target);
+ 9, this->_internal_source_code_info(), deterministic, target);
}
// repeated int32 public_dependency = 10;
@@ -2573,21 +2430,19 @@ size_t FileDescriptorProto::ByteSizeLong() const {
if (has_options()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
- *this->options_);
+ *options_);
}
// optional .google.protobuf.SourceCodeInfo source_code_info = 9;
if (has_source_code_info()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
- *this->source_code_info_);
+ *source_code_info_);
}
}
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;
}
@@ -2686,21 +2541,23 @@ void FileDescriptorProto::UnsafeArenaSwap(FileDescriptorProto* other) {
}
void FileDescriptorProto::InternalSwap(FileDescriptorProto* other) {
using std::swap;
- dependency_.InternalSwap(&other->dependency_);
- message_type_.InternalSwap(&other->message_type_);
- enum_type_.InternalSwap(&other->enum_type_);
- service_.InternalSwap(&other->service_);
- extension_.InternalSwap(&other->extension_);
+ dependency_.InternalSwap(CastToBase(&other->dependency_));
+ CastToBase(&message_type_)->InternalSwap(CastToBase(&other->message_type_));
+ CastToBase(&enum_type_)->InternalSwap(CastToBase(&other->enum_type_));
+ CastToBase(&service_)->InternalSwap(CastToBase(&other->service_));
+ 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 {
@@ -2715,10 +2572,6 @@ void DescriptorProto_ExtensionRange::InitAsDefaultInstance() {
::google::protobuf::_DescriptorProto_ExtensionRange_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::ExtensionRangeOptions*>(
::google::protobuf::ExtensionRangeOptions::internal_default_instance());
}
-void DescriptorProto_ExtensionRange::_slow_mutable_options() {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ExtensionRangeOptions >(
- GetArenaNoVirtual());
-}
void DescriptorProto_ExtensionRange::unsafe_arena_set_allocated_options(
::google::protobuf::ExtensionRangeOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -2740,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)
@@ -2757,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_);
@@ -2772,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_));
@@ -2795,9 +2645,7 @@ void DescriptorProto_ExtensionRange::ArenaDtor(void* object) {
void DescriptorProto_ExtensionRange::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void DescriptorProto_ExtensionRange::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* DescriptorProto_ExtensionRange::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -2805,13 +2653,10 @@ 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();
}
-DescriptorProto_ExtensionRange* DescriptorProto_ExtensionRange::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<DescriptorProto_ExtensionRange>(arena);
-}
void DescriptorProto_ExtensionRange::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.DescriptorProto.ExtensionRange)
@@ -2839,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)) {
@@ -2923,7 +2768,7 @@ void DescriptorProto_ExtensionRange::SerializeWithCachedSizes(
// optional .google.protobuf.ExtensionRangeOptions options = 3;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, *this->options_, output);
+ 3, this->_internal_options(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -2955,7 +2800,7 @@ void DescriptorProto_ExtensionRange::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 3, *this->options_, deterministic, target);
+ 3, this->_internal_options(), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -2980,7 +2825,7 @@ size_t DescriptorProto_ExtensionRange::ByteSizeLong() const {
if (has_options()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
- *this->options_);
+ *options_);
}
// optional int32 start = 1;
@@ -2999,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;
}
@@ -3089,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 {
@@ -3109,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)
@@ -3126,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_) -
@@ -3136,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_));
@@ -3158,9 +2997,7 @@ void DescriptorProto_ReservedRange::ArenaDtor(void* object) {
void DescriptorProto_ReservedRange::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void DescriptorProto_ReservedRange::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* DescriptorProto_ReservedRange::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -3168,13 +3005,10 @@ 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();
}
-DescriptorProto_ReservedRange* DescriptorProto_ReservedRange::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<DescriptorProto_ReservedRange>(arena);
-}
void DescriptorProto_ReservedRange::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.DescriptorProto.ReservedRange)
@@ -3198,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)) {
@@ -3326,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;
}
@@ -3409,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 {
@@ -3424,10 +3255,6 @@ void DescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_DescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::MessageOptions*>(
::google::protobuf::MessageOptions::internal_default_instance());
}
-void DescriptorProto::_slow_mutable_options() {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::MessageOptions >(
- GetArenaNoVirtual());
-}
void DescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::MessageOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -3456,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)
}
@@ -3473,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)
@@ -3482,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_),
@@ -3506,7 +3331,6 @@ DescriptorProto::DescriptorProto(const DescriptorProto& from)
}
void DescriptorProto::SharedCtor() {
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
}
@@ -3529,9 +3353,7 @@ void DescriptorProto::ArenaDtor(void* object) {
void DescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void DescriptorProto::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* DescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -3539,13 +3361,10 @@ 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();
}
-DescriptorProto* DescriptorProto::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<DescriptorProto>(arena);
-}
void DescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.DescriptorProto)
@@ -3564,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);
@@ -3582,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)) {
@@ -3606,7 +3424,8 @@ bool DescriptorProto::MergePartialFromCodedStream(
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_field()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_field()));
} else {
goto handle_unusual;
}
@@ -3617,7 +3436,8 @@ bool DescriptorProto::MergePartialFromCodedStream(
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_nested_type()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_nested_type()));
} else {
goto handle_unusual;
}
@@ -3628,7 +3448,8 @@ bool DescriptorProto::MergePartialFromCodedStream(
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_enum_type()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_enum_type()));
} else {
goto handle_unusual;
}
@@ -3639,7 +3460,8 @@ bool DescriptorProto::MergePartialFromCodedStream(
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_extension_range()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_extension_range()));
} else {
goto handle_unusual;
}
@@ -3650,7 +3472,8 @@ bool DescriptorProto::MergePartialFromCodedStream(
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_extension()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_extension()));
} else {
goto handle_unusual;
}
@@ -3673,7 +3496,8 @@ bool DescriptorProto::MergePartialFromCodedStream(
case 8: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_oneof_decl()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_oneof_decl()));
} else {
goto handle_unusual;
}
@@ -3684,7 +3508,8 @@ bool DescriptorProto::MergePartialFromCodedStream(
case 9: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(74u /* 74 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_reserved_range()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_reserved_range()));
} else {
goto handle_unusual;
}
@@ -3749,55 +3574,69 @@ void DescriptorProto::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->field_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->field(static_cast<int>(i)), output);
+ 2,
+ this->field(static_cast<int>(i)),
+ output);
}
// repeated .google.protobuf.DescriptorProto nested_type = 3;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->nested_type_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, this->nested_type(static_cast<int>(i)), output);
+ 3,
+ this->nested_type(static_cast<int>(i)),
+ output);
}
// repeated .google.protobuf.EnumDescriptorProto enum_type = 4;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->enum_type_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 4, this->enum_type(static_cast<int>(i)), output);
+ 4,
+ this->enum_type(static_cast<int>(i)),
+ output);
}
// repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->extension_range_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 5, this->extension_range(static_cast<int>(i)), output);
+ 5,
+ this->extension_range(static_cast<int>(i)),
+ output);
}
// repeated .google.protobuf.FieldDescriptorProto extension = 6;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->extension_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 6, this->extension(static_cast<int>(i)), output);
+ 6,
+ this->extension(static_cast<int>(i)),
+ output);
}
// optional .google.protobuf.MessageOptions options = 7;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 7, *this->options_, output);
+ 7, this->_internal_options(), output);
}
// repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->oneof_decl_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 8, this->oneof_decl(static_cast<int>(i)), output);
+ 8,
+ this->oneof_decl(static_cast<int>(i)),
+ output);
}
// repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->reserved_range_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 9, this->reserved_range(static_cast<int>(i)), output);
+ 9,
+ this->reserved_range(static_cast<int>(i)),
+ output);
}
// repeated string reserved_name = 10;
@@ -3880,7 +3719,7 @@ void DescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 7, *this->options_, deterministic, target);
+ 7, this->_internal_options(), deterministic, target);
}
// repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;
@@ -4023,14 +3862,12 @@ size_t DescriptorProto::ByteSizeLong() const {
if (has_options()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
- *this->options_);
+ *options_);
}
}
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;
}
@@ -4123,19 +3960,19 @@ void DescriptorProto::UnsafeArenaSwap(DescriptorProto* other) {
}
void DescriptorProto::InternalSwap(DescriptorProto* other) {
using std::swap;
- field_.InternalSwap(&other->field_);
- nested_type_.InternalSwap(&other->nested_type_);
- enum_type_.InternalSwap(&other->enum_type_);
- extension_range_.InternalSwap(&other->extension_range_);
- extension_.InternalSwap(&other->extension_);
- oneof_decl_.InternalSwap(&other->oneof_decl_);
- reserved_range_.InternalSwap(&other->reserved_range_);
- reserved_name_.InternalSwap(&other->reserved_name_);
- name_.Swap(&other->name_);
+ CastToBase(&field_)->InternalSwap(CastToBase(&other->field_));
+ CastToBase(&nested_type_)->InternalSwap(CastToBase(&other->nested_type_));
+ CastToBase(&enum_type_)->InternalSwap(CastToBase(&other->enum_type_));
+ CastToBase(&extension_range_)->InternalSwap(CastToBase(&other->extension_range_));
+ CastToBase(&extension_)->InternalSwap(CastToBase(&other->extension_));
+ 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_, &::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 {
@@ -4154,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)
}
@@ -4165,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)
@@ -4174,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_);
@@ -4182,7 +4017,6 @@ ExtensionRangeOptions::ExtensionRangeOptions(const ExtensionRangeOptions& from)
}
void ExtensionRangeOptions::SharedCtor() {
- _cached_size_ = 0;
}
ExtensionRangeOptions::~ExtensionRangeOptions() {
@@ -4201,9 +4035,7 @@ void ExtensionRangeOptions::ArenaDtor(void* object) {
void ExtensionRangeOptions::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -4211,13 +4043,10 @@ 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();
}
-ExtensionRangeOptions* ExtensionRangeOptions::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<ExtensionRangeOptions>(arena);
-}
void ExtensionRangeOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.ExtensionRangeOptions)
@@ -4237,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)) {
@@ -4245,7 +4074,8 @@ bool ExtensionRangeOptions::MergePartialFromCodedStream(
case 999: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
@@ -4288,7 +4118,9 @@ void ExtensionRangeOptions::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(static_cast<int>(i)), output);
+ 999,
+ this->uninterpreted_option(static_cast<int>(i)),
+ output);
}
// Extension range [1000, 536870912)
@@ -4352,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;
}
@@ -4428,10 +4258,9 @@ void ExtensionRangeOptions::UnsafeArenaSwap(ExtensionRangeOptions* other) {
}
void ExtensionRangeOptions::InternalSwap(ExtensionRangeOptions* other) {
using std::swap;
- uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ 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_);
}
@@ -4447,10 +4276,6 @@ void FieldDescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_FieldDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::FieldOptions*>(
::google::protobuf::FieldOptions::internal_default_instance());
}
-void FieldDescriptorProto::_slow_mutable_options() {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::FieldOptions >(
- GetArenaNoVirtual());
-}
void FieldDescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::FieldOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -4479,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)
@@ -4496,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()) {
@@ -4536,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());
@@ -4571,9 +4393,7 @@ void FieldDescriptorProto::ArenaDtor(void* object) {
void FieldDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void FieldDescriptorProto::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* FieldDescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -4581,13 +4401,10 @@ 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();
}
-FieldDescriptorProto* FieldDescriptorProto::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<FieldDescriptorProto>(arena);
-}
void FieldDescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FieldDescriptorProto)
@@ -4598,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);
@@ -4641,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)) {
@@ -4892,7 +4704,7 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.FieldOptions options = 8;
if (cached_has_bits & 0x00000020u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 8, *this->options_, output);
+ 8, this->_internal_options(), output);
}
// optional int32 oneof_index = 9;
@@ -4990,7 +4802,7 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000020u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 8, *this->options_, deterministic, target);
+ 8, this->_internal_options(), deterministic, target);
}
// optional int32 oneof_index = 9;
@@ -5066,7 +4878,7 @@ size_t FieldDescriptorProto::ByteSizeLong() const {
if (has_options()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
- *this->options_);
+ *options_);
}
// optional int32 number = 3;
@@ -5099,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;
}
@@ -5208,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_);
@@ -5220,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 {
@@ -5235,10 +5049,6 @@ void OneofDescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_OneofDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::OneofOptions*>(
::google::protobuf::OneofOptions::internal_default_instance());
}
-void OneofDescriptorProto::_slow_mutable_options() {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::OneofOptions >(
- GetArenaNoVirtual());
-}
void OneofDescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::OneofOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -5259,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)
@@ -5276,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()) {
@@ -5293,7 +5101,6 @@ OneofDescriptorProto::OneofDescriptorProto(const OneofDescriptorProto& from)
}
void OneofDescriptorProto::SharedCtor() {
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
}
@@ -5316,9 +5123,7 @@ void OneofDescriptorProto::ArenaDtor(void* object) {
void OneofDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void OneofDescriptorProto::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* OneofDescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -5326,13 +5131,10 @@ 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();
}
-OneofDescriptorProto* OneofDescriptorProto::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<OneofDescriptorProto>(arena);
-}
void OneofDescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.OneofDescriptorProto)
@@ -5343,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);
@@ -5361,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)) {
@@ -5433,7 +5234,7 @@ void OneofDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.OneofOptions options = 2;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, *this->options_, output);
+ 2, this->_internal_options(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -5466,7 +5267,7 @@ void OneofDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 2, *this->options_, deterministic, target);
+ 2, this->_internal_options(), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -5498,14 +5299,12 @@ size_t OneofDescriptorProto::ByteSizeLong() const {
if (has_options()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
- *this->options_);
+ *options_);
}
}
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;
}
@@ -5584,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 {
@@ -5608,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)
@@ -5625,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_) -
@@ -5635,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_));
@@ -5657,9 +5453,7 @@ void EnumDescriptorProto_EnumReservedRange::ArenaDtor(void* object) {
void EnumDescriptorProto_EnumReservedRange::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -5667,13 +5461,10 @@ 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();
}
-EnumDescriptorProto_EnumReservedRange* EnumDescriptorProto_EnumReservedRange::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<EnumDescriptorProto_EnumReservedRange>(arena);
-}
void EnumDescriptorProto_EnumReservedRange::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.EnumDescriptorProto.EnumReservedRange)
@@ -5697,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)) {
@@ -5825,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;
}
@@ -5908,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 {
@@ -5923,10 +5711,6 @@ void EnumDescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_EnumDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::EnumOptions*>(
::google::protobuf::EnumOptions::internal_default_instance());
}
-void EnumDescriptorProto::_slow_mutable_options() {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::EnumOptions >(
- GetArenaNoVirtual());
-}
void EnumDescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::EnumOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -5950,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)
}
@@ -5962,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)
@@ -5971,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_) {
@@ -5990,7 +5772,6 @@ EnumDescriptorProto::EnumDescriptorProto(const EnumDescriptorProto& from)
}
void EnumDescriptorProto::SharedCtor() {
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
}
@@ -6013,9 +5794,7 @@ void EnumDescriptorProto::ArenaDtor(void* object) {
void EnumDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void EnumDescriptorProto::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* EnumDescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -6023,13 +5802,10 @@ 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();
}
-EnumDescriptorProto* EnumDescriptorProto::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<EnumDescriptorProto>(arena);
-}
void EnumDescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.EnumDescriptorProto)
@@ -6043,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);
@@ -6061,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)) {
@@ -6085,7 +5860,8 @@ bool EnumDescriptorProto::MergePartialFromCodedStream(
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_value()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_value()));
} else {
goto handle_unusual;
}
@@ -6108,7 +5884,8 @@ bool EnumDescriptorProto::MergePartialFromCodedStream(
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_reserved_range()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_reserved_range()));
} else {
goto handle_unusual;
}
@@ -6173,20 +5950,24 @@ void EnumDescriptorProto::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->value_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->value(static_cast<int>(i)), output);
+ 2,
+ this->value(static_cast<int>(i)),
+ output);
}
// optional .google.protobuf.EnumOptions options = 3;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, *this->options_, output);
+ 3, this->_internal_options(), output);
}
// repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->reserved_range_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 4, this->reserved_range(static_cast<int>(i)), output);
+ 4,
+ this->reserved_range(static_cast<int>(i)),
+ output);
}
// repeated string reserved_name = 5;
@@ -6237,7 +6018,7 @@ void EnumDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 3, *this->options_, deterministic, target);
+ 3, this->_internal_options(), deterministic, target);
}
// repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;
@@ -6317,14 +6098,12 @@ size_t EnumDescriptorProto::ByteSizeLong() const {
if (has_options()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
- *this->options_);
+ *options_);
}
}
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;
}
@@ -6407,14 +6186,14 @@ void EnumDescriptorProto::UnsafeArenaSwap(EnumDescriptorProto* other) {
}
void EnumDescriptorProto::InternalSwap(EnumDescriptorProto* other) {
using std::swap;
- value_.InternalSwap(&other->value_);
- reserved_range_.InternalSwap(&other->reserved_range_);
- reserved_name_.InternalSwap(&other->reserved_name_);
- name_.Swap(&other->name_);
+ CastToBase(&value_)->InternalSwap(CastToBase(&other->value_));
+ CastToBase(&reserved_range_)->InternalSwap(CastToBase(&other->reserved_range_));
+ reserved_name_.InternalSwap(CastToBase(&other->reserved_name_));
+ name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
swap(options_, other->options_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata EnumDescriptorProto::GetMetadata() const {
@@ -6429,10 +6208,6 @@ void EnumValueDescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_EnumValueDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::EnumValueOptions*>(
::google::protobuf::EnumValueOptions::internal_default_instance());
}
-void EnumValueDescriptorProto::_slow_mutable_options() {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::EnumValueOptions >(
- GetArenaNoVirtual());
-}
void EnumValueDescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::EnumValueOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -6454,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)
@@ -6471,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()) {
@@ -6489,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_) -
@@ -6514,9 +6286,7 @@ void EnumValueDescriptorProto::ArenaDtor(void* object) {
void EnumValueDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void EnumValueDescriptorProto::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* EnumValueDescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -6524,13 +6294,10 @@ 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();
}
-EnumValueDescriptorProto* EnumValueDescriptorProto::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<EnumValueDescriptorProto>(arena);
-}
void EnumValueDescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.EnumValueDescriptorProto)
@@ -6541,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);
@@ -6560,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)) {
@@ -6651,7 +6417,7 @@ void EnumValueDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.EnumValueOptions options = 3;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, *this->options_, output);
+ 3, this->_internal_options(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -6689,7 +6455,7 @@ void EnumValueDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 3, *this->options_, deterministic, target);
+ 3, this->_internal_options(), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -6721,7 +6487,7 @@ size_t EnumValueDescriptorProto::ByteSizeLong() const {
if (has_options()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
- *this->options_);
+ *options_);
}
// optional int32 number = 2;
@@ -6733,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;
}
@@ -6818,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 {
@@ -6838,10 +6602,6 @@ void ServiceDescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_ServiceDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::ServiceOptions*>(
::google::protobuf::ServiceOptions::internal_default_instance());
}
-void ServiceDescriptorProto::_slow_mutable_options() {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ServiceOptions >(
- GetArenaNoVirtual());
-}
void ServiceDescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::ServiceOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -6863,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)
}
@@ -6873,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)
@@ -6882,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());
@@ -6899,7 +6657,6 @@ ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& fro
}
void ServiceDescriptorProto::SharedCtor() {
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
}
@@ -6922,9 +6679,7 @@ void ServiceDescriptorProto::ArenaDtor(void* object) {
void ServiceDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void ServiceDescriptorProto::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* ServiceDescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -6932,13 +6687,10 @@ 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();
}
-ServiceDescriptorProto* ServiceDescriptorProto::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<ServiceDescriptorProto>(arena);
-}
void ServiceDescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.ServiceDescriptorProto)
@@ -6950,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);
@@ -6968,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)) {
@@ -6992,7 +6743,8 @@ bool ServiceDescriptorProto::MergePartialFromCodedStream(
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_method()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_method()));
} else {
goto handle_unusual;
}
@@ -7052,13 +6804,15 @@ void ServiceDescriptorProto::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->method_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->method(static_cast<int>(i)), output);
+ 2,
+ this->method(static_cast<int>(i)),
+ output);
}
// optional .google.protobuf.ServiceOptions options = 3;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, *this->options_, output);
+ 3, this->_internal_options(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -7099,7 +6853,7 @@ void ServiceDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 3, *this->options_, deterministic, target);
+ 3, this->_internal_options(), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -7142,14 +6896,12 @@ size_t ServiceDescriptorProto::ByteSizeLong() const {
if (has_options()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
- *this->options_);
+ *options_);
}
}
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;
}
@@ -7230,12 +6982,12 @@ void ServiceDescriptorProto::UnsafeArenaSwap(ServiceDescriptorProto* other) {
}
void ServiceDescriptorProto::InternalSwap(ServiceDescriptorProto* other) {
using std::swap;
- method_.InternalSwap(&other->method_);
- name_.Swap(&other->name_);
+ CastToBase(&method_)->InternalSwap(CastToBase(&other->method_));
+ name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
swap(options_, other->options_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata ServiceDescriptorProto::GetMetadata() const {
@@ -7250,10 +7002,6 @@ void MethodDescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_MethodDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::MethodOptions*>(
::google::protobuf::MethodOptions::internal_default_instance());
}
-void MethodDescriptorProto::_slow_mutable_options() {
- options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::MethodOptions >(
- GetArenaNoVirtual());
-}
void MethodDescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::MethodOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -7278,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)
@@ -7295,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()) {
@@ -7325,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());
@@ -7354,9 +7099,7 @@ void MethodDescriptorProto::ArenaDtor(void* object) {
void MethodDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void MethodDescriptorProto::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* MethodDescriptorProto::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -7364,13 +7107,10 @@ 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();
}
-MethodDescriptorProto* MethodDescriptorProto::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<MethodDescriptorProto>(arena);
-}
void MethodDescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.MethodDescriptorProto)
@@ -7381,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);
@@ -7410,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)) {
@@ -7562,7 +7299,7 @@ void MethodDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.MethodOptions options = 4;
if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 4, *this->options_, output);
+ 4, this->_internal_options(), output);
}
// optional bool client_streaming = 5 [default = false];
@@ -7627,7 +7364,7 @@ void MethodDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 4, *this->options_, deterministic, target);
+ 4, this->_internal_options(), deterministic, target);
}
// optional bool client_streaming = 5 [default = false];
@@ -7683,7 +7420,7 @@ size_t MethodDescriptorProto::ByteSizeLong() const {
if (has_options()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
- *this->options_);
+ *options_);
}
// optional bool client_streaming = 5 [default = false];
@@ -7698,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;
}
@@ -7792,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 {
@@ -7832,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)
}
@@ -7848,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)
@@ -7857,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_);
@@ -7901,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());
@@ -7917,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;
}
@@ -7938,6 +7686,8 @@ 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) {
@@ -7947,9 +7697,7 @@ void FileOptions::ArenaDtor(void* object) {
void FileOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void FileOptions::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* FileOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -7957,13 +7705,10 @@ 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();
}
-FileOptions* FileOptions::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<FileOptions>(arena);
-}
void FileOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FileOptions)
@@ -7976,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();
@@ -8027,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)) {
@@ -8305,11 +8052,44 @@ 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) ==
static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
@@ -8370,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);
}
@@ -8391,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);
}
@@ -8476,15 +8256,37 @@ 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++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(static_cast<int>(i)), output);
+ 999,
+ this->uninterpreted_option(static_cast<int>(i)),
+ output);
}
// Extension range [1000, 536870912)
@@ -8529,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);
}
@@ -8551,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);
}
@@ -8641,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++) {
@@ -8746,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];
@@ -8781,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 +
@@ -8801,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;
}
@@ -8860,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;
@@ -8940,16 +8782,27 @@ void FileOptions::UnsafeArenaSwap(FileOptions* other) {
}
void FileOptions::InternalSwap(FileOptions* other) {
using std::swap;
- uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
- java_package_.Swap(&other->java_package_);
- java_outer_classname_.Swap(&other->java_outer_classname_);
- go_package_.Swap(&other->go_package_);
- objc_class_prefix_.Swap(&other->objc_class_prefix_);
- csharp_namespace_.Swap(&other->csharp_namespace_);
- swift_prefix_.Swap(&other->swift_prefix_);
- php_class_prefix_.Swap(&other->php_class_prefix_);
- php_namespace_.Swap(&other->php_namespace_);
- swap(cc_enable_arenas_, other->cc_enable_arenas_);
+ CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
+ 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_);
@@ -8958,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_);
}
@@ -8985,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)
}
@@ -8996,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)
@@ -9005,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_);
@@ -9016,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_));
@@ -9038,9 +8888,7 @@ void MessageOptions::ArenaDtor(void* object) {
void MessageOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void MessageOptions::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* MessageOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -9048,13 +8896,10 @@ 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();
}
-MessageOptions* MessageOptions::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<MessageOptions>(arena);
-}
void MessageOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.MessageOptions)
@@ -9077,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)) {
@@ -9141,7 +8986,8 @@ bool MessageOptions::MergePartialFromCodedStream(
case 999: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
@@ -9205,7 +9051,9 @@ void MessageOptions::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(static_cast<int>(i)), output);
+ 999,
+ this->uninterpreted_option(static_cast<int>(i)),
+ output);
}
// Extension range [1000, 536870912)
@@ -9312,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;
}
@@ -9404,14 +9250,13 @@ void MessageOptions::UnsafeArenaSwap(MessageOptions* other) {
}
void MessageOptions::InternalSwap(MessageOptions* other) {
using std::swap;
- uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
swap(message_set_wire_format_, other->message_set_wire_format_);
swap(no_standard_descriptor_accessor_, other->no_standard_descriptor_accessor_);
swap(deprecated_, other->deprecated_);
swap(map_entry_, other->map_entry_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
@@ -9437,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)
}
@@ -9448,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)
@@ -9457,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_);
@@ -9468,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_));
@@ -9490,9 +9332,7 @@ void FieldOptions::ArenaDtor(void* object) {
void FieldOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void FieldOptions::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* FieldOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -9500,13 +9340,10 @@ 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();
}
-FieldOptions* FieldOptions::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<FieldOptions>(arena);
-}
void FieldOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FieldOptions)
@@ -9532,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)) {
@@ -9636,7 +9473,8 @@ bool FieldOptions::MergePartialFromCodedStream(
case 999: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
@@ -9712,7 +9550,9 @@ void FieldOptions::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(static_cast<int>(i)), output);
+ 999,
+ this->uninterpreted_option(static_cast<int>(i)),
+ output);
}
// Extension range [1000, 536870912)
@@ -9843,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;
}
@@ -9941,7 +9779,7 @@ void FieldOptions::UnsafeArenaSwap(FieldOptions* other) {
}
void FieldOptions::InternalSwap(FieldOptions* other) {
using std::swap;
- uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
swap(ctype_, other->ctype_);
swap(packed_, other->packed_);
swap(lazy_, other->lazy_);
@@ -9950,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_);
}
@@ -9970,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)
}
@@ -9981,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)
@@ -9990,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_);
@@ -9998,7 +9833,6 @@ OneofOptions::OneofOptions(const OneofOptions& from)
}
void OneofOptions::SharedCtor() {
- _cached_size_ = 0;
}
OneofOptions::~OneofOptions() {
@@ -10017,9 +9851,7 @@ void OneofOptions::ArenaDtor(void* object) {
void OneofOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void OneofOptions::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* OneofOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -10027,13 +9859,10 @@ 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();
}
-OneofOptions* OneofOptions::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<OneofOptions>(arena);
-}
void OneofOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.OneofOptions)
@@ -10053,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)) {
@@ -10061,7 +9890,8 @@ bool OneofOptions::MergePartialFromCodedStream(
case 999: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
@@ -10104,7 +9934,9 @@ void OneofOptions::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(static_cast<int>(i)), output);
+ 999,
+ this->uninterpreted_option(static_cast<int>(i)),
+ output);
}
// Extension range [1000, 536870912)
@@ -10168,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;
}
@@ -10244,10 +10074,9 @@ void OneofOptions::UnsafeArenaSwap(OneofOptions* other) {
}
void OneofOptions::InternalSwap(OneofOptions* other) {
using std::swap;
- uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ 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_);
}
@@ -10269,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)
}
@@ -10280,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)
@@ -10289,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_);
@@ -10300,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_));
@@ -10322,9 +10148,7 @@ void EnumOptions::ArenaDtor(void* object) {
void EnumOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void EnumOptions::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* EnumOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -10332,13 +10156,10 @@ 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();
}
-EnumOptions* EnumOptions::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<EnumOptions>(arena);
-}
void EnumOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.EnumOptions)
@@ -10361,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)) {
@@ -10397,7 +10218,8 @@ bool EnumOptions::MergePartialFromCodedStream(
case 999: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
@@ -10451,7 +10273,9 @@ void EnumOptions::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(static_cast<int>(i)), output);
+ 999,
+ this->uninterpreted_option(static_cast<int>(i)),
+ output);
}
// Extension range [1000, 536870912)
@@ -10538,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;
}
@@ -10624,12 +10446,11 @@ void EnumOptions::UnsafeArenaSwap(EnumOptions* other) {
}
void EnumOptions::InternalSwap(EnumOptions* other) {
using std::swap;
- uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
swap(allow_alias_, other->allow_alias_);
swap(deprecated_, other->deprecated_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
@@ -10650,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)
}
@@ -10661,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)
@@ -10670,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_);
@@ -10679,7 +10498,6 @@ EnumValueOptions::EnumValueOptions(const EnumValueOptions& from)
}
void EnumValueOptions::SharedCtor() {
- _cached_size_ = 0;
deprecated_ = false;
}
@@ -10699,9 +10517,7 @@ void EnumValueOptions::ArenaDtor(void* object) {
void EnumValueOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void EnumValueOptions::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* EnumValueOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -10709,13 +10525,10 @@ 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();
}
-EnumValueOptions* EnumValueOptions::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<EnumValueOptions>(arena);
-}
void EnumValueOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.EnumValueOptions)
@@ -10736,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)) {
@@ -10758,7 +10571,8 @@ bool EnumValueOptions::MergePartialFromCodedStream(
case 999: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
@@ -10807,7 +10621,9 @@ void EnumValueOptions::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(static_cast<int>(i)), output);
+ 999,
+ this->uninterpreted_option(static_cast<int>(i)),
+ output);
}
// Extension range [1000, 536870912)
@@ -10882,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;
}
@@ -10961,11 +10775,10 @@ void EnumValueOptions::UnsafeArenaSwap(EnumValueOptions* other) {
}
void EnumValueOptions::InternalSwap(EnumValueOptions* other) {
using std::swap;
- uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
swap(deprecated_, other->deprecated_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
@@ -10986,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)
}
@@ -10997,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)
@@ -11006,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_);
@@ -11015,7 +10826,6 @@ ServiceOptions::ServiceOptions(const ServiceOptions& from)
}
void ServiceOptions::SharedCtor() {
- _cached_size_ = 0;
deprecated_ = false;
}
@@ -11035,9 +10845,7 @@ void ServiceOptions::ArenaDtor(void* object) {
void ServiceOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void ServiceOptions::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* ServiceOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -11045,13 +10853,10 @@ 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();
}
-ServiceOptions* ServiceOptions::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<ServiceOptions>(arena);
-}
void ServiceOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.ServiceOptions)
@@ -11072,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)) {
@@ -11094,7 +10899,8 @@ bool ServiceOptions::MergePartialFromCodedStream(
case 999: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
@@ -11143,7 +10949,9 @@ void ServiceOptions::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(static_cast<int>(i)), output);
+ 999,
+ this->uninterpreted_option(static_cast<int>(i)),
+ output);
}
// Extension range [1000, 536870912)
@@ -11218,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;
}
@@ -11297,11 +11103,10 @@ void ServiceOptions::UnsafeArenaSwap(ServiceOptions* other) {
}
void ServiceOptions::InternalSwap(ServiceOptions* other) {
using std::swap;
- uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
swap(deprecated_, other->deprecated_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
@@ -11323,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)
}
@@ -11334,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)
@@ -11343,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_);
@@ -11354,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_));
@@ -11376,9 +11178,7 @@ void MethodOptions::ArenaDtor(void* object) {
void MethodOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void MethodOptions::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* MethodOptions::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -11386,13 +11186,10 @@ 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();
}
-MethodOptions* MethodOptions::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<MethodOptions>(arena);
-}
void MethodOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.MethodOptions)
@@ -11418,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)) {
@@ -11460,7 +11257,8 @@ bool MethodOptions::MergePartialFromCodedStream(
case 999: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
@@ -11515,7 +11313,9 @@ void MethodOptions::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(static_cast<int>(i)), output);
+ 999,
+ this->uninterpreted_option(static_cast<int>(i)),
+ output);
}
// Extension range [1000, 536870912)
@@ -11604,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;
}
@@ -11690,12 +11488,11 @@ void MethodOptions::UnsafeArenaSwap(MethodOptions* other) {
}
void MethodOptions::InternalSwap(MethodOptions* other) {
using std::swap;
- uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
swap(deprecated_, other->deprecated_);
swap(idempotency_level_, other->idempotency_level_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
@@ -11716,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)
@@ -11733,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()) {
@@ -11746,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;
}
@@ -11768,9 +11562,7 @@ void UninterpretedOption_NamePart::ArenaDtor(void* object) {
void UninterpretedOption_NamePart::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void UninterpretedOption_NamePart::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* UninterpretedOption_NamePart::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -11778,13 +11570,10 @@ 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();
}
-UninterpretedOption_NamePart* UninterpretedOption_NamePart::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<UninterpretedOption_NamePart>(arena);
-}
void UninterpretedOption_NamePart::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.UninterpretedOption.NamePart)
@@ -11794,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();
@@ -11808,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)) {
@@ -11963,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;
}
@@ -12043,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 {
@@ -12072,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)
}
@@ -12082,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)
@@ -12091,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());
@@ -12116,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());
@@ -12144,9 +11927,7 @@ void UninterpretedOption::ArenaDtor(void* object) {
void UninterpretedOption::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void UninterpretedOption::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* UninterpretedOption::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -12154,13 +11935,10 @@ 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();
}
-UninterpretedOption* UninterpretedOption::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<UninterpretedOption>(arena);
-}
void UninterpretedOption::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.UninterpretedOption)
@@ -12172,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) {
@@ -12199,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)) {
@@ -12207,7 +11982,8 @@ bool UninterpretedOption::MergePartialFromCodedStream(
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_name()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_name()));
} else {
goto handle_unusual;
}
@@ -12330,7 +12106,9 @@ void UninterpretedOption::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->name_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->name(static_cast<int>(i)), output);
+ 2,
+ this->name(static_cast<int>(i)),
+ output);
}
cached_has_bits = _has_bits_[0];
@@ -12513,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;
}
@@ -12606,16 +12382,18 @@ void UninterpretedOption::UnsafeArenaSwap(UninterpretedOption* other) {
}
void UninterpretedOption::InternalSwap(UninterpretedOption* other) {
using std::swap;
- name_.InternalSwap(&other->name_);
- identifier_value_.Swap(&other->identifier_value_);
- string_value_.Swap(&other->string_value_);
- aggregate_value_.Swap(&other->aggregate_value_);
+ CastToBase(&name_)->InternalSwap(CastToBase(&other->name_));
+ 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 {
@@ -12638,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)
}
@@ -12650,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)
@@ -12659,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_) {
@@ -12678,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());
}
@@ -12701,9 +12476,7 @@ void SourceCodeInfo_Location::ArenaDtor(void* object) {
void SourceCodeInfo_Location::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void SourceCodeInfo_Location::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* SourceCodeInfo_Location::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -12711,13 +12484,10 @@ 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();
}
-SourceCodeInfo_Location* SourceCodeInfo_Location::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<SourceCodeInfo_Location>(arena);
-}
void SourceCodeInfo_Location::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.SourceCodeInfo.Location)
@@ -12731,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();
@@ -12749,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)) {
@@ -13066,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;
}
@@ -13149,12 +12915,13 @@ void SourceCodeInfo_Location::InternalSwap(SourceCodeInfo_Location* other) {
using std::swap;
path_.InternalSwap(&other->path_);
span_.InternalSwap(&other->span_);
- leading_detached_comments_.InternalSwap(&other->leading_detached_comments_);
- leading_comments_.Swap(&other->leading_comments_);
- trailing_comments_.Swap(&other->trailing_comments_);
+ leading_detached_comments_.InternalSwap(CastToBase(&other->leading_detached_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 {
@@ -13173,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)
}
@@ -13183,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)
@@ -13192,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() {
@@ -13218,9 +12982,7 @@ void SourceCodeInfo::ArenaDtor(void* object) {
void SourceCodeInfo::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void SourceCodeInfo::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* SourceCodeInfo::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -13228,13 +12990,10 @@ 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();
}
-SourceCodeInfo* SourceCodeInfo::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<SourceCodeInfo>(arena);
-}
void SourceCodeInfo::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.SourceCodeInfo)
@@ -13253,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)) {
@@ -13261,7 +13020,8 @@ bool SourceCodeInfo::MergePartialFromCodedStream(
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_location()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_location()));
} else {
goto handle_unusual;
}
@@ -13298,7 +13058,9 @@ void SourceCodeInfo::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->location_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 1, this->location(static_cast<int>(i)), output);
+ 1,
+ this->location(static_cast<int>(i)),
+ output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -13352,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;
}
@@ -13422,10 +13182,9 @@ void SourceCodeInfo::UnsafeArenaSwap(SourceCodeInfo* other) {
}
void SourceCodeInfo::InternalSwap(SourceCodeInfo* other) {
using std::swap;
- location_.InternalSwap(&other->location_);
+ 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 {
@@ -13447,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)
}
@@ -13457,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)
@@ -13466,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());
@@ -13481,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_) -
@@ -13505,9 +13261,7 @@ void GeneratedCodeInfo_Annotation::ArenaDtor(void* object) {
void GeneratedCodeInfo_Annotation::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void GeneratedCodeInfo_Annotation::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* GeneratedCodeInfo_Annotation::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -13515,13 +13269,10 @@ 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();
}
-GeneratedCodeInfo_Annotation* GeneratedCodeInfo_Annotation::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<GeneratedCodeInfo_Annotation>(arena);
-}
void GeneratedCodeInfo_Annotation::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.GeneratedCodeInfo.Annotation)
@@ -13532,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>(
@@ -13550,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)) {
@@ -13781,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;
}
@@ -13865,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 {
@@ -13889,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)
}
@@ -13899,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)
@@ -13908,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() {
@@ -13934,9 +13679,7 @@ void GeneratedCodeInfo::ArenaDtor(void* object) {
void GeneratedCodeInfo::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void GeneratedCodeInfo::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* GeneratedCodeInfo::descriptor() {
::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
@@ -13944,13 +13687,10 @@ 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();
}
-GeneratedCodeInfo* GeneratedCodeInfo::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<GeneratedCodeInfo>(arena);
-}
void GeneratedCodeInfo::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.GeneratedCodeInfo)
@@ -13969,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)) {
@@ -13977,7 +13717,8 @@ bool GeneratedCodeInfo::MergePartialFromCodedStream(
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_annotation()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_annotation()));
} else {
goto handle_unusual;
}
@@ -14014,7 +13755,9 @@ void GeneratedCodeInfo::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->annotation_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 1, this->annotation(static_cast<int>(i)), output);
+ 1,
+ this->annotation(static_cast<int>(i)),
+ output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -14068,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;
}
@@ -14138,10 +13879,9 @@ void GeneratedCodeInfo::UnsafeArenaSwap(GeneratedCodeInfo* other) {
}
void GeneratedCodeInfo::InternalSwap(GeneratedCodeInfo* other) {
using std::swap;
- annotation_.InternalSwap(&other->annotation_);
+ 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 {
@@ -14153,5 +13893,90 @@ void GeneratedCodeInfo::InternalSwap(GeneratedCodeInfo* other) {
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
+namespace google {
+namespace protobuf {
+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::CreateMaybeMessage< ::google::protobuf::FileDescriptorProto >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::FileDescriptorProto >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ExtensionRange >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto_ExtensionRange >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ReservedRange >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto_ReservedRange >(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::CreateMaybeMessage< ::google::protobuf::ExtensionRangeOptions >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::ExtensionRangeOptions >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::FieldDescriptorProto >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::FieldDescriptorProto >(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::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::EnumDescriptorProto >(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::CreateMaybeMessage< ::google::protobuf::ServiceDescriptorProto >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::ServiceDescriptorProto >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::MethodDescriptorProto >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::MethodDescriptorProto >(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::CreateMaybeMessage< ::google::protobuf::MessageOptions >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::MessageOptions >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage< ::google::protobuf::FieldOptions >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::FieldOptions >(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::CreateMaybeMessage< ::google::protobuf::EnumOptions >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::EnumOptions >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage< ::google::protobuf::EnumValueOptions >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::EnumValueOptions >(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::CreateMaybeMessage< ::google::protobuf::MethodOptions >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::MethodOptions >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage< ::google::protobuf::UninterpretedOption_NamePart >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::UninterpretedOption_NamePart >(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::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo_Location >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::SourceCodeInfo_Location >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::SourceCodeInfo >(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::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::GeneratedCodeInfo >(arena);
+}
+} // namespace protobuf
+} // namespace google
// @@protoc_insertion_point(global_scope)
diff --git a/src/google/protobuf/descriptor.pb.h b/src/google/protobuf/descriptor.pb.h
index 4ed5cac9..5e7a05d5 100644
--- a/src/google/protobuf/descriptor.pb.h
+++ b/src/google/protobuf/descriptor.pb.h
@@ -1,8 +1,8 @@
// 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>
@@ -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,6 +133,37 @@ LIBPROTOBUF_EXPORT extern UninterpretedOption_NamePartDefaultTypeInternal _Unint
} // namespace google
namespace google {
namespace protobuf {
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ExtensionRange>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ReservedRange>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto_EnumReservedRange>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumOptions>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumValueDescriptorProto>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumValueOptions>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::ExtensionRangeOptions* Arena::CreateMaybeMessage<::google::protobuf::ExtensionRangeOptions>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FieldDescriptorProto>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage<::google::protobuf::FieldOptions>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorProto>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorSet* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorSet>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileOptions* Arena::CreateMaybeMessage<::google::protobuf::FileOptions>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo_Annotation>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::MessageOptions* Arena::CreateMaybeMessage<::google::protobuf::MessageOptions>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::MethodDescriptorProto>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodOptions* Arena::CreateMaybeMessage<::google::protobuf::MethodOptions>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::OneofDescriptorProto>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofOptions* Arena::CreateMaybeMessage<::google::protobuf::OneofOptions>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::ServiceDescriptorProto>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceOptions* Arena::CreateMaybeMessage<::google::protobuf::ServiceOptions>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo_Location>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption_NamePart>(Arena*);
+} // namespace protobuf
+} // namespace google
+namespace google {
+namespace protobuf {
enum FieldDescriptorProto_Type {
FieldDescriptorProto_Type_TYPE_DOUBLE = 1,
@@ -385,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();
@@ -399,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);
@@ -410,28 +360,33 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
// implements Message ----------------------------------------------
- inline FileDescriptorSet* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline FileDescriptorSet* New() const final {
+ return CreateMaybeMessage<FileDescriptorSet>(NULL);
+ }
- FileDescriptorSet* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ FileDescriptorSet* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<FileDescriptorSet>(arena);
+ }
+ 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);
@@ -447,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 ----------------------------------------------------
@@ -457,11 +412,11 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
int file_size() const;
void clear_file();
static const int kFileFieldNumber = 1;
- const ::google::protobuf::FileDescriptorProto& file(int index) const;
::google::protobuf::FileDescriptorProto* mutable_file(int index);
- ::google::protobuf::FileDescriptorProto* add_file();
::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >*
mutable_file();
+ const ::google::protobuf::FileDescriptorProto& file(int index) const;
+ ::google::protobuf::FileDescriptorProto* add_file();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >&
file() const;
@@ -473,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();
};
// -------------------------------------------------------------------
@@ -513,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();
@@ -527,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);
@@ -538,28 +492,33 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
// implements Message ----------------------------------------------
- inline FileDescriptorProto* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline FileDescriptorProto* New() const final {
+ return CreateMaybeMessage<FileDescriptorProto>(NULL);
+ }
- FileDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ FileDescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<FileDescriptorProto>(arena);
+ }
+ 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);
@@ -575,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 ----------------------------------------------------
@@ -607,11 +566,11 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
int message_type_size() const;
void clear_message_type();
static const int kMessageTypeFieldNumber = 4;
- const ::google::protobuf::DescriptorProto& message_type(int index) const;
::google::protobuf::DescriptorProto* mutable_message_type(int index);
- ::google::protobuf::DescriptorProto* add_message_type();
::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >*
mutable_message_type();
+ const ::google::protobuf::DescriptorProto& message_type(int index) const;
+ ::google::protobuf::DescriptorProto* add_message_type();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >&
message_type() const;
@@ -619,11 +578,11 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
int enum_type_size() const;
void clear_enum_type();
static const int kEnumTypeFieldNumber = 5;
- const ::google::protobuf::EnumDescriptorProto& enum_type(int index) const;
::google::protobuf::EnumDescriptorProto* mutable_enum_type(int index);
- ::google::protobuf::EnumDescriptorProto* add_enum_type();
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >*
mutable_enum_type();
+ const ::google::protobuf::EnumDescriptorProto& enum_type(int index) const;
+ ::google::protobuf::EnumDescriptorProto* add_enum_type();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >&
enum_type() const;
@@ -631,11 +590,11 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
int service_size() const;
void clear_service();
static const int kServiceFieldNumber = 6;
- const ::google::protobuf::ServiceDescriptorProto& service(int index) const;
::google::protobuf::ServiceDescriptorProto* mutable_service(int index);
- ::google::protobuf::ServiceDescriptorProto* add_service();
::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto >*
mutable_service();
+ const ::google::protobuf::ServiceDescriptorProto& service(int index) const;
+ ::google::protobuf::ServiceDescriptorProto* add_service();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto >&
service() const;
@@ -643,11 +602,11 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
int extension_size() const;
void clear_extension();
static const int kExtensionFieldNumber = 7;
- const ::google::protobuf::FieldDescriptorProto& extension(int index) const;
::google::protobuf::FieldDescriptorProto* mutable_extension(int index);
- ::google::protobuf::FieldDescriptorProto* add_extension();
::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >*
mutable_extension();
+ const ::google::protobuf::FieldDescriptorProto& extension(int index) const;
+ ::google::protobuf::FieldDescriptorProto* add_extension();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >&
extension() const;
@@ -752,7 +711,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
void clear_options();
static const int kOptionsFieldNumber = 8;
private:
- void _slow_mutable_options();
+ const ::google::protobuf::FileOptions& _internal_options() const;
public:
const ::google::protobuf::FileOptions& options() const;
::google::protobuf::FileOptions* release_options();
@@ -767,7 +726,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
void clear_source_code_info();
static const int kSourceCodeInfoFieldNumber = 9;
private:
- void _slow_mutable_source_code_info();
+ 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();
@@ -795,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_;
@@ -809,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();
};
// -------------------------------------------------------------------
@@ -846,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();
@@ -860,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);
@@ -871,28 +829,33 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
// implements Message ----------------------------------------------
- inline DescriptorProto_ExtensionRange* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline DescriptorProto_ExtensionRange* New() const final {
+ return CreateMaybeMessage<DescriptorProto_ExtensionRange>(NULL);
+ }
- DescriptorProto_ExtensionRange* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ DescriptorProto_ExtensionRange* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<DescriptorProto_ExtensionRange>(arena);
+ }
+ 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);
@@ -908,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 ----------------------------------------------------
@@ -919,7 +882,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
void clear_options();
static const int kOptionsFieldNumber = 3;
private:
- void _slow_mutable_options();
+ const ::google::protobuf::ExtensionRangeOptions& _internal_options() const;
public:
const ::google::protobuf::ExtensionRangeOptions& options() const;
::google::protobuf::ExtensionRangeOptions* release_options();
@@ -957,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();
};
// -------------------------------------------------------------------
@@ -999,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();
@@ -1013,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);
@@ -1024,28 +986,33 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
// implements Message ----------------------------------------------
- inline DescriptorProto_ReservedRange* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline DescriptorProto_ReservedRange* New() const final {
+ return CreateMaybeMessage<DescriptorProto_ReservedRange>(NULL);
+ }
- DescriptorProto_ReservedRange* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ DescriptorProto_ReservedRange* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<DescriptorProto_ReservedRange>(arena);
+ }
+ 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);
@@ -1061,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 ----------------------------------------------------
@@ -1093,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();
};
// -------------------------------------------------------------------
@@ -1134,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();
@@ -1148,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);
@@ -1159,28 +1125,33 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
// implements Message ----------------------------------------------
- inline DescriptorProto* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline DescriptorProto* New() const final {
+ return CreateMaybeMessage<DescriptorProto>(NULL);
+ }
- DescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ DescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<DescriptorProto>(arena);
+ }
+ 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);
@@ -1196,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 ----------------------------------------------------
@@ -1209,11 +1180,11 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
int field_size() const;
void clear_field();
static const int kFieldFieldNumber = 2;
- const ::google::protobuf::FieldDescriptorProto& field(int index) const;
::google::protobuf::FieldDescriptorProto* mutable_field(int index);
- ::google::protobuf::FieldDescriptorProto* add_field();
::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >*
mutable_field();
+ const ::google::protobuf::FieldDescriptorProto& field(int index) const;
+ ::google::protobuf::FieldDescriptorProto* add_field();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >&
field() const;
@@ -1221,11 +1192,11 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
int nested_type_size() const;
void clear_nested_type();
static const int kNestedTypeFieldNumber = 3;
- const ::google::protobuf::DescriptorProto& nested_type(int index) const;
::google::protobuf::DescriptorProto* mutable_nested_type(int index);
- ::google::protobuf::DescriptorProto* add_nested_type();
::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >*
mutable_nested_type();
+ const ::google::protobuf::DescriptorProto& nested_type(int index) const;
+ ::google::protobuf::DescriptorProto* add_nested_type();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >&
nested_type() const;
@@ -1233,11 +1204,11 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
int enum_type_size() const;
void clear_enum_type();
static const int kEnumTypeFieldNumber = 4;
- const ::google::protobuf::EnumDescriptorProto& enum_type(int index) const;
::google::protobuf::EnumDescriptorProto* mutable_enum_type(int index);
- ::google::protobuf::EnumDescriptorProto* add_enum_type();
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >*
mutable_enum_type();
+ const ::google::protobuf::EnumDescriptorProto& enum_type(int index) const;
+ ::google::protobuf::EnumDescriptorProto* add_enum_type();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >&
enum_type() const;
@@ -1245,11 +1216,11 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
int extension_range_size() const;
void clear_extension_range();
static const int kExtensionRangeFieldNumber = 5;
- const ::google::protobuf::DescriptorProto_ExtensionRange& extension_range(int index) const;
::google::protobuf::DescriptorProto_ExtensionRange* mutable_extension_range(int index);
- ::google::protobuf::DescriptorProto_ExtensionRange* add_extension_range();
::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange >*
mutable_extension_range();
+ const ::google::protobuf::DescriptorProto_ExtensionRange& extension_range(int index) const;
+ ::google::protobuf::DescriptorProto_ExtensionRange* add_extension_range();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange >&
extension_range() const;
@@ -1257,11 +1228,11 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
int extension_size() const;
void clear_extension();
static const int kExtensionFieldNumber = 6;
- const ::google::protobuf::FieldDescriptorProto& extension(int index) const;
::google::protobuf::FieldDescriptorProto* mutable_extension(int index);
- ::google::protobuf::FieldDescriptorProto* add_extension();
::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >*
mutable_extension();
+ const ::google::protobuf::FieldDescriptorProto& extension(int index) const;
+ ::google::protobuf::FieldDescriptorProto* add_extension();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >&
extension() const;
@@ -1269,11 +1240,11 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
int oneof_decl_size() const;
void clear_oneof_decl();
static const int kOneofDeclFieldNumber = 8;
- const ::google::protobuf::OneofDescriptorProto& oneof_decl(int index) const;
::google::protobuf::OneofDescriptorProto* mutable_oneof_decl(int index);
- ::google::protobuf::OneofDescriptorProto* add_oneof_decl();
::google::protobuf::RepeatedPtrField< ::google::protobuf::OneofDescriptorProto >*
mutable_oneof_decl();
+ const ::google::protobuf::OneofDescriptorProto& oneof_decl(int index) const;
+ ::google::protobuf::OneofDescriptorProto* add_oneof_decl();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::OneofDescriptorProto >&
oneof_decl() const;
@@ -1281,11 +1252,11 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
int reserved_range_size() const;
void clear_reserved_range();
static const int kReservedRangeFieldNumber = 9;
- const ::google::protobuf::DescriptorProto_ReservedRange& reserved_range(int index) const;
::google::protobuf::DescriptorProto_ReservedRange* mutable_reserved_range(int index);
- ::google::protobuf::DescriptorProto_ReservedRange* add_reserved_range();
::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ReservedRange >*
mutable_reserved_range();
+ const ::google::protobuf::DescriptorProto_ReservedRange& reserved_range(int index) const;
+ ::google::protobuf::DescriptorProto_ReservedRange* add_reserved_range();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ReservedRange >&
reserved_range() const;
@@ -1340,7 +1311,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
void clear_options();
static const int kOptionsFieldNumber = 7;
private:
- void _slow_mutable_options();
+ const ::google::protobuf::MessageOptions& _internal_options() const;
public:
const ::google::protobuf::MessageOptions& options() const;
::google::protobuf::MessageOptions* release_options();
@@ -1362,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_;
@@ -1374,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();
};
// -------------------------------------------------------------------
@@ -1411,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();
@@ -1425,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);
@@ -1436,28 +1406,33 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess
// implements Message ----------------------------------------------
- inline ExtensionRangeOptions* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline ExtensionRangeOptions* New() const final {
+ return CreateMaybeMessage<ExtensionRangeOptions>(NULL);
+ }
- ExtensionRangeOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ ExtensionRangeOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<ExtensionRangeOptions>(arena);
+ }
+ 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);
@@ -1473,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 ----------------------------------------------------
@@ -1483,11 +1458,11 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess
int uninterpreted_option_size() const;
void clear_uninterpreted_option();
static const int kUninterpretedOptionFieldNumber = 999;
- const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
- ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
mutable_uninterpreted_option();
+ const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
+ ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
uninterpreted_option() const;
@@ -1502,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();
};
// -------------------------------------------------------------------
@@ -1542,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();
@@ -1556,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);
@@ -1567,28 +1541,33 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
// implements Message ----------------------------------------------
- inline FieldDescriptorProto* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline FieldDescriptorProto* New() const final {
+ return CreateMaybeMessage<FieldDescriptorProto>(NULL);
+ }
- FieldDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ FieldDescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<FieldDescriptorProto>(arena);
+ }
+ 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);
@@ -1604,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 ----------------------------------------------------
@@ -1821,7 +1800,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
void clear_options();
static const int kOptionsFieldNumber = 8;
private:
- void _slow_mutable_options();
+ const ::google::protobuf::FieldOptions& _internal_options() const;
public:
const ::google::protobuf::FieldOptions& options() const;
::google::protobuf::FieldOptions* release_options();
@@ -1887,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_;
@@ -1899,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();
};
// -------------------------------------------------------------------
@@ -1936,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();
@@ -1950,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);
@@ -1961,28 +1939,33 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
// implements Message ----------------------------------------------
- inline OneofDescriptorProto* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline OneofDescriptorProto* New() const final {
+ return CreateMaybeMessage<OneofDescriptorProto>(NULL);
+ }
- OneofDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ OneofDescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<OneofDescriptorProto>(arena);
+ }
+ 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);
@@ -1998,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 ----------------------------------------------------
@@ -2033,7 +2016,7 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
void clear_options();
static const int kOptionsFieldNumber = 2;
private:
- void _slow_mutable_options();
+ const ::google::protobuf::OneofOptions& _internal_options() const;
public:
const ::google::protobuf::OneofOptions& options() const;
::google::protobuf::OneofOptions* release_options();
@@ -2055,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();
};
// -------------------------------------------------------------------
@@ -2096,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();
@@ -2110,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);
@@ -2121,28 +2103,33 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google
// implements Message ----------------------------------------------
- inline EnumDescriptorProto_EnumReservedRange* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline EnumDescriptorProto_EnumReservedRange* New() const final {
+ return CreateMaybeMessage<EnumDescriptorProto_EnumReservedRange>(NULL);
+ }
- EnumDescriptorProto_EnumReservedRange* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ EnumDescriptorProto_EnumReservedRange* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<EnumDescriptorProto_EnumReservedRange>(arena);
+ }
+ 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);
@@ -2158,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 ----------------------------------------------------
@@ -2190,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();
};
// -------------------------------------------------------------------
@@ -2231,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();
@@ -2245,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);
@@ -2256,28 +2242,33 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
// implements Message ----------------------------------------------
- inline EnumDescriptorProto* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline EnumDescriptorProto* New() const final {
+ return CreateMaybeMessage<EnumDescriptorProto>(NULL);
+ }
- EnumDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ EnumDescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<EnumDescriptorProto>(arena);
+ }
+ 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);
@@ -2293,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 ----------------------------------------------------
@@ -2305,11 +2296,11 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
int value_size() const;
void clear_value();
static const int kValueFieldNumber = 2;
- const ::google::protobuf::EnumValueDescriptorProto& value(int index) const;
::google::protobuf::EnumValueDescriptorProto* mutable_value(int index);
- ::google::protobuf::EnumValueDescriptorProto* add_value();
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto >*
mutable_value();
+ const ::google::protobuf::EnumValueDescriptorProto& value(int index) const;
+ ::google::protobuf::EnumValueDescriptorProto* add_value();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto >&
value() const;
@@ -2317,11 +2308,11 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
int reserved_range_size() const;
void clear_reserved_range();
static const int kReservedRangeFieldNumber = 4;
- const ::google::protobuf::EnumDescriptorProto_EnumReservedRange& reserved_range(int index) const;
::google::protobuf::EnumDescriptorProto_EnumReservedRange* mutable_reserved_range(int index);
- ::google::protobuf::EnumDescriptorProto_EnumReservedRange* add_reserved_range();
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >*
mutable_reserved_range();
+ const ::google::protobuf::EnumDescriptorProto_EnumReservedRange& reserved_range(int index) const;
+ ::google::protobuf::EnumDescriptorProto_EnumReservedRange* add_reserved_range();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >&
reserved_range() const;
@@ -2376,7 +2367,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
void clear_options();
static const int kOptionsFieldNumber = 3;
private:
- void _slow_mutable_options();
+ const ::google::protobuf::EnumOptions& _internal_options() const;
public:
const ::google::protobuf::EnumOptions& options() const;
::google::protobuf::EnumOptions* release_options();
@@ -2398,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();
};
// -------------------------------------------------------------------
@@ -2442,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();
@@ -2456,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);
@@ -2467,28 +2457,33 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
// implements Message ----------------------------------------------
- inline EnumValueDescriptorProto* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline EnumValueDescriptorProto* New() const final {
+ return CreateMaybeMessage<EnumValueDescriptorProto>(NULL);
+ }
- EnumValueDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ EnumValueDescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<EnumValueDescriptorProto>(arena);
+ }
+ 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);
@@ -2504,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 ----------------------------------------------------
@@ -2539,7 +2534,7 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
void clear_options();
static const int kOptionsFieldNumber = 3;
private:
- void _slow_mutable_options();
+ const ::google::protobuf::EnumValueOptions& _internal_options() const;
public:
const ::google::protobuf::EnumValueOptions& options() const;
::google::protobuf::EnumValueOptions* release_options();
@@ -2570,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();
};
// -------------------------------------------------------------------
@@ -2612,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();
@@ -2626,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);
@@ -2637,28 +2631,33 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
// implements Message ----------------------------------------------
- inline ServiceDescriptorProto* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline ServiceDescriptorProto* New() const final {
+ return CreateMaybeMessage<ServiceDescriptorProto>(NULL);
+ }
- ServiceDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ ServiceDescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<ServiceDescriptorProto>(arena);
+ }
+ 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);
@@ -2674,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 ----------------------------------------------------
@@ -2684,11 +2683,11 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
int method_size() const;
void clear_method();
static const int kMethodFieldNumber = 2;
- const ::google::protobuf::MethodDescriptorProto& method(int index) const;
::google::protobuf::MethodDescriptorProto* mutable_method(int index);
- ::google::protobuf::MethodDescriptorProto* add_method();
::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto >*
mutable_method();
+ const ::google::protobuf::MethodDescriptorProto& method(int index) const;
+ ::google::protobuf::MethodDescriptorProto* add_method();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto >&
method() const;
@@ -2721,7 +2720,7 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
void clear_options();
static const int kOptionsFieldNumber = 3;
private:
- void _slow_mutable_options();
+ const ::google::protobuf::ServiceOptions& _internal_options() const;
public:
const ::google::protobuf::ServiceOptions& options() const;
::google::protobuf::ServiceOptions* release_options();
@@ -2743,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();
};
// -------------------------------------------------------------------
@@ -2785,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();
@@ -2799,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);
@@ -2810,28 +2808,33 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
// implements Message ----------------------------------------------
- inline MethodDescriptorProto* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline MethodDescriptorProto* New() const final {
+ return CreateMaybeMessage<MethodDescriptorProto>(NULL);
+ }
- MethodDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ MethodDescriptorProto* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<MethodDescriptorProto>(arena);
+ }
+ 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);
@@ -2847,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 ----------------------------------------------------
@@ -2930,7 +2933,7 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
void clear_options();
static const int kOptionsFieldNumber = 4;
private:
- void _slow_mutable_options();
+ const ::google::protobuf::MethodOptions& _internal_options() const;
public:
const ::google::protobuf::MethodOptions& options() const;
::google::protobuf::MethodOptions* release_options();
@@ -2974,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_;
@@ -2982,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();
};
// -------------------------------------------------------------------
@@ -3019,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();
@@ -3033,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);
@@ -3044,28 +3046,33 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
// implements Message ----------------------------------------------
- inline FileOptions* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline FileOptions* New() const final {
+ return CreateMaybeMessage<FileOptions>(NULL);
+ }
- FileOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ FileOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<FileOptions>(arena);
+ }
+ 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);
@@ -3081,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 ----------------------------------------------------
@@ -3119,11 +3126,11 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
int uninterpreted_option_size() const;
void clear_uninterpreted_option();
static const int kUninterpretedOptionFieldNumber = 999;
- const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
- ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
mutable_uninterpreted_option();
+ const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
+ ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
uninterpreted_option() const;
@@ -3319,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;
@@ -3382,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();
@@ -3428,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_;
@@ -3436,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_;
@@ -3446,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_;
@@ -3455,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();
};
// -------------------------------------------------------------------
@@ -3494,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();
@@ -3508,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);
@@ -3519,28 +3579,33 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
// implements Message ----------------------------------------------
- inline MessageOptions* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline MessageOptions* New() const final {
+ return CreateMaybeMessage<MessageOptions>(NULL);
+ }
- MessageOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ MessageOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<MessageOptions>(arena);
+ }
+ 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);
@@ -3556,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 ----------------------------------------------------
@@ -3566,11 +3631,11 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
int uninterpreted_option_size() const;
void clear_uninterpreted_option();
static const int kUninterpretedOptionFieldNumber = 999;
- const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
- ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
mutable_uninterpreted_option();
+ const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
+ ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
uninterpreted_option() const;
@@ -3621,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();
};
// -------------------------------------------------------------------
@@ -3665,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();
@@ -3679,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);
@@ -3690,28 +3754,33 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
// implements Message ----------------------------------------------
- inline FieldOptions* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline FieldOptions* New() const final {
+ return CreateMaybeMessage<FieldOptions>(NULL);
+ }
- FieldOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ FieldOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<FieldOptions>(arena);
+ }
+ 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);
@@ -3727,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 ----------------------------------------------------
@@ -3793,11 +3862,11 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
int uninterpreted_option_size() const;
void clear_uninterpreted_option();
static const int kUninterpretedOptionFieldNumber = 999;
- const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
- ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
mutable_uninterpreted_option();
+ const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
+ ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
uninterpreted_option() const;
@@ -3866,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_;
@@ -3875,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();
};
// -------------------------------------------------------------------
@@ -3912,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();
@@ -3926,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);
@@ -3937,28 +4005,33 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
// implements Message ----------------------------------------------
- inline OneofOptions* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline OneofOptions* New() const final {
+ return CreateMaybeMessage<OneofOptions>(NULL);
+ }
- OneofOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ OneofOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<OneofOptions>(arena);
+ }
+ 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);
@@ -3974,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 ----------------------------------------------------
@@ -3984,11 +4057,11 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
int uninterpreted_option_size() const;
void clear_uninterpreted_option();
static const int kUninterpretedOptionFieldNumber = 999;
- const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
- ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
mutable_uninterpreted_option();
+ const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
+ ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
uninterpreted_option() const;
@@ -4003,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();
};
// -------------------------------------------------------------------
@@ -4043,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();
@@ -4057,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);
@@ -4068,28 +4140,33 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
// implements Message ----------------------------------------------
- inline EnumOptions* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline EnumOptions* New() const final {
+ return CreateMaybeMessage<EnumOptions>(NULL);
+ }
- EnumOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ EnumOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<EnumOptions>(arena);
+ }
+ 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);
@@ -4105,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 ----------------------------------------------------
@@ -4115,11 +4192,11 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
int uninterpreted_option_size() const;
void clear_uninterpreted_option();
static const int kUninterpretedOptionFieldNumber = 999;
- const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
- ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
mutable_uninterpreted_option();
+ const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
+ ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
uninterpreted_option() const;
@@ -4152,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();
};
// -------------------------------------------------------------------
@@ -4194,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();
@@ -4208,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);
@@ -4219,28 +4295,33 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
// implements Message ----------------------------------------------
- inline EnumValueOptions* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline EnumValueOptions* New() const final {
+ return CreateMaybeMessage<EnumValueOptions>(NULL);
+ }
- EnumValueOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ EnumValueOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<EnumValueOptions>(arena);
+ }
+ 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);
@@ -4256,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 ----------------------------------------------------
@@ -4266,11 +4347,11 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
int uninterpreted_option_size() const;
void clear_uninterpreted_option();
static const int kUninterpretedOptionFieldNumber = 999;
- const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
- ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
mutable_uninterpreted_option();
+ const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
+ ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
uninterpreted_option() const;
@@ -4294,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();
};
// -------------------------------------------------------------------
@@ -4335,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();
@@ -4349,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);
@@ -4360,28 +4440,33 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
// implements Message ----------------------------------------------
- inline ServiceOptions* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline ServiceOptions* New() const final {
+ return CreateMaybeMessage<ServiceOptions>(NULL);
+ }
- ServiceOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ ServiceOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<ServiceOptions>(arena);
+ }
+ 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);
@@ -4397,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 ----------------------------------------------------
@@ -4407,11 +4492,11 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
int uninterpreted_option_size() const;
void clear_uninterpreted_option();
static const int kUninterpretedOptionFieldNumber = 999;
- const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
- ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
mutable_uninterpreted_option();
+ const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
+ ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
uninterpreted_option() const;
@@ -4435,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();
};
// -------------------------------------------------------------------
@@ -4476,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();
@@ -4490,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);
@@ -4501,28 +4585,33 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
// implements Message ----------------------------------------------
- inline MethodOptions* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline MethodOptions* New() const final {
+ return CreateMaybeMessage<MethodOptions>(NULL);
+ }
- MethodOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ MethodOptions* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<MethodOptions>(arena);
+ }
+ 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);
@@ -4538,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 ----------------------------------------------------
@@ -4576,11 +4665,11 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
int uninterpreted_option_size() const;
void clear_uninterpreted_option();
static const int kUninterpretedOptionFieldNumber = 999;
- const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
- ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
mutable_uninterpreted_option();
+ const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
+ ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
uninterpreted_option() const;
@@ -4613,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();
};
// -------------------------------------------------------------------
@@ -4655,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();
@@ -4669,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);
@@ -4680,28 +4768,33 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
// implements Message ----------------------------------------------
- inline UninterpretedOption_NamePart* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline UninterpretedOption_NamePart* New() const final {
+ return CreateMaybeMessage<UninterpretedOption_NamePart>(NULL);
+ }
- UninterpretedOption_NamePart* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ UninterpretedOption_NamePart* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<UninterpretedOption_NamePart>(arena);
+ }
+ 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);
@@ -4717,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 ----------------------------------------------------
@@ -4769,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();
};
// -------------------------------------------------------------------
@@ -4810,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();
@@ -4824,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);
@@ -4835,28 +4927,33 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
// implements Message ----------------------------------------------
- inline UninterpretedOption* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline UninterpretedOption* New() const final {
+ return CreateMaybeMessage<UninterpretedOption>(NULL);
+ }
- UninterpretedOption* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ UninterpretedOption* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<UninterpretedOption>(arena);
+ }
+ 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);
@@ -4872,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 ----------------------------------------------------
@@ -4884,11 +4981,11 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
int name_size() const;
void clear_name();
static const int kNameFieldNumber = 2;
- const ::google::protobuf::UninterpretedOption_NamePart& name(int index) const;
::google::protobuf::UninterpretedOption_NamePart* mutable_name(int index);
- ::google::protobuf::UninterpretedOption_NamePart* add_name();
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart >*
mutable_name();
+ const ::google::protobuf::UninterpretedOption_NamePart& name(int index) const;
+ ::google::protobuf::UninterpretedOption_NamePart* add_name();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart >&
name() const;
@@ -5005,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_;
@@ -5014,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();
};
// -------------------------------------------------------------------
@@ -5051,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();
@@ -5065,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);
@@ -5076,28 +5172,33 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
// implements Message ----------------------------------------------
- inline SourceCodeInfo_Location* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline SourceCodeInfo_Location* New() const final {
+ return CreateMaybeMessage<SourceCodeInfo_Location>(NULL);
+ }
- SourceCodeInfo_Location* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ SourceCodeInfo_Location* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<SourceCodeInfo_Location>(arena);
+ }
+ 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);
@@ -5113,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 ----------------------------------------------------
@@ -5225,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_;
@@ -5234,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();
};
// -------------------------------------------------------------------
@@ -5271,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();
@@ -5285,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);
@@ -5296,28 +5396,33 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
// implements Message ----------------------------------------------
- inline SourceCodeInfo* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline SourceCodeInfo* New() const final {
+ return CreateMaybeMessage<SourceCodeInfo>(NULL);
+ }
- SourceCodeInfo* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ SourceCodeInfo* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<SourceCodeInfo>(arena);
+ }
+ 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);
@@ -5333,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 ----------------------------------------------------
@@ -5345,11 +5450,11 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
int location_size() const;
void clear_location();
static const int kLocationFieldNumber = 1;
- const ::google::protobuf::SourceCodeInfo_Location& location(int index) const;
::google::protobuf::SourceCodeInfo_Location* mutable_location(int index);
- ::google::protobuf::SourceCodeInfo_Location* add_location();
::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location >*
mutable_location();
+ const ::google::protobuf::SourceCodeInfo_Location& location(int index) const;
+ ::google::protobuf::SourceCodeInfo_Location* add_location();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location >&
location() const;
@@ -5361,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();
};
// -------------------------------------------------------------------
@@ -5401,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();
@@ -5415,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);
@@ -5426,28 +5530,33 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
// implements Message ----------------------------------------------
- inline GeneratedCodeInfo_Annotation* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline GeneratedCodeInfo_Annotation* New() const final {
+ return CreateMaybeMessage<GeneratedCodeInfo_Annotation>(NULL);
+ }
- GeneratedCodeInfo_Annotation* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ GeneratedCodeInfo_Annotation* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<GeneratedCodeInfo_Annotation>(arena);
+ }
+ 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);
@@ -5463,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 ----------------------------------------------------
@@ -5533,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();
};
// -------------------------------------------------------------------
@@ -5577,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();
@@ -5591,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);
@@ -5602,28 +5710,33 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
// implements Message ----------------------------------------------
- inline GeneratedCodeInfo* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline GeneratedCodeInfo* New() const final {
+ return CreateMaybeMessage<GeneratedCodeInfo>(NULL);
+ }
- GeneratedCodeInfo* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ GeneratedCodeInfo* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<GeneratedCodeInfo>(arena);
+ }
+ 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);
@@ -5639,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 ----------------------------------------------------
@@ -5651,11 +5764,11 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
int annotation_size() const;
void clear_annotation();
static const int kAnnotationFieldNumber = 1;
- const ::google::protobuf::GeneratedCodeInfo_Annotation& annotation(int index) const;
::google::protobuf::GeneratedCodeInfo_Annotation* mutable_annotation(int index);
- ::google::protobuf::GeneratedCodeInfo_Annotation* add_annotation();
::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation >*
mutable_annotation();
+ const ::google::protobuf::GeneratedCodeInfo_Annotation& annotation(int index) const;
+ ::google::protobuf::GeneratedCodeInfo_Annotation* add_annotation();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation >&
annotation() const;
@@ -5667,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();
};
// ===================================================================
@@ -5690,23 +5802,23 @@ inline int FileDescriptorSet::file_size() const {
inline void FileDescriptorSet::clear_file() {
file_.Clear();
}
-inline const ::google::protobuf::FileDescriptorProto& FileDescriptorSet::file(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorSet.file)
- return file_.Get(index);
-}
inline ::google::protobuf::FileDescriptorProto* FileDescriptorSet::mutable_file(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorSet.file)
return file_.Mutable(index);
}
-inline ::google::protobuf::FileDescriptorProto* FileDescriptorSet::add_file() {
- // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorSet.file)
- return file_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >*
FileDescriptorSet::mutable_file() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorSet.file)
return &file_;
}
+inline const ::google::protobuf::FileDescriptorProto& FileDescriptorSet::file(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorSet.file)
+ return file_.Get(index);
+}
+inline ::google::protobuf::FileDescriptorProto* FileDescriptorSet::add_file() {
+ // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorSet.file)
+ return file_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >&
FileDescriptorSet::file() const {
// @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorSet.file)
@@ -5769,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) {
@@ -5854,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) {
@@ -6023,23 +6141,23 @@ inline int FileDescriptorProto::message_type_size() const {
inline void FileDescriptorProto::clear_message_type() {
message_type_.Clear();
}
-inline const ::google::protobuf::DescriptorProto& FileDescriptorProto::message_type(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.message_type)
- return message_type_.Get(index);
-}
inline ::google::protobuf::DescriptorProto* FileDescriptorProto::mutable_message_type(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.message_type)
return message_type_.Mutable(index);
}
-inline ::google::protobuf::DescriptorProto* FileDescriptorProto::add_message_type() {
- // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.message_type)
- return message_type_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >*
FileDescriptorProto::mutable_message_type() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.message_type)
return &message_type_;
}
+inline const ::google::protobuf::DescriptorProto& FileDescriptorProto::message_type(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.message_type)
+ return message_type_.Get(index);
+}
+inline ::google::protobuf::DescriptorProto* FileDescriptorProto::add_message_type() {
+ // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.message_type)
+ return message_type_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >&
FileDescriptorProto::message_type() const {
// @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.message_type)
@@ -6053,23 +6171,23 @@ inline int FileDescriptorProto::enum_type_size() const {
inline void FileDescriptorProto::clear_enum_type() {
enum_type_.Clear();
}
-inline const ::google::protobuf::EnumDescriptorProto& FileDescriptorProto::enum_type(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.enum_type)
- return enum_type_.Get(index);
-}
inline ::google::protobuf::EnumDescriptorProto* FileDescriptorProto::mutable_enum_type(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.enum_type)
return enum_type_.Mutable(index);
}
-inline ::google::protobuf::EnumDescriptorProto* FileDescriptorProto::add_enum_type() {
- // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.enum_type)
- return enum_type_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >*
FileDescriptorProto::mutable_enum_type() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.enum_type)
return &enum_type_;
}
+inline const ::google::protobuf::EnumDescriptorProto& FileDescriptorProto::enum_type(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.enum_type)
+ return enum_type_.Get(index);
+}
+inline ::google::protobuf::EnumDescriptorProto* FileDescriptorProto::add_enum_type() {
+ // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.enum_type)
+ return enum_type_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >&
FileDescriptorProto::enum_type() const {
// @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.enum_type)
@@ -6083,23 +6201,23 @@ inline int FileDescriptorProto::service_size() const {
inline void FileDescriptorProto::clear_service() {
service_.Clear();
}
-inline const ::google::protobuf::ServiceDescriptorProto& FileDescriptorProto::service(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.service)
- return service_.Get(index);
-}
inline ::google::protobuf::ServiceDescriptorProto* FileDescriptorProto::mutable_service(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.service)
return service_.Mutable(index);
}
-inline ::google::protobuf::ServiceDescriptorProto* FileDescriptorProto::add_service() {
- // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.service)
- return service_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto >*
FileDescriptorProto::mutable_service() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.service)
return &service_;
}
+inline const ::google::protobuf::ServiceDescriptorProto& FileDescriptorProto::service(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.service)
+ return service_.Get(index);
+}
+inline ::google::protobuf::ServiceDescriptorProto* FileDescriptorProto::add_service() {
+ // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.service)
+ return service_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto >&
FileDescriptorProto::service() const {
// @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.service)
@@ -6113,23 +6231,23 @@ inline int FileDescriptorProto::extension_size() const {
inline void FileDescriptorProto::clear_extension() {
extension_.Clear();
}
-inline const ::google::protobuf::FieldDescriptorProto& FileDescriptorProto::extension(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.extension)
- return extension_.Get(index);
-}
inline ::google::protobuf::FieldDescriptorProto* FileDescriptorProto::mutable_extension(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.extension)
return extension_.Mutable(index);
}
-inline ::google::protobuf::FieldDescriptorProto* FileDescriptorProto::add_extension() {
- // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.extension)
- return extension_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >*
FileDescriptorProto::mutable_extension() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.extension)
return &extension_;
}
+inline const ::google::protobuf::FieldDescriptorProto& FileDescriptorProto::extension(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.extension)
+ return extension_.Get(index);
+}
+inline ::google::protobuf::FieldDescriptorProto* FileDescriptorProto::add_extension() {
+ // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.extension)
+ return extension_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >&
FileDescriptorProto::extension() const {
// @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.extension)
@@ -6150,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)
@@ -6161,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;
@@ -6176,7 +6297,8 @@ inline ::google::protobuf::FileOptions* FileDescriptorProto::unsafe_arena_releas
inline ::google::protobuf::FileOptions* FileDescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- _slow_mutable_options();
+ auto* p = CreateMaybeMessage<::google::protobuf::FileOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.options)
return options_;
@@ -6215,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)
@@ -6226,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;
@@ -6241,7 +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) {
- _slow_mutable_source_code_info();
+ 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_;
@@ -6318,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) {
@@ -6417,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)
@@ -6428,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;
@@ -6443,7 +6575,8 @@ inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange
inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange::mutable_options() {
set_has_options();
if (options_ == NULL) {
- _slow_mutable_options();
+ auto* p = CreateMaybeMessage<::google::protobuf::ExtensionRangeOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.ExtensionRange.options)
return options_;
@@ -6576,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) {
@@ -6616,23 +6752,23 @@ inline int DescriptorProto::field_size() const {
inline void DescriptorProto::clear_field() {
field_.Clear();
}
-inline const ::google::protobuf::FieldDescriptorProto& DescriptorProto::field(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.field)
- return field_.Get(index);
-}
inline ::google::protobuf::FieldDescriptorProto* DescriptorProto::mutable_field(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.field)
return field_.Mutable(index);
}
-inline ::google::protobuf::FieldDescriptorProto* DescriptorProto::add_field() {
- // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.field)
- return field_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >*
DescriptorProto::mutable_field() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.field)
return &field_;
}
+inline const ::google::protobuf::FieldDescriptorProto& DescriptorProto::field(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.field)
+ return field_.Get(index);
+}
+inline ::google::protobuf::FieldDescriptorProto* DescriptorProto::add_field() {
+ // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.field)
+ return field_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >&
DescriptorProto::field() const {
// @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.field)
@@ -6646,23 +6782,23 @@ inline int DescriptorProto::extension_size() const {
inline void DescriptorProto::clear_extension() {
extension_.Clear();
}
-inline const ::google::protobuf::FieldDescriptorProto& DescriptorProto::extension(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.extension)
- return extension_.Get(index);
-}
inline ::google::protobuf::FieldDescriptorProto* DescriptorProto::mutable_extension(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.extension)
return extension_.Mutable(index);
}
-inline ::google::protobuf::FieldDescriptorProto* DescriptorProto::add_extension() {
- // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.extension)
- return extension_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >*
DescriptorProto::mutable_extension() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.extension)
return &extension_;
}
+inline const ::google::protobuf::FieldDescriptorProto& DescriptorProto::extension(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.extension)
+ return extension_.Get(index);
+}
+inline ::google::protobuf::FieldDescriptorProto* DescriptorProto::add_extension() {
+ // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.extension)
+ return extension_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >&
DescriptorProto::extension() const {
// @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.extension)
@@ -6676,23 +6812,23 @@ inline int DescriptorProto::nested_type_size() const {
inline void DescriptorProto::clear_nested_type() {
nested_type_.Clear();
}
-inline const ::google::protobuf::DescriptorProto& DescriptorProto::nested_type(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.nested_type)
- return nested_type_.Get(index);
-}
inline ::google::protobuf::DescriptorProto* DescriptorProto::mutable_nested_type(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.nested_type)
return nested_type_.Mutable(index);
}
-inline ::google::protobuf::DescriptorProto* DescriptorProto::add_nested_type() {
- // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.nested_type)
- return nested_type_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >*
DescriptorProto::mutable_nested_type() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.nested_type)
return &nested_type_;
}
+inline const ::google::protobuf::DescriptorProto& DescriptorProto::nested_type(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.nested_type)
+ return nested_type_.Get(index);
+}
+inline ::google::protobuf::DescriptorProto* DescriptorProto::add_nested_type() {
+ // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.nested_type)
+ return nested_type_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >&
DescriptorProto::nested_type() const {
// @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.nested_type)
@@ -6706,23 +6842,23 @@ inline int DescriptorProto::enum_type_size() const {
inline void DescriptorProto::clear_enum_type() {
enum_type_.Clear();
}
-inline const ::google::protobuf::EnumDescriptorProto& DescriptorProto::enum_type(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.enum_type)
- return enum_type_.Get(index);
-}
inline ::google::protobuf::EnumDescriptorProto* DescriptorProto::mutable_enum_type(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.enum_type)
return enum_type_.Mutable(index);
}
-inline ::google::protobuf::EnumDescriptorProto* DescriptorProto::add_enum_type() {
- // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.enum_type)
- return enum_type_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >*
DescriptorProto::mutable_enum_type() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.enum_type)
return &enum_type_;
}
+inline const ::google::protobuf::EnumDescriptorProto& DescriptorProto::enum_type(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.enum_type)
+ return enum_type_.Get(index);
+}
+inline ::google::protobuf::EnumDescriptorProto* DescriptorProto::add_enum_type() {
+ // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.enum_type)
+ return enum_type_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >&
DescriptorProto::enum_type() const {
// @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.enum_type)
@@ -6736,23 +6872,23 @@ inline int DescriptorProto::extension_range_size() const {
inline void DescriptorProto::clear_extension_range() {
extension_range_.Clear();
}
-inline const ::google::protobuf::DescriptorProto_ExtensionRange& DescriptorProto::extension_range(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.extension_range)
- return extension_range_.Get(index);
-}
inline ::google::protobuf::DescriptorProto_ExtensionRange* DescriptorProto::mutable_extension_range(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.extension_range)
return extension_range_.Mutable(index);
}
-inline ::google::protobuf::DescriptorProto_ExtensionRange* DescriptorProto::add_extension_range() {
- // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.extension_range)
- return extension_range_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange >*
DescriptorProto::mutable_extension_range() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.extension_range)
return &extension_range_;
}
+inline const ::google::protobuf::DescriptorProto_ExtensionRange& DescriptorProto::extension_range(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.extension_range)
+ return extension_range_.Get(index);
+}
+inline ::google::protobuf::DescriptorProto_ExtensionRange* DescriptorProto::add_extension_range() {
+ // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.extension_range)
+ return extension_range_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange >&
DescriptorProto::extension_range() const {
// @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.extension_range)
@@ -6766,23 +6902,23 @@ inline int DescriptorProto::oneof_decl_size() const {
inline void DescriptorProto::clear_oneof_decl() {
oneof_decl_.Clear();
}
-inline const ::google::protobuf::OneofDescriptorProto& DescriptorProto::oneof_decl(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.oneof_decl)
- return oneof_decl_.Get(index);
-}
inline ::google::protobuf::OneofDescriptorProto* DescriptorProto::mutable_oneof_decl(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.oneof_decl)
return oneof_decl_.Mutable(index);
}
-inline ::google::protobuf::OneofDescriptorProto* DescriptorProto::add_oneof_decl() {
- // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.oneof_decl)
- return oneof_decl_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::OneofDescriptorProto >*
DescriptorProto::mutable_oneof_decl() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.oneof_decl)
return &oneof_decl_;
}
+inline const ::google::protobuf::OneofDescriptorProto& DescriptorProto::oneof_decl(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.oneof_decl)
+ return oneof_decl_.Get(index);
+}
+inline ::google::protobuf::OneofDescriptorProto* DescriptorProto::add_oneof_decl() {
+ // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.oneof_decl)
+ return oneof_decl_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::OneofDescriptorProto >&
DescriptorProto::oneof_decl() const {
// @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.oneof_decl)
@@ -6803,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)
@@ -6814,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;
@@ -6829,7 +6968,8 @@ inline ::google::protobuf::MessageOptions* DescriptorProto::unsafe_arena_release
inline ::google::protobuf::MessageOptions* DescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- _slow_mutable_options();
+ auto* p = CreateMaybeMessage<::google::protobuf::MessageOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.options)
return options_;
@@ -6861,23 +7001,23 @@ inline int DescriptorProto::reserved_range_size() const {
inline void DescriptorProto::clear_reserved_range() {
reserved_range_.Clear();
}
-inline const ::google::protobuf::DescriptorProto_ReservedRange& DescriptorProto::reserved_range(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.reserved_range)
- return reserved_range_.Get(index);
-}
inline ::google::protobuf::DescriptorProto_ReservedRange* DescriptorProto::mutable_reserved_range(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.reserved_range)
return reserved_range_.Mutable(index);
}
-inline ::google::protobuf::DescriptorProto_ReservedRange* DescriptorProto::add_reserved_range() {
- // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.reserved_range)
- return reserved_range_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ReservedRange >*
DescriptorProto::mutable_reserved_range() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.reserved_range)
return &reserved_range_;
}
+inline const ::google::protobuf::DescriptorProto_ReservedRange& DescriptorProto::reserved_range(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.reserved_range)
+ return reserved_range_.Get(index);
+}
+inline ::google::protobuf::DescriptorProto_ReservedRange* DescriptorProto::add_reserved_range() {
+ // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.reserved_range)
+ return reserved_range_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ReservedRange >&
DescriptorProto::reserved_range() const {
// @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.reserved_range)
@@ -6964,23 +7104,23 @@ inline int ExtensionRangeOptions::uninterpreted_option_size() const {
inline void ExtensionRangeOptions::clear_uninterpreted_option() {
uninterpreted_option_.Clear();
}
-inline const ::google::protobuf::UninterpretedOption& ExtensionRangeOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.ExtensionRangeOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
inline ::google::protobuf::UninterpretedOption* ExtensionRangeOptions::mutable_uninterpreted_option(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.ExtensionRangeOptions.uninterpreted_option)
return uninterpreted_option_.Mutable(index);
}
-inline ::google::protobuf::UninterpretedOption* ExtensionRangeOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.ExtensionRangeOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
ExtensionRangeOptions::mutable_uninterpreted_option() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.ExtensionRangeOptions.uninterpreted_option)
return &uninterpreted_option_;
}
+inline const ::google::protobuf::UninterpretedOption& ExtensionRangeOptions::uninterpreted_option(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.ExtensionRangeOptions.uninterpreted_option)
+ return uninterpreted_option_.Get(index);
+}
+inline ::google::protobuf::UninterpretedOption* ExtensionRangeOptions::add_uninterpreted_option() {
+ // @@protoc_insertion_point(field_add:google.protobuf.ExtensionRangeOptions.uninterpreted_option)
+ return uninterpreted_option_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
ExtensionRangeOptions::uninterpreted_option() const {
// @@protoc_insertion_point(field_list:google.protobuf.ExtensionRangeOptions.uninterpreted_option)
@@ -7043,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) {
@@ -7202,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) {
@@ -7287,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) {
@@ -7372,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) {
@@ -7481,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) {
@@ -7528,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)
@@ -7539,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;
@@ -7554,7 +7712,8 @@ inline ::google::protobuf::FieldOptions* FieldDescriptorProto::unsafe_arena_rele
inline ::google::protobuf::FieldOptions* FieldDescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- _slow_mutable_options();
+ auto* p = CreateMaybeMessage<::google::protobuf::FieldOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.options)
return options_;
@@ -7635,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) {
@@ -7682,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)
@@ -7693,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;
@@ -7708,7 +7873,8 @@ inline ::google::protobuf::OneofOptions* OneofDescriptorProto::unsafe_arena_rele
inline ::google::protobuf::OneofOptions* OneofDescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- _slow_mutable_options();
+ auto* p = CreateMaybeMessage<::google::protobuf::OneofOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.OneofDescriptorProto.options)
return options_;
@@ -7841,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) {
@@ -7881,23 +8050,23 @@ inline int EnumDescriptorProto::value_size() const {
inline void EnumDescriptorProto::clear_value() {
value_.Clear();
}
-inline const ::google::protobuf::EnumValueDescriptorProto& EnumDescriptorProto::value(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.value)
- return value_.Get(index);
-}
inline ::google::protobuf::EnumValueDescriptorProto* EnumDescriptorProto::mutable_value(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.value)
return value_.Mutable(index);
}
-inline ::google::protobuf::EnumValueDescriptorProto* EnumDescriptorProto::add_value() {
- // @@protoc_insertion_point(field_add:google.protobuf.EnumDescriptorProto.value)
- return value_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto >*
EnumDescriptorProto::mutable_value() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumDescriptorProto.value)
return &value_;
}
+inline const ::google::protobuf::EnumValueDescriptorProto& EnumDescriptorProto::value(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.value)
+ return value_.Get(index);
+}
+inline ::google::protobuf::EnumValueDescriptorProto* EnumDescriptorProto::add_value() {
+ // @@protoc_insertion_point(field_add:google.protobuf.EnumDescriptorProto.value)
+ return value_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto >&
EnumDescriptorProto::value() const {
// @@protoc_insertion_point(field_list:google.protobuf.EnumDescriptorProto.value)
@@ -7918,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)
@@ -7929,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;
@@ -7944,7 +8116,8 @@ inline ::google::protobuf::EnumOptions* EnumDescriptorProto::unsafe_arena_releas
inline ::google::protobuf::EnumOptions* EnumDescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- _slow_mutable_options();
+ auto* p = CreateMaybeMessage<::google::protobuf::EnumOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.options)
return options_;
@@ -7976,23 +8149,23 @@ inline int EnumDescriptorProto::reserved_range_size() const {
inline void EnumDescriptorProto::clear_reserved_range() {
reserved_range_.Clear();
}
-inline const ::google::protobuf::EnumDescriptorProto_EnumReservedRange& EnumDescriptorProto::reserved_range(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.reserved_range)
- return reserved_range_.Get(index);
-}
inline ::google::protobuf::EnumDescriptorProto_EnumReservedRange* EnumDescriptorProto::mutable_reserved_range(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.reserved_range)
return reserved_range_.Mutable(index);
}
-inline ::google::protobuf::EnumDescriptorProto_EnumReservedRange* EnumDescriptorProto::add_reserved_range() {
- // @@protoc_insertion_point(field_add:google.protobuf.EnumDescriptorProto.reserved_range)
- return reserved_range_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >*
EnumDescriptorProto::mutable_reserved_range() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumDescriptorProto.reserved_range)
return &reserved_range_;
}
+inline const ::google::protobuf::EnumDescriptorProto_EnumReservedRange& EnumDescriptorProto::reserved_range(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.reserved_range)
+ return reserved_range_.Get(index);
+}
+inline ::google::protobuf::EnumDescriptorProto_EnumReservedRange* EnumDescriptorProto::add_reserved_range() {
+ // @@protoc_insertion_point(field_add:google.protobuf.EnumDescriptorProto.reserved_range)
+ return reserved_range_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >&
EnumDescriptorProto::reserved_range() const {
// @@protoc_insertion_point(field_list:google.protobuf.EnumDescriptorProto.reserved_range)
@@ -8124,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) {
@@ -8195,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)
@@ -8206,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;
@@ -8221,7 +8400,8 @@ inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::unsafe_ar
inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- _slow_mutable_options();
+ auto* p = CreateMaybeMessage<::google::protobuf::EnumValueOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueDescriptorProto.options)
return options_;
@@ -8302,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) {
@@ -8342,23 +8525,23 @@ inline int ServiceDescriptorProto::method_size() const {
inline void ServiceDescriptorProto::clear_method() {
method_.Clear();
}
-inline const ::google::protobuf::MethodDescriptorProto& ServiceDescriptorProto::method(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.method)
- return method_.Get(index);
-}
inline ::google::protobuf::MethodDescriptorProto* ServiceDescriptorProto::mutable_method(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.method)
return method_.Mutable(index);
}
-inline ::google::protobuf::MethodDescriptorProto* ServiceDescriptorProto::add_method() {
- // @@protoc_insertion_point(field_add:google.protobuf.ServiceDescriptorProto.method)
- return method_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto >*
ServiceDescriptorProto::mutable_method() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.ServiceDescriptorProto.method)
return &method_;
}
+inline const ::google::protobuf::MethodDescriptorProto& ServiceDescriptorProto::method(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.method)
+ return method_.Get(index);
+}
+inline ::google::protobuf::MethodDescriptorProto* ServiceDescriptorProto::add_method() {
+ // @@protoc_insertion_point(field_add:google.protobuf.ServiceDescriptorProto.method)
+ return method_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto >&
ServiceDescriptorProto::method() const {
// @@protoc_insertion_point(field_list:google.protobuf.ServiceDescriptorProto.method)
@@ -8379,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)
@@ -8390,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;
@@ -8405,7 +8591,8 @@ inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::unsafe_arena_
inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- _slow_mutable_options();
+ auto* p = CreateMaybeMessage<::google::protobuf::ServiceOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.options)
return options_;
@@ -8486,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) {
@@ -8571,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) {
@@ -8656,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) {
@@ -8703,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)
@@ -8714,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;
@@ -8729,7 +8928,8 @@ inline ::google::protobuf::MethodOptions* MethodDescriptorProto::unsafe_arena_re
inline ::google::protobuf::MethodOptions* MethodDescriptorProto::mutable_options() {
set_has_options();
if (options_ == NULL) {
- _slow_mutable_options();
+ auto* p = CreateMaybeMessage<::google::protobuf::MethodOptions>(GetArenaNoVirtual());
+ options_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.options)
return options_;
@@ -8858,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) {
@@ -8943,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) {
@@ -8978,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;
@@ -9002,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;
@@ -9026,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;
@@ -9050,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;
@@ -9125,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) {
@@ -9160,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;
@@ -9184,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;
@@ -9208,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;
@@ -9232,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;
@@ -9256,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;
@@ -9280,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;
@@ -9354,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) {
@@ -9439,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) {
@@ -9524,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) {
@@ -9609,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) {
@@ -9694,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) {
@@ -9727,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();
@@ -9734,23 +10134,23 @@ inline int FileOptions::uninterpreted_option_size() const {
inline void FileOptions::clear_uninterpreted_option() {
uninterpreted_option_.Clear();
}
-inline const ::google::protobuf::UninterpretedOption& FileOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
inline ::google::protobuf::UninterpretedOption* FileOptions::mutable_uninterpreted_option(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.uninterpreted_option)
return uninterpreted_option_.Mutable(index);
}
-inline ::google::protobuf::UninterpretedOption* FileOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.FileOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
FileOptions::mutable_uninterpreted_option() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.FileOptions.uninterpreted_option)
return &uninterpreted_option_;
}
+inline const ::google::protobuf::UninterpretedOption& FileOptions::uninterpreted_option(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.uninterpreted_option)
+ return uninterpreted_option_.Get(index);
+}
+inline ::google::protobuf::UninterpretedOption* FileOptions::add_uninterpreted_option() {
+ // @@protoc_insertion_point(field_add:google.protobuf.FileOptions.uninterpreted_option)
+ return uninterpreted_option_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
FileOptions::uninterpreted_option() const {
// @@protoc_insertion_point(field_list:google.protobuf.FileOptions.uninterpreted_option)
@@ -9864,23 +10264,23 @@ inline int MessageOptions::uninterpreted_option_size() const {
inline void MessageOptions::clear_uninterpreted_option() {
uninterpreted_option_.Clear();
}
-inline const ::google::protobuf::UninterpretedOption& MessageOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
inline ::google::protobuf::UninterpretedOption* MessageOptions::mutable_uninterpreted_option(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.MessageOptions.uninterpreted_option)
return uninterpreted_option_.Mutable(index);
}
-inline ::google::protobuf::UninterpretedOption* MessageOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.MessageOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
MessageOptions::mutable_uninterpreted_option() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.MessageOptions.uninterpreted_option)
return &uninterpreted_option_;
}
+inline const ::google::protobuf::UninterpretedOption& MessageOptions::uninterpreted_option(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.uninterpreted_option)
+ return uninterpreted_option_.Get(index);
+}
+inline ::google::protobuf::UninterpretedOption* MessageOptions::add_uninterpreted_option() {
+ // @@protoc_insertion_point(field_add:google.protobuf.MessageOptions.uninterpreted_option)
+ return uninterpreted_option_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
MessageOptions::uninterpreted_option() const {
// @@protoc_insertion_point(field_list:google.protobuf.MessageOptions.uninterpreted_option)
@@ -10044,23 +10444,23 @@ inline int FieldOptions::uninterpreted_option_size() const {
inline void FieldOptions::clear_uninterpreted_option() {
uninterpreted_option_.Clear();
}
-inline const ::google::protobuf::UninterpretedOption& FieldOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
inline ::google::protobuf::UninterpretedOption* FieldOptions::mutable_uninterpreted_option(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldOptions.uninterpreted_option)
return uninterpreted_option_.Mutable(index);
}
-inline ::google::protobuf::UninterpretedOption* FieldOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.FieldOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
FieldOptions::mutable_uninterpreted_option() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.FieldOptions.uninterpreted_option)
return &uninterpreted_option_;
}
+inline const ::google::protobuf::UninterpretedOption& FieldOptions::uninterpreted_option(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.uninterpreted_option)
+ return uninterpreted_option_.Get(index);
+}
+inline ::google::protobuf::UninterpretedOption* FieldOptions::add_uninterpreted_option() {
+ // @@protoc_insertion_point(field_add:google.protobuf.FieldOptions.uninterpreted_option)
+ return uninterpreted_option_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
FieldOptions::uninterpreted_option() const {
// @@protoc_insertion_point(field_list:google.protobuf.FieldOptions.uninterpreted_option)
@@ -10078,23 +10478,23 @@ inline int OneofOptions::uninterpreted_option_size() const {
inline void OneofOptions::clear_uninterpreted_option() {
uninterpreted_option_.Clear();
}
-inline const ::google::protobuf::UninterpretedOption& OneofOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.OneofOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
inline ::google::protobuf::UninterpretedOption* OneofOptions::mutable_uninterpreted_option(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.OneofOptions.uninterpreted_option)
return uninterpreted_option_.Mutable(index);
}
-inline ::google::protobuf::UninterpretedOption* OneofOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.OneofOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
OneofOptions::mutable_uninterpreted_option() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.OneofOptions.uninterpreted_option)
return &uninterpreted_option_;
}
+inline const ::google::protobuf::UninterpretedOption& OneofOptions::uninterpreted_option(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.OneofOptions.uninterpreted_option)
+ return uninterpreted_option_.Get(index);
+}
+inline ::google::protobuf::UninterpretedOption* OneofOptions::add_uninterpreted_option() {
+ // @@protoc_insertion_point(field_add:google.protobuf.OneofOptions.uninterpreted_option)
+ return uninterpreted_option_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
OneofOptions::uninterpreted_option() const {
// @@protoc_insertion_point(field_list:google.protobuf.OneofOptions.uninterpreted_option)
@@ -10160,23 +10560,23 @@ inline int EnumOptions::uninterpreted_option_size() const {
inline void EnumOptions::clear_uninterpreted_option() {
uninterpreted_option_.Clear();
}
-inline const ::google::protobuf::UninterpretedOption& EnumOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
inline ::google::protobuf::UninterpretedOption* EnumOptions::mutable_uninterpreted_option(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumOptions.uninterpreted_option)
return uninterpreted_option_.Mutable(index);
}
-inline ::google::protobuf::UninterpretedOption* EnumOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.EnumOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
EnumOptions::mutable_uninterpreted_option() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumOptions.uninterpreted_option)
return &uninterpreted_option_;
}
+inline const ::google::protobuf::UninterpretedOption& EnumOptions::uninterpreted_option(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.EnumOptions.uninterpreted_option)
+ return uninterpreted_option_.Get(index);
+}
+inline ::google::protobuf::UninterpretedOption* EnumOptions::add_uninterpreted_option() {
+ // @@protoc_insertion_point(field_add:google.protobuf.EnumOptions.uninterpreted_option)
+ return uninterpreted_option_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
EnumOptions::uninterpreted_option() const {
// @@protoc_insertion_point(field_list:google.protobuf.EnumOptions.uninterpreted_option)
@@ -10218,23 +10618,23 @@ inline int EnumValueOptions::uninterpreted_option_size() const {
inline void EnumValueOptions::clear_uninterpreted_option() {
uninterpreted_option_.Clear();
}
-inline const ::google::protobuf::UninterpretedOption& EnumValueOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumValueOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
inline ::google::protobuf::UninterpretedOption* EnumValueOptions::mutable_uninterpreted_option(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueOptions.uninterpreted_option)
return uninterpreted_option_.Mutable(index);
}
-inline ::google::protobuf::UninterpretedOption* EnumValueOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.EnumValueOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
EnumValueOptions::mutable_uninterpreted_option() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumValueOptions.uninterpreted_option)
return &uninterpreted_option_;
}
+inline const ::google::protobuf::UninterpretedOption& EnumValueOptions::uninterpreted_option(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.EnumValueOptions.uninterpreted_option)
+ return uninterpreted_option_.Get(index);
+}
+inline ::google::protobuf::UninterpretedOption* EnumValueOptions::add_uninterpreted_option() {
+ // @@protoc_insertion_point(field_add:google.protobuf.EnumValueOptions.uninterpreted_option)
+ return uninterpreted_option_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
EnumValueOptions::uninterpreted_option() const {
// @@protoc_insertion_point(field_list:google.protobuf.EnumValueOptions.uninterpreted_option)
@@ -10276,23 +10676,23 @@ inline int ServiceOptions::uninterpreted_option_size() const {
inline void ServiceOptions::clear_uninterpreted_option() {
uninterpreted_option_.Clear();
}
-inline const ::google::protobuf::UninterpretedOption& ServiceOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.ServiceOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
inline ::google::protobuf::UninterpretedOption* ServiceOptions::mutable_uninterpreted_option(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.ServiceOptions.uninterpreted_option)
return uninterpreted_option_.Mutable(index);
}
-inline ::google::protobuf::UninterpretedOption* ServiceOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.ServiceOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
ServiceOptions::mutable_uninterpreted_option() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.ServiceOptions.uninterpreted_option)
return &uninterpreted_option_;
}
+inline const ::google::protobuf::UninterpretedOption& ServiceOptions::uninterpreted_option(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.ServiceOptions.uninterpreted_option)
+ return uninterpreted_option_.Get(index);
+}
+inline ::google::protobuf::UninterpretedOption* ServiceOptions::add_uninterpreted_option() {
+ // @@protoc_insertion_point(field_add:google.protobuf.ServiceOptions.uninterpreted_option)
+ return uninterpreted_option_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
ServiceOptions::uninterpreted_option() const {
// @@protoc_insertion_point(field_list:google.protobuf.ServiceOptions.uninterpreted_option)
@@ -10359,23 +10759,23 @@ inline int MethodOptions::uninterpreted_option_size() const {
inline void MethodOptions::clear_uninterpreted_option() {
uninterpreted_option_.Clear();
}
-inline const ::google::protobuf::UninterpretedOption& MethodOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.MethodOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
inline ::google::protobuf::UninterpretedOption* MethodOptions::mutable_uninterpreted_option(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.MethodOptions.uninterpreted_option)
return uninterpreted_option_.Mutable(index);
}
-inline ::google::protobuf::UninterpretedOption* MethodOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.MethodOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
MethodOptions::mutable_uninterpreted_option() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.MethodOptions.uninterpreted_option)
return &uninterpreted_option_;
}
+inline const ::google::protobuf::UninterpretedOption& MethodOptions::uninterpreted_option(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.MethodOptions.uninterpreted_option)
+ return uninterpreted_option_.Get(index);
+}
+inline ::google::protobuf::UninterpretedOption* MethodOptions::add_uninterpreted_option() {
+ // @@protoc_insertion_point(field_add:google.protobuf.MethodOptions.uninterpreted_option)
+ return uninterpreted_option_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
MethodOptions::uninterpreted_option() const {
// @@protoc_insertion_point(field_list:google.protobuf.MethodOptions.uninterpreted_option)
@@ -10438,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) {
@@ -10506,23 +10909,23 @@ inline int UninterpretedOption::name_size() const {
inline void UninterpretedOption::clear_name() {
name_.Clear();
}
-inline const ::google::protobuf::UninterpretedOption_NamePart& UninterpretedOption::name(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.name)
- return name_.Get(index);
-}
inline ::google::protobuf::UninterpretedOption_NamePart* UninterpretedOption::mutable_name(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.name)
return name_.Mutable(index);
}
-inline ::google::protobuf::UninterpretedOption_NamePart* UninterpretedOption::add_name() {
- // @@protoc_insertion_point(field_add:google.protobuf.UninterpretedOption.name)
- return name_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart >*
UninterpretedOption::mutable_name() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.UninterpretedOption.name)
return &name_;
}
+inline const ::google::protobuf::UninterpretedOption_NamePart& UninterpretedOption::name(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.name)
+ return name_.Get(index);
+}
+inline ::google::protobuf::UninterpretedOption_NamePart* UninterpretedOption::add_name() {
+ // @@protoc_insertion_point(field_add:google.protobuf.UninterpretedOption.name)
+ return name_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart >&
UninterpretedOption::name() const {
// @@protoc_insertion_point(field_list:google.protobuf.UninterpretedOption.name)
@@ -10581,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) {
@@ -10738,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) {
@@ -10823,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) {
@@ -10972,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) {
@@ -11057,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) {
@@ -11170,23 +11588,23 @@ inline int SourceCodeInfo::location_size() const {
inline void SourceCodeInfo::clear_location() {
location_.Clear();
}
-inline const ::google::protobuf::SourceCodeInfo_Location& SourceCodeInfo::location(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.location)
- return location_.Get(index);
-}
inline ::google::protobuf::SourceCodeInfo_Location* SourceCodeInfo::mutable_location(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.location)
return location_.Mutable(index);
}
-inline ::google::protobuf::SourceCodeInfo_Location* SourceCodeInfo::add_location() {
- // @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.location)
- return location_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location >*
SourceCodeInfo::mutable_location() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.SourceCodeInfo.location)
return &location_;
}
+inline const ::google::protobuf::SourceCodeInfo_Location& SourceCodeInfo::location(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.location)
+ return location_.Get(index);
+}
+inline ::google::protobuf::SourceCodeInfo_Location* SourceCodeInfo::add_location() {
+ // @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.location)
+ return location_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location >&
SourceCodeInfo::location() const {
// @@protoc_insertion_point(field_list:google.protobuf.SourceCodeInfo.location)
@@ -11279,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) {
@@ -11371,23 +11792,23 @@ inline int GeneratedCodeInfo::annotation_size() const {
inline void GeneratedCodeInfo::clear_annotation() {
annotation_.Clear();
}
-inline const ::google::protobuf::GeneratedCodeInfo_Annotation& GeneratedCodeInfo::annotation(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.annotation)
- return annotation_.Get(index);
-}
inline ::google::protobuf::GeneratedCodeInfo_Annotation* GeneratedCodeInfo::mutable_annotation(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.GeneratedCodeInfo.annotation)
return annotation_.Mutable(index);
}
-inline ::google::protobuf::GeneratedCodeInfo_Annotation* GeneratedCodeInfo::add_annotation() {
- // @@protoc_insertion_point(field_add:google.protobuf.GeneratedCodeInfo.annotation)
- return annotation_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation >*
GeneratedCodeInfo::mutable_annotation() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.GeneratedCodeInfo.annotation)
return &annotation_;
}
+inline const ::google::protobuf::GeneratedCodeInfo_Annotation& GeneratedCodeInfo::annotation(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.annotation)
+ return annotation_.Get(index);
+}
+inline ::google::protobuf::GeneratedCodeInfo_Annotation* GeneratedCodeInfo::add_annotation() {
+ // @@protoc_insertion_point(field_add:google.protobuf.GeneratedCodeInfo.annotation)
+ return annotation_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation >&
GeneratedCodeInfo::annotation() const {
// @@protoc_insertion_point(field_list:google.protobuf.GeneratedCodeInfo.annotation)
@@ -11458,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();
@@ -11494,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..d61f2a6a 100644
--- a/src/google/protobuf/descriptor_database.h
+++ b/src/google/protobuf/descriptor_database.h
@@ -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.
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 6cca0ada..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>
@@ -431,6 +428,7 @@ TEST_F(FileDescriptorTest, FindExtensionByNumber) {
EXPECT_TRUE(pool_.FindExtensionByNumber(foo_message_, 2) == NULL);
}
+
TEST_F(FileDescriptorTest, BuildAgain) {
// Test that if te call BuildFile again on the same input we get the same
// FileDescriptor back.
@@ -973,6 +971,7 @@ TEST_F(DescriptorTest, FieldEnumType) {
EXPECT_EQ(enum_, bar_->enum_type());
}
+
// ===================================================================
// Test simple flat messages and fields.
@@ -1943,6 +1942,7 @@ TEST_F(ExtensionDescriptorTest, FindAllExtensions) {
EXPECT_EQ(39, extensions[3]->number());
}
+
TEST_F(ExtensionDescriptorTest, DuplicateFieldNumber) {
DescriptorPool pool;
FileDescriptorProto file_proto;
@@ -2249,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) {
@@ -2679,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) {
@@ -3949,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) {
@@ -3963,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) {
@@ -3977,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) {
@@ -6890,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",
@@ -6934,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
@@ -6953,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));
}
@@ -6986,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 0a8aad48..ddc063db 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];
@@ -71,15 +68,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
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 ::google::protobuf::internal::once_flag once;
+ ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
@@ -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() {
@@ -177,9 +170,7 @@ void Duration::ArenaDtor(void* object) {
void Duration::RegisterArenaDtor(::google::protobuf::Arena* 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,13 +178,10 @@ 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();
}
-Duration* Duration::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<Duration>(arena);
-}
void Duration::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Duration)
@@ -213,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)) {
@@ -337,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;
}
@@ -415,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 {
@@ -427,5 +412,12 @@ void Duration::InternalSwap(Duration* other) {
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
+namespace google {
+namespace protobuf {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Duration* Arena::CreateMaybeMessage< ::google::protobuf::Duration >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::Duration >(arena);
+}
+} // namespace protobuf
+} // namespace google
// @@protoc_insertion_point(global_scope)
diff --git a/src/google/protobuf/duration.pb.h b/src/google/protobuf/duration.pb.h
index e13328ac..3d0889d1 100644
--- a/src/google/protobuf/duration.pb.h
+++ b/src/google/protobuf/duration.pb.h
@@ -1,8 +1,8 @@
// 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>
@@ -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,6 +54,11 @@ LIBPROTOBUF_EXPORT extern DurationDefaultTypeInternal _Duration_default_instance
} // namespace google
namespace google {
namespace protobuf {
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Duration* Arena::CreateMaybeMessage<::google::protobuf::Duration>(Arena*);
+} // namespace protobuf
+} // namespace google
+namespace google {
+namespace protobuf {
// ===================================================================
@@ -86,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();
@@ -100,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);
@@ -111,28 +113,33 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
// implements Message ----------------------------------------------
- inline Duration* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Duration* New() const final {
+ return CreateMaybeMessage<Duration>(NULL);
+ }
- Duration* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Duration* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Duration>(arena);
+ }
+ 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);
@@ -148,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 ----------------------------------------------------
@@ -175,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();
};
// ===================================================================
@@ -229,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 cdd43243..ceedf500 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;
@@ -263,7 +260,7 @@ class DynamicMessage : public Message {
Message* New() const;
Message* New(::google::protobuf::Arena* arena) const;
- ::google::protobuf::Arena* GetArena() const { return NULL; };
+ ::google::protobuf::Arena* GetArena() const { return arena_; }
int GetCachedSize() const;
void SetCachedSize(int size) const;
@@ -282,7 +279,6 @@ class DynamicMessage : public Message {
#endif // !_MSC_VER
private:
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMessage);
DynamicMessage(const TypeInfo* type_info, ::google::protobuf::Arena* arena);
void SharedCtor(bool lock_factory);
@@ -302,25 +298,25 @@ class DynamicMessage : public Message {
}
const TypeInfo* type_info_;
+ Arena* const arena_;
// TODO(kenton): Make this an atomic<int> when C++ supports it.
mutable int cached_byte_size_;
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMessage);
};
DynamicMessage::DynamicMessage(const TypeInfo* type_info)
- : type_info_(type_info),
- cached_byte_size_(0) {
+ : type_info_(type_info), arena_(NULL), cached_byte_size_(0) {
SharedCtor(true);
}
DynamicMessage::DynamicMessage(const TypeInfo* type_info,
::google::protobuf::Arena* arena)
- : type_info_(type_info),
- cached_byte_size_(0) {
+ : type_info_(type_info), arena_(arena), cached_byte_size_(0) {
SharedCtor(true);
}
DynamicMessage::DynamicMessage(const TypeInfo* type_info, bool lock_factory)
- : type_info_(type_info), cached_byte_size_(0) {
+ : type_info_(type_info), arena_(NULL), cached_byte_size_(0) {
SharedCtor(lock_factory);
}
@@ -342,10 +338,10 @@ void DynamicMessage::SharedCtor(bool lock_factory) {
}
new (OffsetToPointer(type_info_->internal_metadata_offset))
- InternalMetadataWithArena;
+ InternalMetadataWithArena(arena_);
if (type_info_->extensions_offset != -1) {
- new (OffsetToPointer(type_info_->extensions_offset)) ExtensionSet;
+ new (OffsetToPointer(type_info_->extensions_offset)) ExtensionSet(arena_);
}
for (int i = 0; i < descriptor->field_count(); i++) {
const FieldDescriptor* field = descriptor->field(i);
@@ -354,14 +350,14 @@ void DynamicMessage::SharedCtor(bool lock_factory) {
continue;
}
switch (field->cpp_type()) {
-#define HANDLE_TYPE(CPPTYPE, TYPE) \
- case FieldDescriptor::CPPTYPE_##CPPTYPE: \
- if (!field->is_repeated()) { \
- new(field_ptr) TYPE(field->default_value_##TYPE()); \
- } else { \
- new(field_ptr) RepeatedField<TYPE>(); \
- } \
- break;
+#define HANDLE_TYPE(CPPTYPE, TYPE) \
+ case FieldDescriptor::CPPTYPE_##CPPTYPE: \
+ if (!field->is_repeated()) { \
+ new (field_ptr) TYPE(field->default_value_##TYPE()); \
+ } else { \
+ new (field_ptr) RepeatedField<TYPE>(arena_); \
+ } \
+ break;
HANDLE_TYPE(INT32 , int32 );
HANDLE_TYPE(INT64 , int64 );
@@ -376,7 +372,7 @@ void DynamicMessage::SharedCtor(bool lock_factory) {
if (!field->is_repeated()) {
new(field_ptr) int(field->default_value_enum()->number());
} else {
- new(field_ptr) RepeatedField<int>();
+ new (field_ptr) RepeatedField<int>(arena_);
}
break;
@@ -397,7 +393,7 @@ void DynamicMessage::SharedCtor(bool lock_factory) {
ArenaStringPtr* asp = new(field_ptr) ArenaStringPtr();
asp->UnsafeSetDefault(default_value);
} else {
- new(field_ptr) RepeatedPtrField<string>();
+ new (field_ptr) RepeatedPtrField<string>(arena_);
}
break;
}
@@ -412,15 +408,28 @@ void DynamicMessage::SharedCtor(bool lock_factory) {
// when the constructor is called inside GetPrototype(), in which
// case we have already locked the factory.
if (lock_factory) {
- new (field_ptr) DynamicMapField(
- type_info_->factory->GetPrototype(field->message_type()));
+ if (arena_ != NULL) {
+ new (field_ptr) DynamicMapField(
+ type_info_->factory->GetPrototype(field->message_type()),
+ arena_);
+ } else {
+ new (field_ptr) DynamicMapField(
+ type_info_->factory->GetPrototype(field->message_type()));
+ }
} else {
- new (field_ptr)
- DynamicMapField(type_info_->factory->GetPrototypeNoLock(
- field->message_type()));
+ if (arena_ != NULL) {
+ new (field_ptr)
+ DynamicMapField(type_info_->factory->GetPrototypeNoLock(
+ field->message_type()),
+ arena_);
+ } else {
+ new (field_ptr)
+ DynamicMapField(type_info_->factory->GetPrototypeNoLock(
+ field->message_type()));
+ }
}
} else {
- new (field_ptr) RepeatedPtrField<Message>();
+ new (field_ptr) RepeatedPtrField<Message>(arena_);
}
}
break;
@@ -568,19 +577,17 @@ void DynamicMessage::CrossLinkPrototypes() {
}
}
-Message* DynamicMessage::New() const {
- void* new_base = operator new(type_info_->size);
- memset(new_base, 0, type_info_->size);
- return new(new_base) DynamicMessage(type_info_);
-}
+Message* DynamicMessage::New() const { return New(NULL); }
Message* DynamicMessage::New(::google::protobuf::Arena* arena) const {
if (arena != NULL) {
- Message* message = New();
- arena->Own(message);
- return message;
+ void* new_base = Arena::CreateArray<char>(arena, type_info_->size);
+ memset(new_base, 0, type_info_->size);
+ return new (new_base) DynamicMessage(type_info_, arena);
} else {
- return New();
+ void* new_base = operator new(type_info_->size);
+ memset(new_base, 0, type_info_->size);
+ return new (new_base) DynamicMessage(type_info_);
}
}
diff --git a/src/google/protobuf/dynamic_message.h b/src/google/protobuf/dynamic_message.h
index e29b148d..d84cc8af 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>
@@ -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 fe51d8cf..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>
@@ -60,7 +57,7 @@
namespace google {
namespace protobuf {
-class DynamicMessageTest : public testing::Test {
+class DynamicMessageTest : public ::testing::TestWithParam<bool> {
protected:
DescriptorPool pool_;
DynamicMessageFactory factory_;
@@ -144,38 +141,54 @@ TEST_F(DynamicMessageTest, Defaults) {
reflection_tester.ExpectClearViaReflection(*prototype_);
}
-TEST_F(DynamicMessageTest, IndependentOffsets) {
+TEST_P(DynamicMessageTest, IndependentOffsets) {
// 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(prototype_->New());
+ Arena arena;
+ Message* message = prototype_->New(GetParam()? &arena : NULL);
TestUtil::ReflectionTester reflection_tester(descriptor_);
- reflection_tester.SetAllFieldsViaReflection(message.get());
+ reflection_tester.SetAllFieldsViaReflection(message);
reflection_tester.ExpectAllFieldsSetViaReflection(*message);
+
+ if (!GetParam()) {
+ delete message;
+ }
}
-TEST_F(DynamicMessageTest, Extensions) {
+TEST_P(DynamicMessageTest, Extensions) {
// Check that extensions work.
- google::protobuf::scoped_ptr<Message> message(extensions_prototype_->New());
+ Arena arena;
+ Message* message = extensions_prototype_->New(GetParam()? &arena : NULL);
TestUtil::ReflectionTester reflection_tester(extensions_descriptor_);
- reflection_tester.SetAllFieldsViaReflection(message.get());
+ reflection_tester.SetAllFieldsViaReflection(message);
reflection_tester.ExpectAllFieldsSetViaReflection(*message);
+
+ if (!GetParam()) {
+ delete message;
+ }
}
-TEST_F(DynamicMessageTest, PackedFields) {
+TEST_P(DynamicMessageTest, PackedFields) {
// Check that packed fields work properly.
- google::protobuf::scoped_ptr<Message> message(packed_prototype_->New());
+ Arena arena;
+ Message* message = packed_prototype_->New(GetParam()? &arena : NULL);
TestUtil::ReflectionTester reflection_tester(packed_descriptor_);
- reflection_tester.SetPackedFieldsViaReflection(message.get());
+ reflection_tester.SetPackedFieldsViaReflection(message);
reflection_tester.ExpectPackedFieldsSetViaReflection(*message);
+
+ if (!GetParam()) {
+ delete message;
+ }
}
-TEST_F(DynamicMessageTest, Oneof) {
+TEST_P(DynamicMessageTest, Oneof) {
// Check that oneof fields work properly.
- google::protobuf::scoped_ptr<Message> message(oneof_prototype_->New());
+ Arena arena;
+ Message* message = oneof_prototype_->New(GetParam()? &arena : NULL);
// Check default values.
const Descriptor* descriptor = message->GetDescriptor();
@@ -226,29 +239,46 @@ TEST_F(DynamicMessageTest, Oneof) {
// Check set functions.
TestUtil::ReflectionTester reflection_tester(oneof_descriptor_);
- reflection_tester.SetOneofViaReflection(message.get());
+ reflection_tester.SetOneofViaReflection(message);
reflection_tester.ExpectOneofSetViaReflection(*message);
+
+ if (!GetParam()) {
+ delete message;
+ }
}
-TEST_F(DynamicMessageTest, SpaceUsed) {
+TEST_P(DynamicMessageTest, SpaceUsed) {
// Test that SpaceUsed() works properly
// 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(prototype_->New());
+ Arena arena;
+ Message* message = prototype_->New(GetParam()? &arena : NULL);
TestUtil::ReflectionTester reflection_tester(descriptor_);
int initial_space_used = message->SpaceUsed();
- reflection_tester.SetAllFieldsViaReflection(message.get());
+ reflection_tester.SetAllFieldsViaReflection(message);
EXPECT_LT(initial_space_used, message->SpaceUsed());
+
+ if (!GetParam()) {
+ delete message;
+ }
}
TEST_F(DynamicMessageTest, Arena) {
Arena arena;
Message* message = prototype_->New(&arena);
- (void)message; // avoid unused-variable error.
+ Message* extension_message = extensions_prototype_->New(&arena);
+ Message* packed_message = packed_prototype_->New(&arena);
+ Message* oneof_message = oneof_prototype_->New(&arena);
+
+ // avoid unused-variable error.
+ (void)message;
+ (void)extension_message;
+ (void)packed_message;
+ (void)oneof_message;
// Return without freeing: should not leak.
}
@@ -286,6 +316,7 @@ TEST_F(DynamicMessageTest, Proto3) {
delete message;
}
+INSTANTIATE_TEST_CASE_P(UseArena, DynamicMessageTest, ::testing::Bool());
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/empty.pb.cc b/src/google/protobuf/empty.pb.cc
index caa019e8..9b53c546 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];
@@ -69,15 +66,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
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 ::google::protobuf::internal::once_flag once;
+ ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
@@ -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() {
@@ -166,9 +159,7 @@ void Empty::ArenaDtor(void* object) {
void Empty::RegisterArenaDtor(::google::protobuf::Arena* 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,13 +167,10 @@ 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();
}
-Empty* Empty::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<Empty>(arena);
-}
void Empty::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Empty)
@@ -199,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:
@@ -256,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;
}
@@ -326,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 {
@@ -338,5 +323,12 @@ void Empty::InternalSwap(Empty* other) {
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
+namespace google {
+namespace protobuf {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Empty* Arena::CreateMaybeMessage< ::google::protobuf::Empty >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::Empty >(arena);
+}
+} // namespace protobuf
+} // namespace google
// @@protoc_insertion_point(global_scope)
diff --git a/src/google/protobuf/empty.pb.h b/src/google/protobuf/empty.pb.h
index 76e0e4c6..53857e5f 100644
--- a/src/google/protobuf/empty.pb.h
+++ b/src/google/protobuf/empty.pb.h
@@ -1,8 +1,8 @@
// 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>
@@ -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,6 +54,11 @@ LIBPROTOBUF_EXPORT extern EmptyDefaultTypeInternal _Empty_default_instance_;
} // namespace google
namespace google {
namespace protobuf {
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Empty* Arena::CreateMaybeMessage<::google::protobuf::Empty>(Arena*);
+} // namespace protobuf
+} // namespace google
+namespace google {
+namespace protobuf {
// ===================================================================
@@ -86,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();
@@ -100,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);
@@ -111,28 +113,33 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
// implements Message ----------------------------------------------
- inline Empty* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Empty* New() const final {
+ return CreateMaybeMessage<Empty>(NULL);
+ }
- Empty* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Empty* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Empty>(arena);
+ }
+ 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);
@@ -148,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 ----------------------------------------------------
@@ -161,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();
};
// ===================================================================
@@ -187,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 cf6b6fb4..b587b38f 100644
--- a/src/google/protobuf/extension_set.cc
+++ b/src/google/protobuf/extension_set.cc
@@ -33,6 +33,8 @@
// 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>
#include <google/protobuf/extension_set.h>
@@ -178,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;
}
}
}
@@ -202,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();
}
// ===================================================================
@@ -266,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; \
} \
} \
\
@@ -291,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, \
@@ -335,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,
@@ -392,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 =
@@ -409,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;
}
@@ -421,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;
}
}
@@ -446,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,
@@ -482,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;
}
}
@@ -508,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,
@@ -542,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;
}
}
}
@@ -662,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;
}
}
@@ -721,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,
@@ -750,8 +757,10 @@ 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 = extension->repeated_message_value
- ->AddFromCleared<GenericTypeHandler<MessageLite> >();
+ MessageLite* result =
+ reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
+ extension->repeated_message_value)
+ ->AddFromCleared<GenericTypeHandler<MessageLite> >();
if (result == NULL) {
result = prototype.New(arena_);
extension->repeated_message_value->AddAllocated(result);
@@ -767,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)) {
@@ -808,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)) {
@@ -861,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(
@@ -925,8 +955,10 @@ void ExtensionSet::InternalExtensionMergeFrom(
other_extension.repeated_message_value;
for (int i = 0; i < other_repeated_message->size(); i++) {
const MessageLite& other_message = other_repeated_message->Get(i);
- MessageLite* target = extension->repeated_message_value
- ->AddFromCleared<GenericTypeHandler<MessageLite> >();
+ MessageLite* target =
+ reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
+ extension->repeated_message_value)
+ ->AddFromCleared<GenericTypeHandler<MessageLite> >();
if (target == NULL) {
target = other_message.New(arena_);
extension->repeated_message_value->AddAllocated(target);
@@ -1015,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
@@ -1032,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
@@ -1052,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;
}
}
@@ -1086,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;
}
@@ -1346,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;
}
@@ -1371,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;
}
// ===================================================================
@@ -1747,6 +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 0a5d98f2..c4796629 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 {
@@ -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;
@@ -483,6 +488,8 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
}
private:
+ virtual void UnusedKeyMethod(); // Dummy key method to avoid weak vtable.
+
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(LazyMessageExtension);
};
struct Extension {
@@ -565,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);
@@ -631,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);
};
@@ -1125,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 fad31340..a3c84167 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>
@@ -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;
}
}
@@ -259,8 +257,10 @@ 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 = extension->repeated_message_value
- ->AddFromCleared<GenericTypeHandler<MessageLite> >();
+ MessageLite* result =
+ reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
+ extension->repeated_message_value)
+ ->AddFromCleared<GenericTypeHandler<MessageLite> >();
if (result == NULL) {
const MessageLite* prototype;
if (extension->repeated_message_value->size() == 0) {
@@ -347,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;
}
@@ -391,7 +387,9 @@ size_t ExtensionSet::Extension::SpaceUsedExcludingSelfLong() const {
// type handler.
total_size +=
sizeof(*repeated_message_value) +
- RepeatedMessage_SpaceUsedExcludingSelfLong(repeated_message_value);
+ RepeatedMessage_SpaceUsedExcludingSelfLong(
+ reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
+ repeated_message_value));
break;
}
} else {
@@ -434,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;
}
@@ -779,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);
@@ -792,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 3e71b253..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;
@@ -792,11 +813,16 @@ TEST(ExtensionSetTest, SpaceUsedExcludingSelf) {
message.AddExtension(unittest::repeated_##type##_extension, value); \
EXPECT_EQ(empty_repeated_field_size, message.SpaceUsed()) << #type; \
message.ClearExtension(unittest::repeated_##type##_extension); \
+ const int old_capacity = \
+ message.GetRepeatedExtension(unittest::repeated_##type##_extension) \
+ .Capacity(); \
+ EXPECT_GE(old_capacity, kMinRepeatedFieldAllocationSize); \
for (int i = 0; i < 16; ++i) { \
message.AddExtension(unittest::repeated_##type##_extension, value); \
} \
- int expected_size = sizeof(cpptype) * (16 - \
- kMinRepeatedFieldAllocationSize) + empty_repeated_field_size; \
+ int expected_size = sizeof(cpptype) * \
+ (message.GetRepeatedExtension(unittest::repeated_##type##_extension) \
+ .Capacity() - old_capacity) + empty_repeated_field_size; \
EXPECT_LE(expected_size, message.SpaceUsed()) << #type; \
} while (0)
@@ -993,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(
@@ -1002,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 c55a697a..000fa8d3 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];
@@ -70,15 +67,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
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 ::google::protobuf::internal::once_flag once;
+ ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
@@ -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,17 +156,10 @@ 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();
}
-FieldMask* FieldMask::New(::google::protobuf::Arena* arena) const {
- FieldMask* n = new FieldMask;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
-}
void FieldMask::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FieldMask)
@@ -193,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)) {
@@ -300,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;
}
@@ -355,9 +337,8 @@ void FieldMask::Swap(FieldMask* other) {
}
void FieldMask::InternalSwap(FieldMask* other) {
using std::swap;
- paths_.InternalSwap(&other->paths_);
+ paths_.InternalSwap(CastToBase(&other->paths_));
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata FieldMask::GetMetadata() const {
@@ -369,5 +350,12 @@ void FieldMask::InternalSwap(FieldMask* other) {
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
+namespace google {
+namespace protobuf {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldMask* Arena::CreateMaybeMessage< ::google::protobuf::FieldMask >(Arena* arena) {
+ return Arena::CreateInternal< ::google::protobuf::FieldMask >(arena);
+}
+} // namespace protobuf
+} // namespace google
// @@protoc_insertion_point(global_scope)
diff --git a/src/google/protobuf/field_mask.pb.h b/src/google/protobuf/field_mask.pb.h
index d57a4494..144b41fa 100644
--- a/src/google/protobuf/field_mask.pb.h
+++ b/src/google/protobuf/field_mask.pb.h
@@ -1,8 +1,8 @@
// 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>
@@ -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,6 +54,11 @@ LIBPROTOBUF_EXPORT extern FieldMaskDefaultTypeInternal _FieldMask_default_instan
} // namespace google
namespace google {
namespace protobuf {
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldMask* Arena::CreateMaybeMessage<::google::protobuf::FieldMask>(Arena*);
+} // namespace protobuf
+} // namespace google
+namespace google {
+namespace protobuf {
// ===================================================================
@@ -94,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);
@@ -104,28 +106,33 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
// implements Message ----------------------------------------------
- inline FieldMask* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline FieldMask* New() const final {
+ return CreateMaybeMessage<FieldMask>(NULL);
+ }
- FieldMask* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ FieldMask* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<FieldMask>(arena);
+ }
+ 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 {
@@ -136,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 ----------------------------------------------------
@@ -169,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();
};
// ===================================================================
@@ -264,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_reflection.h b/src/google/protobuf/generated_enum_reflection.h
index fdcdc277..983d3185 100644
--- a/src/google/protobuf/generated_enum_reflection.h
+++ b/src/google/protobuf/generated_enum_reflection.h
@@ -41,7 +41,6 @@
#include <string>
-#include <google/protobuf/stubs/template_util.h>
#include <google/protobuf/generated_enum_util.h>
namespace google {
diff --git a/src/google/protobuf/generated_enum_util.h b/src/google/protobuf/generated_enum_util.h
index e4242055..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/template_util.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 f0f207ea..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,12 +1155,13 @@ 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();
}
}
-
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return GetEmptyString(); // Make compiler happy.
}
}
@@ -1141,12 +1176,13 @@ 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();
}
}
-
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return GetEmptyString(); // Make compiler happy.
}
}
@@ -1162,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());
@@ -1188,9 +1230,6 @@ string GeneratedMessageReflection::GetRepeatedString(
case FieldOptions::STRING:
return GetRepeatedPtrField<string>(message, field, index);
}
-
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return GetEmptyString(); // Make compiler happy.
}
}
@@ -1206,9 +1245,6 @@ const string& GeneratedMessageReflection::GetRepeatedStringReference(
case FieldOptions::STRING:
return GetRepeatedPtrField<string>(message, field, index);
}
-
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return GetEmptyString(); // Make compiler happy.
}
}
@@ -1880,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 {
@@ -1975,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;
}
}
@@ -2319,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,
@@ -2328,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 02ecba61..31f249b6 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:
@@ -543,6 +575,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,
@@ -655,12 +689,9 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection PROTOBUF_FINAL : public Refl
// dynamic_cast_if_available() implements this logic. If RTTI is
// enabled, it does a dynamic_cast. If RTTI is disabled, it just returns
// NULL.
-//
-// If you need to compile without RTTI, simply #define GOOGLE_PROTOBUF_NO_RTTI.
-// On MSVC, this should be detected automatically.
template<typename To, typename From>
inline To dynamic_cast_if_available(From from) {
-#if defined(GOOGLE_PROTOBUF_NO_RTTI) || (defined(_MSC_VER)&&!defined(_CPPRTTI))
+#ifdef GOOGLE_PROTOBUF_NO_RTTI
// Avoid the compiler warning about unused variables.
(void)from;
return NULL;
@@ -688,8 +719,7 @@ T* DynamicCastToGenerated(const Message* from) {
const Message* unused = static_cast<T*>(NULL);
(void)unused;
-#if defined(GOOGLE_PROTOBUF_NO_RTTI) || \
- (defined(_MSC_VER) && !defined(_CPPRTTI))
+#ifdef GOOGLE_PROTOBUF_NO_RTTI
bool ok = &T::default_instance() ==
from->GetReflection()->GetMessageFactory()->GetPrototype(
from->GetDescriptor());
@@ -708,7 +738,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 20b4da21..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) {
@@ -307,6 +345,7 @@ inline bool HandleEnum(const ParseTable& table, io::CodedInputStream* input,
class RepeatedMessageTypeHandler {
public:
typedef MessageLite Type;
+ typedef MessageLite WeakType;
static Arena* GetArena(Type* t) { return t->GetArena(); }
static void* GetMaybeArenaPointer(Type* t) {
return t->GetMaybeArenaPointer();
@@ -322,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,
@@ -394,7 +395,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
continue;
}
- if (GOOGLE_PREDICT_FALSE(!UnknownFieldHandler::Skip(msg, table, input, tag))) {
+ if (GOOGLE_PREDICT_FALSE(
+ !UnknownFieldHandler::Skip(msg, table, input, tag))) {
return false;
}
@@ -421,7 +423,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
#define HANDLE_TYPE(TYPE, CPPTYPE) \
case (WireFormatLite::TYPE_##TYPE): { \
CPPTYPE value; \
- if (GOOGLE_PREDICT_FALSE( \
+ if (GOOGLE_PREDICT_FALSE( \
(!WireFormatLite::ReadPrimitive< \
CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)))) { \
return false; \
@@ -432,8 +434,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
case (WireFormatLite::TYPE_##TYPE) | kRepeatedMask: { \
google::protobuf::RepeatedField<CPPTYPE>* values = \
Raw<google::protobuf::RepeatedField<CPPTYPE> >(msg, offset); \
- if (GOOGLE_PREDICT_FALSE((!WireFormatLite::ReadRepeatedPrimitive< \
- CPPTYPE, WireFormatLite::TYPE_##TYPE>( \
+ if (GOOGLE_PREDICT_FALSE((!WireFormatLite::ReadRepeatedPrimitive< \
+ CPPTYPE, WireFormatLite::TYPE_##TYPE>( \
data->tag_size, tag, input, values)))) { \
return false; \
} \
@@ -442,7 +444,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
case (WireFormatLite::TYPE_##TYPE) | kOneofMask: { \
uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset); \
CPPTYPE value; \
- if (GOOGLE_PREDICT_FALSE( \
+ if (GOOGLE_PREDICT_FALSE( \
(!WireFormatLite::ReadPrimitive< \
CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)))) { \
return false; \
@@ -488,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:
@@ -511,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 =
@@ -543,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);
@@ -578,29 +600,32 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
}
#endif
case WireFormatLite::TYPE_ENUM: {
- if (GOOGLE_PREDICT_FALSE((!HandleEnum<UnknownFieldHandler, InternalMetadata,
- Cardinality_SINGULAR>(
- table, input, msg, has_bits, presence_index, offset, tag,
- field_number)))) {
+ if (GOOGLE_PREDICT_FALSE(
+ (!HandleEnum<UnknownFieldHandler, InternalMetadata,
+ Cardinality_SINGULAR>(
+ table, input, msg, has_bits, presence_index, offset, tag,
+ field_number)))) {
return false;
}
break;
}
case WireFormatLite::TYPE_ENUM | kRepeatedMask: {
- if (GOOGLE_PREDICT_FALSE((!HandleEnum<UnknownFieldHandler, InternalMetadata,
- Cardinality_REPEATED>(
- table, input, msg, has_bits, presence_index, offset, tag,
- field_number)))) {
+ if (GOOGLE_PREDICT_FALSE(
+ (!HandleEnum<UnknownFieldHandler, InternalMetadata,
+ Cardinality_REPEATED>(
+ table, input, msg, has_bits, presence_index, offset, tag,
+ field_number)))) {
return false;
}
break;
}
case WireFormatLite::TYPE_ENUM | kOneofMask: {
uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset);
- if (GOOGLE_PREDICT_FALSE((!HandleEnum<UnknownFieldHandler, InternalMetadata,
- Cardinality_ONEOF>(
- table, input, msg, oneof_case, presence_index, offset, tag,
- field_number)))) {
+ if (GOOGLE_PREDICT_FALSE(
+ (!HandleEnum<UnknownFieldHandler, InternalMetadata,
+ Cardinality_ONEOF>(table, input, msg, oneof_case,
+ presence_index, offset, tag,
+ field_number)))) {
return false;
}
break;
@@ -619,8 +644,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
*submsg_holder = submsg;
}
- if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadGroup(
- field_number, input, submsg))) {
+ if (GOOGLE_PREDICT_FALSE(
+ !WireFormatLite::ReadGroup(field_number, input, submsg))) {
return false;
}
@@ -635,8 +660,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
MessageLite* submsg =
MergePartialFromCodedStreamHelper::Add(field, prototype);
- if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadGroup(
- field_number, input, submsg))) {
+ if (GOOGLE_PREDICT_FALSE(
+ !WireFormatLite::ReadGroup(field_number, input, submsg))) {
return false;
}
@@ -652,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;
}
@@ -668,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);
@@ -695,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)))) {
@@ -716,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.
//
@@ -727,7 +776,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
case WireFormatLite::TYPE_##TYPE: { \
google::protobuf::RepeatedField<CPPTYPE>* values = \
Raw<google::protobuf::RepeatedField<CPPTYPE> >(msg, offset); \
- if (GOOGLE_PREDICT_FALSE( \
+ if (GOOGLE_PREDICT_FALSE( \
(!WireFormatLite::ReadPackedPrimitive< \
CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, values)))) { \
return false; \
@@ -809,7 +858,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
}
// process unknown field.
- if (GOOGLE_PREDICT_FALSE(!UnknownFieldHandler::Skip(msg, table, input, tag))) {
+ if (GOOGLE_PREDICT_FALSE(
+ !UnknownFieldHandler::Skip(msg, table, input, tag))) {
return false;
}
}
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 8ebfc13b..c26e3e52 100644
--- a/src/google/protobuf/generated_message_util.h
+++ b/src/google/protobuf/generated_message_util.h
@@ -39,14 +39,16 @@
#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>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/wire_format_lite.h>
@@ -120,6 +122,21 @@ template <class Type> bool AllAreInitialized(const Type& t) {
return true;
}
+// "Weak" variant of AllAreInitialized, used to implement implicit weak fields.
+// This version operates on MessageLite to avoid introducing a dependency on the
+// concrete message type.
+template <class T>
+bool AllAreInitializedWeak(const ::google::protobuf::RepeatedPtrField<T>& t) {
+ for (int i = t.size(); --i >= 0;) {
+ if (!reinterpret_cast<const ::google::protobuf::internal::RepeatedPtrFieldBase&>(t)
+ .Get<::google::protobuf::internal::ImplicitWeakTypeHandler<T> >(i)
+ .IsInitialized()) {
+ return false;
+ }
+ }
+ return true;
+}
+
LIBPROTOBUF_EXPORT void InitProtobufDefaults();
struct LIBPROTOBUF_EXPORT FieldMetadata {
@@ -148,7 +165,8 @@ struct LIBPROTOBUF_EXPORT FieldMetadata {
enum {
kCordType = 19,
kStringPieceType = 20,
- kNumTypes = 20,
+ kInlinedType = 21,
+ kNumTypes = 21,
kSpecial = kNumTypes * kNumTypeClasses,
};
@@ -157,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) {
@@ -274,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>
@@ -297,20 +315,48 @@ 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
+ };
+ std::atomic<int> visit_status;
+ 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 12cc7db9..3279bd17 100644
--- a/src/google/protobuf/implicit_weak_message.h
+++ b/src/google/protobuf/implicit_weak_message.h
@@ -35,15 +35,23 @@
#include <google/protobuf/arena.h>
#include <google/protobuf/message_lite.h>
+// This file is logically internal-only and should only be used by protobuf
+// generated code.
+
namespace google {
namespace protobuf {
namespace internal {
+// An implementation of MessageLite that treats all data as unknown. This type
+// acts as a placeholder for an implicit weak field in the case where the true
+// message type does not get linked into the binary.
class LIBPROTOBUF_EXPORT ImplicitWeakMessage : public MessageLite {
public:
ImplicitWeakMessage() : arena_(NULL) {}
explicit ImplicitWeakMessage(Arena* arena) : arena_(arena) {}
+ static const ImplicitWeakMessage* default_instance();
+
string GetTypeName() const { return ""; }
MessageLite* New() const { return new ImplicitWeakMessage; }
@@ -69,7 +77,7 @@ class LIBPROTOBUF_EXPORT ImplicitWeakMessage : public MessageLite {
output->WriteString(data_);
}
- int GetCachedSize() const { return data_.size(); }
+ int GetCachedSize() const { return static_cast<int>(data_.size()); }
typedef void InternalArenaConstructable_;
@@ -79,8 +87,46 @@ class LIBPROTOBUF_EXPORT ImplicitWeakMessage : public MessageLite {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImplicitWeakMessage);
};
-extern ::google::protobuf::internal::ExplicitlyConstructed<ImplicitWeakMessage>
- implicit_weak_message_default_instance;
+// A type handler for use with implicit weak repeated message fields.
+template <typename ImplicitWeakType>
+class ImplicitWeakTypeHandler {
+ public:
+ typedef ImplicitWeakType Type;
+ typedef ::google::protobuf::MessageLite WeakType;
+ static const bool Moveable = false;
+
+ // With implicit weak fields, we need separate NewFromPrototype and
+ // NewFromPrototypeWeak functions. The former is used when we want to create a
+ // strong dependency on the message type, and it just delegates to the
+ // GenericTypeHandler. The latter avoids creating a strong dependency, by
+ // simply calling MessageLite::New.
+ static inline ::google::protobuf::MessageLite* NewFromPrototype(
+ const ::google::protobuf::MessageLite* prototype, ::google::protobuf::Arena* arena = NULL) {
+ return prototype->New(arena);
+ }
+
+ static inline void Delete(::google::protobuf::MessageLite* value, Arena* arena) {
+ if (arena == NULL) {
+ delete value;
+ }
+ }
+ static inline ::google::protobuf::Arena* GetArena(::google::protobuf::MessageLite* value) {
+ return value->GetArena();
+ }
+ static inline void* GetMaybeArenaPointer(::google::protobuf::MessageLite* value) {
+ return value->GetArena();
+ }
+ static inline void Clear(::google::protobuf::MessageLite* value) {
+ value->Clear();
+ }
+ static void Merge(const ::google::protobuf::MessageLite& from,
+ ::google::protobuf::MessageLite* to) {
+ to->CheckTypeAndMergeFrom(from);
+ }
+ static inline size_t SpaceUsedLong(const Type& value) {
+ return value.SpaceUsedLong();
+ }
+};
} // 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 79cff2c7..0851ff0c 100644
--- a/src/google/protobuf/io/coded_stream.cc
+++ b/src/google/protobuf/io/coded_stream.cc
@@ -121,9 +121,9 @@ CodedInputStream::Limit CodedInputStream::PushLimit(int byte_limit) {
// security: byte_limit is possibly evil, so check for negative values
// and overflow. Also check that the new requested limit is before the
// previous limit; otherwise we continue to enforce the previous limit.
- if GOOGLE_PREDICT_TRUE(byte_limit >= 0 &&
- byte_limit <= INT_MAX - current_position &&
- byte_limit < current_limit_ - current_position) {
+ if (GOOGLE_PREDICT_TRUE(byte_limit >= 0 &&
+ byte_limit <= INT_MAX - current_position &&
+ byte_limit < current_limit_ - current_position)) {
current_limit_ = current_position + byte_limit;
RecomputeBufferLimits();
}
@@ -173,10 +173,7 @@ int CodedInputStream::BytesUntilLimit() const {
return current_limit_ - current_position;
}
-void CodedInputStream::SetTotalBytesLimit(
- int total_bytes_limit, int warning_threshold) {
- (void) warning_threshold;
-
+void CodedInputStream::SetTotalBytesLimit(int total_bytes_limit) {
// Make sure the limit isn't already past, since this could confuse other
// code.
int current_position = CurrentPosition();
@@ -220,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) {
@@ -618,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)
@@ -644,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 02d87ea4..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>
@@ -367,42 +367,32 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// Total Bytes Limit -----------------------------------------------
// To prevent malicious users from sending excessively large messages
- // and causing integer overflows or memory exhaustion, CodedInputStream
- // imposes a hard limit on the total number of bytes it will read.
+ // and causing memory exhaustion, CodedInputStream imposes a hard limit on
+ // the total number of bytes it will read.
// Sets the maximum number of bytes that this CodedInputStream will read
- // before refusing to continue. To prevent integer overflows in the
- // protocol buffers implementation, as well as to prevent servers from
- // allocating enormous amounts of memory to hold parsed messages, the
- // maximum message length should be limited to the shortest length that
- // will not harm usability. The theoretical shortest message that could
- // cause integer overflows is 512MB. The default limit is 64MB. Apps
- // should set shorter limits if possible. For backwards compatibility all
- // negative values get squashed to -1, as other negative values might have
- // special internal meanings. An error will always be printed to stderr if
- // the limit is reached.
+ // before refusing to continue. To prevent servers from allocating enormous
+ // amounts of memory to hold parsed messages, the maximum message length
+ // should be limited to the shortest length that will not harm usability.
+ // The default limit is INT_MAX (~2GB) and apps should set shorter limits
+ // if possible. An error will always be printed to stderr if the limit is
+ // reached.
//
- // This is unrelated to PushLimit()/PopLimit().
+ // Note: setting a limit less than the current read position is interpreted
+ // as a limit on the current position.
//
- // Hint: If you are reading this because your program is printing a
- // warning about dangerously large protocol messages, you may be
- // confused about what to do next. The best option is to change your
- // design such that excessively large messages are not necessary.
- // For example, try to design file formats to consist of many small
- // messages rather than a single large one. If this is infeasible,
- // you will need to increase the limit. Chances are, though, that
- // your code never constructs a CodedInputStream on which the limit
- // can be set. You probably parse messages by calling things like
- // Message::ParseFromString(). In this case, you will need to change
- // your code to instead construct some sort of ZeroCopyInputStream
- // (e.g. an ArrayInputStream), construct a CodedInputStream around
- // that, then you can adjust the limit. Then call
- // Message::ParseFromCodedStream() instead. Yes, it's more work, but
- // you're doing something unusual.
- void SetTotalBytesLimit(int total_bytes_limit, int warning_threshold);
-
- // The Total Bytes Limit minus the Current Position, or -1 if there
- // is no Total Bytes Limit.
+ // This is unrelated to PushLimit()/PopLimit().
+ void SetTotalBytesLimit(int total_bytes_limit);
+
+ PROTOBUF_RUNTIME_DEPRECATED(
+ "Please use the single parameter version of SetTotalBytesLimit(). The "
+ "second parameter is ignored.")
+ void SetTotalBytesLimit(int total_bytes_limit, int) {
+ SetTotalBytesLimit(total_bytes_limit);
+ }
+
+ // The Total Bytes Limit minus the Current Position, or -1 if the total bytes
+ // limit is INT_MAX.
int BytesUntilTotalBytesLimit() const;
// Recursion Limit -------------------------------------------------
@@ -580,8 +570,6 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// Recursion depth limit, set by SetRecursionLimit().
int recursion_limit_;
- bool disable_strict_correctness_enforcement_;
-
// See SetExtensionRegistry().
const DescriptorPool* extension_pool_;
MessageFactory* extension_factory_;
@@ -841,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.)
//
@@ -852,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:
@@ -878,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);
@@ -910,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);
}
};
@@ -1053,8 +1034,7 @@ inline std::pair<uint32, bool> CodedInputStream::ReadTagWithCutoffNoLastTag(
// Other hot case: cutoff >= 0x80, buffer_ has at least two bytes available,
// and tag is two bytes. The latter is tested by bitwise-and-not of the
// first byte and the second byte.
- if (cutoff >= 0x80 &&
- GOOGLE_PREDICT_TRUE(buffer_ + 1 < buffer_end_) &&
+ if (cutoff >= 0x80 && GOOGLE_PREDICT_TRUE(buffer_ + 1 < buffer_end_) &&
GOOGLE_PREDICT_TRUE((buffer_[0] & ~buffer_[1]) >= 0x80)) {
const uint32 kMax2ByteVarint = (0x7f << 7) + 0x7f;
uint32 tag = (1u << 7) * buffer_[1] + (buffer_[0] - 0x80);
@@ -1364,7 +1344,6 @@ inline CodedInputStream::CodedInputStream(ZeroCopyInputStream* input)
total_bytes_limit_(kDefaultTotalBytesLimit),
recursion_budget_(default_recursion_limit_),
recursion_limit_(default_recursion_limit_),
- disable_strict_correctness_enforcement_(true),
extension_pool_(NULL),
extension_factory_(NULL) {
// Eagerly Refresh() so buffer space is immediately available.
@@ -1385,7 +1364,6 @@ inline CodedInputStream::CodedInputStream(const uint8* buffer, int size)
total_bytes_limit_(kDefaultTotalBytesLimit),
recursion_budget_(default_recursion_limit_),
recursion_limit_(default_recursion_limit_),
- disable_strict_correctness_enforcement_(true),
extension_pool_(NULL),
extension_factory_(NULL) {
// Note that setting current_limit_ == size is important to prevent some
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/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_lite.h b/src/google/protobuf/io/zero_copy_stream_impl_lite.h
index ab0fd5ac..29f63bf0 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>
@@ -239,7 +236,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
@@ -328,7 +325,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 7d9cc5c5..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>
@@ -142,7 +143,6 @@ class Map {
insert(other.begin(), other.end());
}
-#if LANG_CXX11
Map(Map&& other) noexcept : Map() {
if (other.arena_) {
*this = other;
@@ -160,7 +160,6 @@ class Map {
}
return *this;
}
-#endif
template <class InputIt>
Map(const InputIt& first, const InputIt& last)
@@ -741,7 +740,7 @@ class Map {
return true;
}
} else if (GOOGLE_PREDICT_FALSE(new_size <= lo_cutoff &&
- num_buckets_ > kMinTableSize)) {
+ num_buckets_ > kMinTableSize)) {
size_type lg2_of_size_reduction_factor = 1;
// It's possible we want to shrink a lot here... size() could even be 0.
// So, estimate how much to shrink by making sure we don't shrink so
@@ -1113,6 +1112,9 @@ class Map {
}
}
}
+ void insert(std::initializer_list<value_type> values) {
+ insert(values.begin(), values.end());
+ }
// Erase and clear
size_type erase(const key_type& key) {
diff --git a/src/google/protobuf/map_entry_lite.h b/src/google/protobuf/map_entry_lite.h
index 7c477c56..85a0bed7 100644
--- a/src/google/protobuf/map_entry_lite.h
+++ b/src/google/protobuf/map_entry_lite.h
@@ -33,7 +33,9 @@
#include <assert.h>
+#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/arena.h>
+#include <google/protobuf/arenastring.h>
#include <google/protobuf/map.h>
#include <google/protobuf/map_type_handler.h>
#include <google/protobuf/stubs/port.h>
@@ -200,8 +202,7 @@ class MapEntryImpl : public Base {
return false;
}
set_has_key();
- if (!input->ExpectTag(kValueTag)) break;
- GOOGLE_FALLTHROUGH_INTENDED;
+ break;
case kValueTag:
if (!ValueTypeHandler::Read(input, mutable_value())) {
@@ -354,9 +355,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 +432,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:
@@ -603,7 +604,9 @@ template <>
struct FromHelper<WireFormatLite::TYPE_STRING> {
static ArenaStringPtr From(const string& x) {
ArenaStringPtr res;
- *res.UnsafeRawStringPointer() = const_cast<string*>(&x);
+ TaggedPtr<::std::string> ptr;
+ ptr.Set(const_cast<string*>(&x));
+ res.UnsafeSetTaggedPointer(ptr);
return res;
}
};
@@ -611,7 +614,9 @@ template <>
struct FromHelper<WireFormatLite::TYPE_BYTES> {
static ArenaStringPtr From(const string& x) {
ArenaStringPtr res;
- *res.UnsafeRawStringPointer() = const_cast<string*>(&x);
+ 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 64dcc990..ac29c7e9 100644
--- a/src/google/protobuf/map_field.cc
+++ b/src/google/protobuf/map_field.cc
@@ -43,13 +43,15 @@ MapFieldBase::~MapFieldBase() {
const RepeatedPtrFieldBase& MapFieldBase::GetRepeatedField() const {
SyncRepeatedFieldWithMap();
- return *repeated_field_;
+ return *reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
+ repeated_field_);
}
RepeatedPtrFieldBase* MapFieldBase::MutableRepeatedField() {
SyncRepeatedFieldWithMap();
SetRepeatedDirty();
- return repeated_field_;
+ return reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
+ repeated_field_);
}
size_t MapFieldBase::SpaceUsedExcludingSelfLong() const {
@@ -70,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();
}
@@ -105,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();
}
@@ -130,6 +139,7 @@ DynamicMapField::DynamicMapField(const Message* default_entry)
DynamicMapField::DynamicMapField(const Message* default_entry,
Arena* arena)
: TypeDefinedMapFieldBase<MapKey, MapValueRef>(arena),
+ map_(arena),
default_entry_(default_entry) {
}
diff --git a/src/google/protobuf/map_field.h b/src/google/protobuf/map_field.h
index 6c75a6da..494401e1 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;
@@ -814,13 +815,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 080c71a7..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,6 +673,14 @@ TEST_F(MapImplTest, InsertByIterator) {
ExpectElements(map1);
}
+TEST_F(MapImplTest, InsertByInitializerList) {
+ map_.insert({{1, 100}, {2, 200}});
+ ExpectElements({{1, 100}, {2, 200}});
+
+ map_.insert({{2, 201}, {3, 301}});
+ ExpectElements({{1, 100}, {2, 200}, {3, 301}});
+}
+
TEST_F(MapImplTest, EraseSingleByKey) {
int32 key = 0;
int32 value = 100;
@@ -1259,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());
@@ -1809,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 =
@@ -1826,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
@@ -1994,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(
@@ -2011,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(
@@ -2030,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());
@@ -2049,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());
@@ -2063,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());
@@ -2715,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());
@@ -2724,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_);
@@ -2738,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();
@@ -2751,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());
@@ -2788,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());
@@ -2957,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(
@@ -3283,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);
@@ -3319,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/map_unittest_proto3.proto b/src/google/protobuf/map_unittest_proto3.proto
deleted file mode 100644
index 16be2773..00000000
--- a/src/google/protobuf/map_unittest_proto3.proto
+++ /dev/null
@@ -1,120 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This file is mostly equivalent to map_unittest.proto, but imports
-// unittest_proto3.proto instead of unittest.proto, so that it only
-// uses proto3 messages. This makes it suitable for testing
-// implementations which only support proto3.
-// The TestRequiredMessageMap message has been removed as there are no
-// required fields in proto3.
-syntax = "proto3";
-
-option cc_enable_arenas = true;
-option csharp_namespace = "Google.Protobuf.TestProtos";
-
-import "google/protobuf/unittest_proto3.proto";
-
-// We don't put this in a package within proto2 because we need to make sure
-// that the generated code doesn't depend on being in the proto2 namespace.
-// In map_test_util.h we do "using namespace unittest = protobuf_unittest".
-package protobuf_unittest;
-
-// Tests maps.
-message TestMap {
- map<int32 , int32 > map_int32_int32 = 1;
- map<int64 , int64 > map_int64_int64 = 2;
- map<uint32 , uint32 > map_uint32_uint32 = 3;
- map<uint64 , uint64 > map_uint64_uint64 = 4;
- map<sint32 , sint32 > map_sint32_sint32 = 5;
- map<sint64 , sint64 > map_sint64_sint64 = 6;
- map<fixed32 , fixed32 > map_fixed32_fixed32 = 7;
- map<fixed64 , fixed64 > map_fixed64_fixed64 = 8;
- map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9;
- map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10;
- map<int32 , float > map_int32_float = 11;
- map<int32 , double > map_int32_double = 12;
- map<bool , bool > map_bool_bool = 13;
- map<string , string > map_string_string = 14;
- map<int32 , bytes > map_int32_bytes = 15;
- map<int32 , MapEnum > map_int32_enum = 16;
- map<int32 , ForeignMessage> map_int32_foreign_message = 17;
-}
-
-message TestMapSubmessage {
- TestMap test_map = 1;
-}
-
-message TestMessageMap {
- map<int32, TestAllTypes> map_int32_message = 1;
-}
-
-// Two map fields share the same entry default instance.
-message TestSameTypeMap {
- map<int32, int32> map1 = 1;
- map<int32, int32> map2 = 2;
-}
-
-enum MapEnum {
- MAP_ENUM_FOO = 0;
- MAP_ENUM_BAR = 1;
- MAP_ENUM_BAZ = 2;
-}
-
-message TestArenaMap {
- map<int32 , int32 > map_int32_int32 = 1;
- map<int64 , int64 > map_int64_int64 = 2;
- map<uint32 , uint32 > map_uint32_uint32 = 3;
- map<uint64 , uint64 > map_uint64_uint64 = 4;
- map<sint32 , sint32 > map_sint32_sint32 = 5;
- map<sint64 , sint64 > map_sint64_sint64 = 6;
- map<fixed32 , fixed32 > map_fixed32_fixed32 = 7;
- map<fixed64 , fixed64 > map_fixed64_fixed64 = 8;
- map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9;
- map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10;
- map<int32 , float > map_int32_float = 11;
- map<int32 , double > map_int32_double = 12;
- map<bool , bool > map_bool_bool = 13;
- map<int32 , MapEnum > map_int32_enum = 14;
- map<int32 , ForeignMessage> map_int32_foreign_message = 15;
-}
-
-// Previously, message containing enum called Type cannot be used as value of
-// map field.
-message MessageContainingEnumCalledType {
- enum Type {
- TYPE_FOO = 0;
- }
- map<int32, MessageContainingEnumCalledType> type = 1;
-}
-
-// Previously, message cannot contain map field called "entry".
-message MessageContainingMapCalledEntry {
- map<int32, int32> entry = 1;
-}
diff --git a/src/google/protobuf/message.cc b/src/google/protobuf/message.cc
index 42ec0337..810db233 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>
diff --git a/src/google/protobuf/message.h b/src/google/protobuf/message.h
index ab018596..f3d1a58a 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>
@@ -152,6 +152,9 @@ class CodedOutputStream; // coded_stream.h
namespace python {
class MapReflectionFriend; // scalar_map_container.h
}
+namespace expr {
+class CelMapReflectionFriend; // field_backed_map_impl.cc
+}
namespace internal {
@@ -339,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;
}
@@ -406,9 +409,6 @@ class MutableRepeatedFieldRef;
// double the message's memory footprint, probably worse. Allocating the
// objects on-demand, on the other hand, would be expensive and prone to
// memory leaks. So, instead we ended up with this flat interface.
-//
-// TODO(kenton): Create a utility class which callers can use to read and
-// write fields from a Reflection without paying attention to the type.
class LIBPROTOBUF_EXPORT Reflection {
public:
inline Reflection() {}
@@ -815,6 +815,7 @@ class LIBPROTOBUF_EXPORT Reflection {
//
// for T = Cord and all protobuf scalar types except enums.
template<typename T>
+ PROTOBUF_RUNTIME_DEPRECATED("Please use GetRepeatedFieldRef() instead")
const RepeatedField<T>& GetRepeatedField(
const Message&, const FieldDescriptor*) const;
@@ -822,6 +823,7 @@ class LIBPROTOBUF_EXPORT Reflection {
//
// for T = Cord and all protobuf scalar types except enums.
template<typename T>
+ PROTOBUF_RUNTIME_DEPRECATED("Please use GetMutableRepeatedFieldRef() instead")
RepeatedField<T>* MutableRepeatedField(
Message*, const FieldDescriptor*) const;
@@ -830,6 +832,7 @@ class LIBPROTOBUF_EXPORT Reflection {
// for T = string, google::protobuf::internal::StringPieceField
// google::protobuf::Message & descendants.
template<typename T>
+ PROTOBUF_RUNTIME_DEPRECATED("Please use GetRepeatedFieldRef() instead")
const RepeatedPtrField<T>& GetRepeatedPtrField(
const Message&, const FieldDescriptor*) const;
@@ -838,6 +841,7 @@ class LIBPROTOBUF_EXPORT Reflection {
// for T = string, google::protobuf::internal::StringPieceField
// google::protobuf::Message & descendants.
template<typename T>
+ PROTOBUF_RUNTIME_DEPRECATED("Please use GetMutableRepeatedFieldRef() instead")
RepeatedPtrField<T>* MutableRepeatedPtrField(
Message*, const FieldDescriptor*) const;
@@ -949,6 +953,8 @@ class LIBPROTOBUF_EXPORT Reflection {
template<typename T, typename Enable>
friend class MutableRepeatedFieldRef;
friend class ::google::protobuf::python::MapReflectionFriend;
+#define GOOGLE_PROTOBUF_HAS_CEL_MAP_REFLECTION_FRIEND
+ friend class ::google::protobuf::expr::CelMapReflectionFriend;
friend class internal::MapFieldReflectionTest;
friend class internal::MapKeySorter;
friend class internal::WireFormat;
diff --git a/src/google/protobuf/message_lite.h b/src/google/protobuf/message_lite.h
index 5cd6babc..4cbec330 100644
--- a/src/google/protobuf/message_lite.h
+++ b/src/google/protobuf/message_lite.h
@@ -43,11 +43,13 @@
#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 {
class CodedInputStream;
class CodedOutputStream;
@@ -56,7 +58,9 @@ class ZeroCopyOutputStream;
}
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
@@ -110,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:
@@ -130,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();
@@ -271,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.
//
@@ -380,12 +378,34 @@ class LIBPROTOBUF_EXPORT MessageLite {
virtual uint8* InternalSerializeWithCachedSizesToArray(bool deterministic,
uint8* target) const;
+ protected:
+ // CastToBase allows generated code to cast a RepeatedPtrField<T> to
+ // RepeatedPtrFieldBase. We try to restrict access to RepeatedPtrFieldBase
+ // because it is an implementation detail that user code should not access
+ // directly.
+ template <typename T>
+ static ::google::protobuf::internal::RepeatedPtrFieldBase* CastToBase(
+ ::google::protobuf::RepeatedPtrField<T>* repeated) {
+ return repeated;
+ }
+ template <typename T>
+ static const ::google::protobuf::internal::RepeatedPtrFieldBase& CastToBase(
+ const ::google::protobuf::RepeatedPtrField<T>& repeated) {
+ 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
--- 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_ops.cc b/src/google/protobuf/reflection_ops.cc
index d1867311..3cd50340 100644
--- a/src/google/protobuf/reflection_ops.cc
+++ b/src/google/protobuf/reflection_ops.cc
@@ -31,13 +31,15 @@
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
+#include <google/protobuf/reflection_ops.h>
#include <string>
#include <vector>
-#include <google/protobuf/reflection_ops.h>
-#include <google/protobuf/descriptor.h>
+#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/stubs/common.h>
#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/descriptor.h>
#include <google/protobuf/map_field.h>
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/stubs/strutil.h>
@@ -46,6 +48,17 @@ namespace google {
namespace protobuf {
namespace internal {
+static const Reflection* GetReflectionOrDie(const Message& m) {
+ const Reflection* r = m.GetReflection();
+ if (r == nullptr) {
+ const Descriptor* d = m.GetDescriptor();
+ const string& mtype = d ? d->name() : "unknown";
+ // RawMessage is one known type for which GetReflection() returns nullptr.
+ GOOGLE_LOG(FATAL) << "Message does not support reflection (type " << mtype << ").";
+ }
+ return r;
+}
+
void ReflectionOps::Copy(const Message& from, Message* to) {
if (&from == to) return;
Clear(to);
@@ -61,8 +74,8 @@ void ReflectionOps::Merge(const Message& from, Message* to) {
<< "(merge " << descriptor->full_name()
<< " to " << to->GetDescriptor()->full_name() << ")";
- const Reflection* from_reflection = from.GetReflection();
- const Reflection* to_reflection = to->GetReflection();
+ const Reflection* from_reflection = GetReflectionOrDie(from);
+ const Reflection* to_reflection = GetReflectionOrDie(*to);
std::vector<const FieldDescriptor*> fields;
from_reflection->ListFields(from, &fields);
@@ -128,7 +141,7 @@ void ReflectionOps::Merge(const Message& from, Message* to) {
}
void ReflectionOps::Clear(Message* message) {
- const Reflection* reflection = message->GetReflection();
+ const Reflection* reflection = GetReflectionOrDie(*message);
std::vector<const FieldDescriptor*> fields;
reflection->ListFields(*message, &fields);
@@ -141,7 +154,7 @@ void ReflectionOps::Clear(Message* message) {
bool ReflectionOps::IsInitialized(const Message& message) {
const Descriptor* descriptor = message.GetDescriptor();
- const Reflection* reflection = message.GetReflection();
+ const Reflection* reflection = GetReflectionOrDie(message);
// Check required fields of this message.
for (int i = 0; i < descriptor->field_count(); i++) {
@@ -201,7 +214,7 @@ bool ReflectionOps::IsInitialized(const Message& message) {
}
void ReflectionOps::DiscardUnknownFields(Message* message) {
- const Reflection* reflection = message->GetReflection();
+ const Reflection* reflection = GetReflectionOrDie(*message);
reflection->MutableUnknownFields(message)->Clear();
@@ -248,7 +261,7 @@ void ReflectionOps::FindInitializationErrors(
const string& prefix,
std::vector<string>* errors) {
const Descriptor* descriptor = message.GetDescriptor();
- const Reflection* reflection = message.GetReflection();
+ const Reflection* reflection = GetReflectionOrDie(message);
// Check required fields of this message.
for (int i = 0; i < descriptor->field_count(); i++) {
diff --git a/src/google/protobuf/repeated_field.cc b/src/google/protobuf/repeated_field.cc
index 5ca964c1..310000aa 100644
--- a/src/google/protobuf/repeated_field.cc
+++ b/src/google/protobuf/repeated_field.cc
@@ -103,6 +103,22 @@ void RepeatedPtrFieldBase::CloseGap(int start, int num) {
rep_->allocated_size -= num;
}
+google::protobuf::MessageLite* RepeatedPtrFieldBase::AddWeak(
+ const google::protobuf::MessageLite* prototype) {
+ if (rep_ != NULL && current_size_ < rep_->allocated_size) {
+ return reinterpret_cast<google::protobuf::MessageLite*>(
+ rep_->elements[current_size_++]);
+ }
+ if (!rep_ || rep_->allocated_size == total_size_) {
+ Reserve(total_size_ + 1);
+ }
+ ++rep_->allocated_size;
+ google::protobuf::MessageLite* result = prototype ? prototype->New(arena_) :
+ Arena::CreateMessage<ImplicitWeakMessage>(arena_);
+ rep_->elements[current_size_++] = result;
+ return result;
+}
+
} // namespace internal
diff --git a/src/google/protobuf/repeated_field.h b/src/google/protobuf/repeated_field.h
index 8eb6c795..b47ea994 100644
--- a/src/google/protobuf/repeated_field.h
+++ b/src/google/protobuf/repeated_field.h
@@ -57,10 +57,11 @@
#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/type_traits.h>
#include <google/protobuf/arena.h>
+#include <google/protobuf/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.
@@ -86,7 +87,7 @@ void LogIndexOutOfBounds(int index, int size);
template <typename Iter>
inline int CalculateReserve(Iter begin, Iter end, std::forward_iterator_tag) {
- return std::distance(begin, end);
+ return static_cast<int>(std::distance(begin, end));
}
template <typename Iter>
@@ -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;
@@ -279,9 +278,19 @@ class RepeatedField PROTOBUF_FINAL {
// a "gap" after the field arena and before the field elements (e.g., when
// Element is double and pointer is 32bit).
static const size_t kRepHeaderSize;
- // Contains arena ptr and the elements array. We also keep the invariant that
- // if rep_ is NULL, then arena is NULL.
- Rep* rep_;
+
+ // We reuse the Rep* for an Arena* when total_size == 0, to avoid having to do
+ // an allocation in the constructor when we have an Arena.
+ union Pointer {
+ Pointer(Arena* a) : arena(a) {}
+ Arena* arena; // When total_size_ == 0.
+ Rep* rep; // When total_size_ != 0.
+ } ptr_;
+
+ Rep* rep() const {
+ GOOGLE_DCHECK_GT(total_size_, 0);
+ return ptr_.rep;
+ }
friend class Arena;
typedef void InternalArenaConstructable_;
@@ -297,7 +306,7 @@ class RepeatedField PROTOBUF_FINAL {
// Internal helper expected by Arena methods.
inline Arena* GetArenaNoVirtual() const {
- return (rep_ == NULL) ? NULL : rep_->arena;
+ return (total_size_ == 0) ? ptr_.arena : ptr_.rep->arena;
}
// Internal helper to delete all elements and deallocate the storage.
@@ -342,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);
};
@@ -376,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;
};
@@ -388,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*
@@ -399,7 +408,12 @@ struct TypeImplementsMergeBehavior< ::std::string> {
// class TypeHandler {
// public:
// typedef MyType Type;
+// // WeakType is almost always the same as MyType, but we use it in
+// // ImplicitWeakTypeHandler.
+// typedef MyType WeakType;
// static Type* New();
+// static WeakType* NewFromPrototype(const WeakType* prototype,
+// ::google::protobuf::Arena* arena);
// static void Delete(Type*);
// static void Clear(Type*);
// static void Merge(const Type& from, Type* to);
@@ -409,31 +423,6 @@ struct TypeImplementsMergeBehavior< ::std::string> {
// };
class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
protected:
- // The reflection implementation needs to call protected methods directly,
- // reinterpreting pointers as being to Message instead of a specific Message
- // subclass.
- friend class GeneratedMessageReflection;
-
- // ExtensionSet stores repeated message extensions as
- // RepeatedPtrField<MessageLite>, but non-lite ExtensionSets need to implement
- // SpaceUsedLong(), and thus need to call SpaceUsedExcludingSelfLong()
- // reinterpreting MessageLite as Message. ExtensionSet also needs to make use
- // of AddFromCleared(), which is not part of the public interface.
- friend class ExtensionSet;
-
- // The MapFieldBase implementation needs to call protected methods directly,
- // reinterpreting pointers as being to Message instead of a specific Message
- // subclass.
- friend class MapFieldBase;
-
- // The table-driven MergePartialFromCodedStream implementation needs to
- // operate on RepeatedPtrField<MessageLite>.
- friend class MergePartialFromCodedStreamHelper;
-
- // To parse directly into a proto2 generated class, the upb class GMR_Handlers
- // needs to be able to modify a RepeatedPtrFieldBase directly.
- friend class upb::google_opensource::GMR_Handlers;
-
RepeatedPtrFieldBase();
explicit RepeatedPtrFieldBase(::google::protobuf::Arena* arena);
~RepeatedPtrFieldBase() {}
@@ -446,25 +435,41 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
int size() const;
template <typename TypeHandler>
- const typename TypeHandler::Type& Get(int index) const;
- template <typename TypeHandler>
typename TypeHandler::Type* Mutable(int index);
template <typename TypeHandler>
void Delete(int index);
template <typename TypeHandler>
typename TypeHandler::Type* Add(typename TypeHandler::Type* prototype = NULL);
-#if LANG_CXX11
- template <typename TypeHandler>
- void Add(typename TypeHandler::Type&& value,
- internal::enable_if<TypeHandler::Moveable>* dummy = NULL);
-#endif
+
+ public:
+ // The next few methods are public so that they can be called from generated
+ // code when implicit weak fields are used, but they should never be called by
+ // application code.
template <typename TypeHandler>
- void RemoveLast();
+ const typename TypeHandler::WeakType& Get(int index) const;
+
+ // Creates and adds an element using the given prototype, without introducing
+ // a link-time dependency on the concrete message type. This method is used to
+ // implement implicit weak fields. The prototype may be NULL, in which case an
+ // ImplicitWeakMessage will be used as a placeholder.
+ google::protobuf::MessageLite* AddWeak(const google::protobuf::MessageLite* prototype);
+
template <typename TypeHandler>
void Clear();
+
template <typename TypeHandler>
void MergeFrom(const RepeatedPtrFieldBase& other);
+
+ inline void InternalSwap(RepeatedPtrFieldBase* other);
+
+ protected:
+ template <typename TypeHandler>
+ void Add(typename TypeHandler::Type&& value,
+ std::enable_if<TypeHandler::Moveable>* dummy = NULL);
+
+ template <typename TypeHandler>
+ void RemoveLast();
template <typename TypeHandler>
void CopyFrom(const RepeatedPtrFieldBase& other);
@@ -491,7 +496,6 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
template <typename TypeHandler>
size_t SpaceUsedExcludingSelfLong() const;
-
// Advanced memory management --------------------------------------
// Like Add(), but if there are no cleared objects to use, returns NULL.
@@ -524,13 +528,10 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
template <typename TypeHandler>
typename TypeHandler::Type* ReleaseCleared();
- protected:
- inline void InternalSwap(RepeatedPtrFieldBase* other);
-
template <typename TypeHandler>
- void AddAllocatedInternal(typename TypeHandler::Type* value, google::protobuf::internal::true_type);
+ void AddAllocatedInternal(typename TypeHandler::Type* value, 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,
@@ -540,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);
@@ -601,7 +602,33 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
// Reserve() and MergeFrom() to reduce code size. |extend_amount| must be > 0.
void** InternalExtend(int extend_amount);
+ // The reflection implementation needs to call protected methods directly,
+ // reinterpreting pointers as being to Message instead of a specific Message
+ // subclass.
+ friend class GeneratedMessageReflection;
+
+ // ExtensionSet stores repeated message extensions as
+ // RepeatedPtrField<MessageLite>, but non-lite ExtensionSets need to implement
+ // SpaceUsedLong(), and thus need to call SpaceUsedExcludingSelfLong()
+ // reinterpreting MessageLite as Message. ExtensionSet also needs to make use
+ // of AddFromCleared(), which is not part of the public interface.
+ friend class ExtensionSet;
+
+ // The MapFieldBase implementation needs to call protected methods directly,
+ // reinterpreting pointers as being to Message instead of a specific Message
+ // subclass.
+ friend class MapFieldBase;
+
+ // The table-driven MergePartialFromCodedStream implementation needs to
+ // operate on RepeatedPtrField<MessageLite>.
+ friend class MergePartialFromCodedStreamHelper;
+
+ // To parse directly into a proto2 generated class, the upb class GMR_Handlers
+ // needs to be able to modify a RepeatedPtrFieldBase directly.
+ friend class upb::google_opensource::GMR_Handlers;
+
friend class AccessorHelper;
+
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPtrFieldBase);
};
@@ -609,9 +636,8 @@ template <typename GenericType>
class GenericTypeHandler {
public:
typedef GenericType Type;
-#if LANG_CXX11
+ typedef GenericType WeakType;
static const bool Moveable = false;
-#endif
static inline GenericType* New(Arena* arena) {
return ::google::protobuf::Arena::CreateMaybeMessage<Type>(arena);
@@ -636,9 +662,6 @@ class GenericTypeHandler {
static inline size_t SpaceUsedLong(const GenericType& value) {
return value.SpaceUsedLong();
}
- static inline const Type& default_instance() {
- return Type::default_instance();
- }
};
template <typename GenericType>
@@ -700,42 +723,19 @@ DECLARE_SPECIALIZATIONS_FOR_BASE_PROTO_TYPES(Message)
#undef DECLARE_SPECIALIZATIONS_FOR_BASE_PROTO_TYPES
-template <>
-inline const MessageLite& GenericTypeHandler<MessageLite>::default_instance() {
- // Yes, the behavior of the code is undefined, but this function is only
- // called when we're already deep into the world of undefined, because the
- // caller called Get(index) out of bounds.
- MessageLite* null = NULL;
- return *null;
-}
-
-template <>
-inline const Message& GenericTypeHandler<Message>::default_instance() {
- // Yes, the behavior of the code is undefined, but this function is only
- // called when we're already deep into the world of undefined, because the
- // caller called Get(index) out of bounds.
- Message* null = NULL;
- return *null;
-}
-
-
class StringTypeHandler {
public:
typedef string Type;
-#if LANG_CXX11
- static const bool Moveable =
- std::is_move_constructible<Type>::value &&
- std::is_move_assignable<Type>::value;
-#endif
+ typedef string WeakType;
+ static const bool Moveable = std::is_move_constructible<Type>::value &&
+ std::is_move_assignable<Type>::value;
static inline string* New(Arena* arena) {
return Arena::Create<string>(arena);
}
-#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);
@@ -753,9 +753,6 @@ class StringTypeHandler {
}
static inline void Clear(string* value) { value->clear(); }
static inline void Merge(const string& from, string* to) { *to = from; }
- static inline const Type& default_instance() {
- return ::google::protobuf::internal::GetEmptyString();
- }
static size_t SpaceUsedLong(const string& value) {
return sizeof(value) + StringSpaceUsedExcludingSelfLong(value);
}
@@ -766,7 +763,7 @@ class StringTypeHandler {
// RepeatedPtrField is like RepeatedField, but used for repeated strings or
// Messages.
template <typename Element>
-class RepeatedPtrField PROTOBUF_FINAL : public internal::RepeatedPtrFieldBase {
+class RepeatedPtrField final : private internal::RepeatedPtrFieldBase {
public:
RepeatedPtrField();
explicit RepeatedPtrField(::google::protobuf::Arena* arena);
@@ -778,10 +775,8 @@ class RepeatedPtrField PROTOBUF_FINAL : public internal::RepeatedPtrFieldBase {
RepeatedPtrField& operator=(const RepeatedPtrField& other);
-#if LANG_CXX11
RepeatedPtrField(RepeatedPtrField&& other) noexcept;
RepeatedPtrField& operator=(RepeatedPtrField&& other) noexcept;
-#endif
bool empty() const;
int size() const;
@@ -789,9 +784,7 @@ class RepeatedPtrField PROTOBUF_FINAL : public 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); }
@@ -921,7 +914,7 @@ class RepeatedPtrField PROTOBUF_FINAL : public 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.
@@ -1020,11 +1013,13 @@ class RepeatedPtrField PROTOBUF_FINAL : public 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;
+
typedef void InternalArenaConstructable_;
};
@@ -1035,33 +1030,25 @@ template <typename Element>
inline RepeatedField<Element>::RepeatedField()
: current_size_(0),
total_size_(0),
- rep_(NULL) {
+ ptr_(NULL) {
}
template <typename Element>
inline RepeatedField<Element>::RepeatedField(Arena* arena)
: current_size_(0),
total_size_(0),
- rep_(NULL) {
- // In case arena is NULL, then we do not create rep_, as code has an invariant
- // `rep_ == NULL then arena == NULL`.
- if (arena != NULL) {
- rep_ = reinterpret_cast<Rep*>(
- ::google::protobuf::Arena::CreateArray<char>(arena, kRepHeaderSize));
- rep_->arena = arena;
- }
+ ptr_(arena) {
}
template <typename Element>
inline RepeatedField<Element>::RepeatedField(const RepeatedField& other)
: current_size_(0),
total_size_(0),
- rep_(NULL) {
+ ptr_(NULL) {
if (other.current_size_ != 0) {
- Reserve(other.current_size_);
- CopyArray(rep_->elements,
- other.rep_->elements, other.current_size_);
- current_size_ = other.current_size_;
+ Reserve(other.size());
+ AddNAlreadyReserved(other.size());
+ CopyArray(Mutable(0), &other.Get(0), other.size());
}
}
@@ -1070,7 +1057,7 @@ template <typename Iter>
RepeatedField<Element>::RepeatedField(Iter begin, const Iter& end)
: current_size_(0),
total_size_(0),
- rep_(NULL) {
+ ptr_(NULL) {
int reserve = internal::CalculateReserve(begin, end);
if (reserve != -1) {
Reserve(reserve);
@@ -1086,9 +1073,9 @@ RepeatedField<Element>::RepeatedField(Iter begin, const Iter& end)
template <typename Element>
RepeatedField<Element>::~RepeatedField() {
- // See explanation in Reserve(): we need to invoke destructors here for the
- // case that Element has a non-trivial destructor.
- InternalDeallocate(rep_, total_size_);
+ if (total_size_ > 0) {
+ InternalDeallocate(rep(), total_size_);
+ }
}
template <typename Element>
@@ -1099,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() {
@@ -1128,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;
@@ -1148,19 +1131,21 @@ inline int RepeatedField<Element>::Capacity() const {
template<typename Element>
inline void RepeatedField<Element>::AddAlreadyReserved(const Element& value) {
GOOGLE_DCHECK_LT(current_size_, total_size_);
- rep_->elements[current_size_++] = value;
+ rep()->elements[current_size_++] = value;
}
template<typename Element>
inline Element* RepeatedField<Element>::AddAlreadyReserved() {
GOOGLE_DCHECK_LT(current_size_, total_size_);
- return &rep_->elements[current_size_++];
+ return &rep()->elements[current_size_++];
}
template<typename Element>
inline Element* RepeatedField<Element>::AddNAlreadyReserved(int elements) {
GOOGLE_DCHECK_LE(current_size_ + elements, total_size_);
- Element* ret = &rep_->elements[current_size_];
+ // Warning: total_size_ can be NULL if elements == 0 && current_size_ == 0.
+ // Existing callers depend on this behavior. :(
+ Element* ret = &ptr_.rep->elements[current_size_];
current_size_ += elements;
return ret;
}
@@ -1170,8 +1155,8 @@ inline void RepeatedField<Element>::Resize(int new_size, const Element& value) {
GOOGLE_DCHECK_GE(new_size, 0);
if (new_size > current_size_) {
Reserve(new_size);
- std::fill(&rep_->elements[current_size_],
- &rep_->elements[new_size], value);
+ std::fill(&rep()->elements[current_size_],
+ &rep()->elements[new_size], value);
}
current_size_ = new_size;
}
@@ -1180,33 +1165,33 @@ template <typename Element>
inline const Element& RepeatedField<Element>::Get(int index) const {
GOOGLE_DCHECK_GE(index, 0);
GOOGLE_DCHECK_LT(index, current_size_);
- return rep_->elements[index];
+ return rep()->elements[index];
}
template <typename Element>
inline Element* RepeatedField<Element>::Mutable(int index) {
GOOGLE_DCHECK_GE(index, 0);
GOOGLE_DCHECK_LT(index, current_size_);
- return &rep_->elements[index];
+ return &rep()->elements[index];
}
template <typename Element>
inline void RepeatedField<Element>::Set(int index, const Element& value) {
GOOGLE_DCHECK_GE(index, 0);
GOOGLE_DCHECK_LT(index, current_size_);
- rep_->elements[index] = value;
+ rep()->elements[index] = value;
}
template <typename Element>
inline void RepeatedField<Element>::Add(const Element& value) {
if (current_size_ == total_size_) Reserve(total_size_ + 1);
- rep_->elements[current_size_++] = value;
+ rep()->elements[current_size_++] = value;
}
template <typename Element>
inline Element* RepeatedField<Element>::Add() {
if (current_size_ == total_size_) Reserve(total_size_ + 1);
- return &rep_->elements[current_size_++];
+ return &rep()->elements[current_size_++];
}
template <typename Element>
@@ -1245,10 +1230,10 @@ template <typename Element>
inline void RepeatedField<Element>::MergeFrom(const RepeatedField& other) {
GOOGLE_DCHECK_NE(&other, this);
if (other.current_size_ != 0) {
- Reserve(current_size_ + other.current_size_);
- CopyArray(rep_->elements + current_size_,
- other.rep_->elements, other.current_size_);
- current_size_ += other.current_size_;
+ int existing_size = size();
+ Reserve(existing_size + other.size());
+ AddNAlreadyReserved(other.size());
+ CopyArray(Mutable(existing_size), &other.Get(0), other.size());
}
}
@@ -1277,18 +1262,17 @@ inline typename RepeatedField<Element>::iterator RepeatedField<Element>::erase(
template <typename Element>
inline Element* RepeatedField<Element>::mutable_data() {
- return rep_ ? rep_->elements : NULL;
+ return total_size_ > 0 ? rep()->elements : NULL;
}
template <typename Element>
inline const Element* RepeatedField<Element>::data() const {
- return rep_ ? rep_->elements : NULL;
+ return total_size_ > 0 ? rep()->elements : NULL;
}
template <typename Element>
inline const Element* RepeatedField<Element>::unsafe_data() const {
- GOOGLE_DCHECK(rep_);
- return rep_->elements;
+ return rep()->elements;
}
template <typename Element>
@@ -1296,7 +1280,7 @@ inline void RepeatedField<Element>::InternalSwap(RepeatedField* other) {
GOOGLE_DCHECK(this != other);
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
- std::swap(rep_, other->rep_);
+ std::swap(ptr_, other->ptr_);
std::swap(current_size_, other->current_size_);
std::swap(total_size_, other->total_size_);
}
@@ -1323,43 +1307,43 @@ void RepeatedField<Element>::UnsafeArenaSwap(RepeatedField* other) {
template <typename Element>
void RepeatedField<Element>::SwapElements(int index1, int index2) {
using std::swap; // enable ADL with fallback
- swap(rep_->elements[index1], rep_->elements[index2]);
+ swap(rep()->elements[index1], rep()->elements[index2]);
}
template <typename Element>
inline typename RepeatedField<Element>::iterator
RepeatedField<Element>::begin() {
- return rep_ ? rep_->elements : NULL;
+ return total_size_ > 0 ? rep()->elements : NULL;
}
template <typename Element>
inline typename RepeatedField<Element>::const_iterator
RepeatedField<Element>::begin() const {
- return rep_ ? rep_->elements : NULL;
+ return total_size_ > 0 ? rep()->elements : NULL;
}
template <typename Element>
inline typename RepeatedField<Element>::const_iterator
RepeatedField<Element>::cbegin() const {
- return rep_ ? rep_->elements : NULL;
+ return total_size_ > 0 ? rep()->elements : NULL;
}
template <typename Element>
inline typename RepeatedField<Element>::iterator
RepeatedField<Element>::end() {
- return rep_ ? rep_->elements + current_size_ : NULL;
+ return total_size_ > 0 ? rep()->elements + current_size_ : NULL;
}
template <typename Element>
inline typename RepeatedField<Element>::const_iterator
RepeatedField<Element>::end() const {
- return rep_ ? rep_->elements + current_size_ : NULL;
+ return total_size_ > 0 ? rep()->elements + current_size_ : NULL;
}
template <typename Element>
inline typename RepeatedField<Element>::const_iterator
RepeatedField<Element>::cend() const {
- return rep_ ? rep_->elements + current_size_ : NULL;
+ return total_size_ > 0 ? rep()->elements + current_size_ : NULL;
}
template <typename Element>
inline size_t RepeatedField<Element>::SpaceUsedExcludingSelfLong() const {
- return rep_ ? (total_size_ * sizeof(Element) + kRepHeaderSize) : 0;
+ return total_size_ > 0 ? (total_size_ * sizeof(Element) + kRepHeaderSize) : 0;
}
// Avoid inlining of Reserve(): new, copy, and delete[] lead to a significant
@@ -1367,7 +1351,7 @@ inline size_t RepeatedField<Element>::SpaceUsedExcludingSelfLong() const {
template <typename Element>
void RepeatedField<Element>::Reserve(int new_size) {
if (total_size_ >= new_size) return;
- Rep* old_rep = rep_;
+ Rep* old_rep = total_size_ > 0 ? rep() : NULL;
Arena* arena = GetArenaNoVirtual();
new_size = std::max(google::protobuf::internal::kMinRepeatedFieldAllocationSize,
std::max(total_size_ * 2, new_size));
@@ -1377,12 +1361,12 @@ void RepeatedField<Element>::Reserve(int new_size) {
<< "Requested size is too large to fit into size_t.";
size_t bytes = kRepHeaderSize + sizeof(Element) * static_cast<size_t>(new_size);
if (arena == NULL) {
- rep_ = static_cast<Rep*>(::operator new(bytes));
+ ptr_.rep = static_cast<Rep*>(::operator new(bytes));
} else {
- rep_ = reinterpret_cast<Rep*>(
+ ptr_.rep = reinterpret_cast<Rep*>(
::google::protobuf::Arena::CreateArray<char>(arena, bytes));
}
- rep_->arena = arena;
+ ptr_.rep->arena = arena;
int old_total_size = total_size_;
total_size_ = new_size;
// Invoke placement-new on newly allocated elements. We shouldn't have to do
@@ -1394,13 +1378,13 @@ void RepeatedField<Element>::Reserve(int new_size) {
// effect unless its side-effects are required for correctness.
// Note that we do this before MoveArray() below because Element's copy
// assignment implementation will want an initialized instance first.
- Element* e = &rep_->elements[0];
- Element* limit = &rep_->elements[total_size_];
+ Element* e = &rep()->elements[0];
+ Element* limit = e + total_size_;
for (; e < limit; e++) {
new (e) Element;
}
if (current_size_ > 0) {
- MoveArray(rep_->elements, old_rep->elements, current_size_);
+ MoveArray(&rep()->elements[0], old_rep->elements, current_size_);
}
// Likewise, we need to invoke destructors on the old array.
@@ -1516,14 +1500,13 @@ inline int RepeatedPtrFieldBase::size() const {
}
template <typename TypeHandler>
-inline const typename TypeHandler::Type&
+inline const typename TypeHandler::WeakType&
RepeatedPtrFieldBase::Get(int index) const {
GOOGLE_DCHECK_GE(index, 0);
GOOGLE_DCHECK_LT(index, current_size_);
return *cast<TypeHandler>(rep_->elements[index]);
}
-
template <typename TypeHandler>
inline typename TypeHandler::Type*
RepeatedPtrFieldBase::Mutable(int index) {
@@ -1555,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;
@@ -1572,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() {
@@ -1632,18 +1613,18 @@ void RepeatedPtrFieldBase::MergeFromInnerLoop(
// to avoid a branch within the loop.
for (int i = 0; i < already_allocated && i < length; i++) {
// Already allocated: use existing element.
- typename TypeHandler::Type* other_elem =
- reinterpret_cast<typename TypeHandler::Type*>(other_elems[i]);
- typename TypeHandler::Type* new_elem =
- reinterpret_cast<typename TypeHandler::Type*>(our_elems[i]);
+ typename TypeHandler::WeakType* other_elem =
+ reinterpret_cast<typename TypeHandler::WeakType*>(other_elems[i]);
+ typename TypeHandler::WeakType* new_elem =
+ reinterpret_cast<typename TypeHandler::WeakType*>(our_elems[i]);
TypeHandler::Merge(*other_elem, new_elem);
}
Arena* arena = GetArenaNoVirtual();
for (int i = already_allocated; i < length; i++) {
// Not allocated: alloc a new element first, then merge it.
- typename TypeHandler::Type* other_elem =
- reinterpret_cast<typename TypeHandler::Type*>(other_elems[i]);
- typename TypeHandler::Type* new_elem =
+ typename TypeHandler::WeakType* other_elem =
+ reinterpret_cast<typename TypeHandler::WeakType*>(other_elems[i]);
+ typename TypeHandler::WeakType* new_elem =
TypeHandler::NewFromPrototype(other_elem, arena);
TypeHandler::Merge(*other_elem, new_elem);
our_elems[i] = new_elem;
@@ -1715,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();
@@ -1765,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
@@ -1815,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.
@@ -1836,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; "
@@ -1942,8 +1923,6 @@ inline RepeatedPtrField<Element>& RepeatedPtrField<Element>::operator=(
return *this;
}
-#if LANG_CXX11
-
template <typename Element>
inline RepeatedPtrField<Element>::RepeatedPtrField(
RepeatedPtrField&& other) noexcept
@@ -1972,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();
@@ -2000,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() {
@@ -2035,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());
@@ -2068,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
@@ -2240,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.
@@ -2258,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));
}
}
@@ -2334,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.
@@ -2519,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;
}
@@ -2639,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 4a290e1e..739172f8 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];
@@ -70,15 +67,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
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 ::google::protobuf::internal::once_flag once;
+ ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
@@ -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,17 +162,10 @@ 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();
}
-SourceContext* SourceContext::New(::google::protobuf::Arena* arena) const {
- SourceContext* n = new SourceContext;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
-}
void SourceContext::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.SourceContext)
@@ -199,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)) {
@@ -305,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;
}
@@ -363,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 {
@@ -377,5 +359,12 @@ void SourceContext::InternalSwap(SourceContext* other) {
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
+namespace google {
+namespace protobuf {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceContext* Arena::CreateMaybeMessage< ::google::protobuf::SourceContext >(Arena* arena) {
+ return Arena::CreateInternal< ::google::protobuf::SourceContext >(arena);
+}
+} // namespace protobuf
+} // namespace google
// @@protoc_insertion_point(global_scope)
diff --git a/src/google/protobuf/source_context.pb.h b/src/google/protobuf/source_context.pb.h
index dfa2444c..16ed21ca 100644
--- a/src/google/protobuf/source_context.pb.h
+++ b/src/google/protobuf/source_context.pb.h
@@ -1,8 +1,8 @@
// 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>
@@ -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,6 +54,11 @@ LIBPROTOBUF_EXPORT extern SourceContextDefaultTypeInternal _SourceContext_defaul
} // namespace google
namespace google {
namespace protobuf {
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceContext* Arena::CreateMaybeMessage<::google::protobuf::SourceContext>(Arena*);
+} // namespace protobuf
+} // namespace google
+namespace google {
+namespace protobuf {
// ===================================================================
@@ -94,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);
@@ -104,28 +106,33 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
// implements Message ----------------------------------------------
- inline SourceContext* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline SourceContext* New() const final {
+ return CreateMaybeMessage<SourceContext>(NULL);
+ }
- SourceContext* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ SourceContext* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<SourceContext>(arena);
+ }
+ 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 {
@@ -136,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 ----------------------------------------------------
@@ -161,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();
};
// ===================================================================
@@ -240,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 fe3ba327..8f2d4848 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];
@@ -142,15 +142,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
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 ::google::protobuf::internal::once_flag once;
+ ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
@@ -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() {
@@ -284,9 +280,7 @@ void Struct::ArenaDtor(void* object) {
void Struct::RegisterArenaDtor(::google::protobuf::Arena* 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,13 +288,10 @@ 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();
}
-Struct* Struct::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<Struct>(arena);
-}
void Struct::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Struct)
@@ -318,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)) {
@@ -388,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;
@@ -398,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));
@@ -410,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) {
@@ -457,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;
@@ -467,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));
@@ -481,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) {
@@ -520,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) {
@@ -537,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;
}
@@ -609,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 {
@@ -672,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()) {
@@ -726,7 +712,6 @@ Value::Value(const Value& from)
void Value::SharedCtor() {
clear_has_kind();
- _cached_size_ = 0;
}
Value::~Value() {
@@ -748,9 +733,7 @@ void Value::ArenaDtor(void* object) {
void Value::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -758,13 +741,10 @@ 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();
}
-Value* Value::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<Value>(arena);
-}
void Value::clear_kind() {
// @@protoc_insertion_point(one_of_clear_start:google.protobuf.Value)
@@ -822,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)) {
@@ -966,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())) {
@@ -1020,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())) {
@@ -1090,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;
}
@@ -1191,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 {
@@ -1210,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)
}
@@ -1220,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)
@@ -1228,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() {
@@ -1254,9 +1228,7 @@ void ListValue::ArenaDtor(void* object) {
void ListValue::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -1264,13 +1236,10 @@ 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();
}
-ListValue* ListValue::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<ListValue>(arena);
-}
void ListValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.ListValue)
@@ -1288,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)) {
@@ -1296,7 +1265,8 @@ bool ListValue::MergePartialFromCodedStream(
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_values()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_values()));
} else {
goto handle_unusual;
}
@@ -1333,7 +1303,9 @@ void ListValue::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->values_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 1, this->values(static_cast<int>(i)), output);
+ 1,
+ this->values(static_cast<int>(i)),
+ output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
@@ -1387,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;
}
@@ -1457,9 +1427,8 @@ void ListValue::UnsafeArenaSwap(ListValue* other) {
}
void ListValue::InternalSwap(ListValue* other) {
using std::swap;
- values_.InternalSwap(&other->values_);
+ CastToBase(&values_)->InternalSwap(CastToBase(&other->values_));
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata ListValue::GetMetadata() const {
@@ -1471,5 +1440,21 @@ void ListValue::InternalSwap(ListValue* other) {
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
+namespace google {
+namespace protobuf {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage< ::google::protobuf::Struct_FieldsEntry_DoNotUse >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::Struct_FieldsEntry_DoNotUse >(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::CreateMaybeMessage< ::google::protobuf::Value >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::Value >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ListValue* Arena::CreateMaybeMessage< ::google::protobuf::ListValue >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::ListValue >(arena);
+}
+} // namespace protobuf
+} // namespace google
// @@protoc_insertion_point(global_scope)
diff --git a/src/google/protobuf/struct.pb.h b/src/google/protobuf/struct.pb.h
index cdc00dcd..75665ff2 100644
--- a/src/google/protobuf/struct.pb.h
+++ b/src/google/protobuf/struct.pb.h
@@ -1,8 +1,8 @@
// 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>
@@ -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,6 +67,14 @@ LIBPROTOBUF_EXPORT extern ValueDefaultTypeInternal _Value_default_instance_;
} // namespace google
namespace google {
namespace protobuf {
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::ListValue* Arena::CreateMaybeMessage<::google::protobuf::ListValue>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct* Arena::CreateMaybeMessage<::google::protobuf::Struct>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage<::google::protobuf::Struct_FieldsEntry_DoNotUse>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Value* Arena::CreateMaybeMessage<::google::protobuf::Value>(Arena*);
+} // namespace protobuf
+} // namespace google
+namespace google {
+namespace protobuf {
enum NullValue {
NULL_VALUE = 0,
@@ -108,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;
};
@@ -140,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();
@@ -154,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);
@@ -165,28 +170,33 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
// implements Message ----------------------------------------------
- inline Struct* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Struct* New() const final {
+ return CreateMaybeMessage<Struct>(NULL);
+ }
- Struct* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Struct* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Struct>(arena);
+ }
+ 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);
@@ -202,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 ----------------------------------------------------
@@ -231,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();
};
// -------------------------------------------------------------------
@@ -263,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();
@@ -287,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);
@@ -298,28 +307,33 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
// implements Message ----------------------------------------------
- inline Value* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Value* New() const final {
+ return CreateMaybeMessage<Value>(NULL);
+ }
- Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Value* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Value>(arena);
+ }
+ 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);
@@ -335,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 ----------------------------------------------------
@@ -399,7 +413,7 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
void clear_struct_value();
static const int kStructValueFieldNumber = 5;
private:
- void _slow_mutable_struct_value();
+ const ::google::protobuf::Struct& _internal_struct_value() const;
public:
const ::google::protobuf::Struct& struct_value() const;
::google::protobuf::Struct* release_struct_value();
@@ -414,7 +428,7 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
void clear_list_value();
static const int kListValueFieldNumber = 6;
private:
- void _slow_mutable_list_value();
+ const ::google::protobuf::ListValue& _internal_list_value() const;
public:
const ::google::protobuf::ListValue& list_value() const;
::google::protobuf::ListValue* release_list_value();
@@ -424,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:
@@ -435,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_;
@@ -451,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();
};
// -------------------------------------------------------------------
@@ -485,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();
@@ -499,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);
@@ -510,28 +523,33 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
// implements Message ----------------------------------------------
- inline ListValue* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline ListValue* New() const final {
+ return CreateMaybeMessage<ListValue>(NULL);
+ }
- ListValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ ListValue* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<ListValue>(arena);
+ }
+ 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);
@@ -547,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 ----------------------------------------------------
@@ -557,11 +575,11 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
int values_size() const;
void clear_values();
static const int kValuesFieldNumber = 1;
- const ::google::protobuf::Value& values(int index) const;
::google::protobuf::Value* mutable_values(int index);
- ::google::protobuf::Value* add_values();
::google::protobuf::RepeatedPtrField< ::google::protobuf::Value >*
mutable_values();
+ const ::google::protobuf::Value& values(int index) const;
+ ::google::protobuf::Value* add_values();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Value >&
values() const;
@@ -573,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();
};
// ===================================================================
@@ -838,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;
@@ -881,9 +901,8 @@ inline ::google::protobuf::Struct* Value::mutable_struct_value() {
if (!has_struct_value()) {
clear_kind();
set_has_struct_value();
- kind_.struct_value_ =
- ::google::protobuf::Arena::CreateMessage< ::google::protobuf::Struct >(
- GetArenaNoVirtual());
+ kind_.struct_value_ = CreateMaybeMessage< ::google::protobuf::Struct >(
+ GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Value.struct_value)
return kind_.struct_value_;
@@ -904,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;
@@ -947,9 +969,8 @@ inline ::google::protobuf::ListValue* Value::mutable_list_value() {
if (!has_list_value()) {
clear_kind();
set_has_list_value();
- kind_.list_value_ =
- ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ListValue >(
- GetArenaNoVirtual());
+ kind_.list_value_ = CreateMaybeMessage< ::google::protobuf::ListValue >(
+ GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Value.list_value)
return kind_.list_value_;
@@ -975,23 +996,23 @@ inline int ListValue::values_size() const {
inline void ListValue::clear_values() {
values_.Clear();
}
-inline const ::google::protobuf::Value& ListValue::values(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.ListValue.values)
- return values_.Get(index);
-}
inline ::google::protobuf::Value* ListValue::mutable_values(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.ListValue.values)
return values_.Mutable(index);
}
-inline ::google::protobuf::Value* ListValue::add_values() {
- // @@protoc_insertion_point(field_add:google.protobuf.ListValue.values)
- return values_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Value >*
ListValue::mutable_values() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.ListValue.values)
return &values_;
}
+inline const ::google::protobuf::Value& ListValue::values(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.ListValue.values)
+ return values_.Get(index);
+}
+inline ::google::protobuf::Value* ListValue::add_values() {
+ // @@protoc_insertion_point(field_add:google.protobuf.ListValue.values)
+ return values_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Value >&
ListValue::values() const {
// @@protoc_insertion_point(field_list:google.protobuf.ListValue.values)
@@ -1016,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();
@@ -1027,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 0b0b06ce..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_generic_gcc.h
+++ /dev/null
@@ -1,155 +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);
-}
-
-#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/callback.h b/src/google/protobuf/stubs/callback.h
index 9ec04979..6888f136 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
@@ -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;
};
@@ -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 73822168..33d24c57 100755
--- 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
@@ -430,9 +350,9 @@ struct ShutdownData {
}
}
- vector<void (*)()> functions;
- vector<const std::string*> strings;
- vector<const MessageLite*> messages;
+ std::vector<void (*)()> functions;
+ std::vector<const std::string*> strings;
+ std::vector<const MessageLite*> messages;
Mutex mutex;
};
diff --git a/src/google/protobuf/stubs/common.h b/src/google/protobuf/stubs/common.h
index d11b8100..c336383d 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>
@@ -229,12 +229,7 @@ class FatalException : public std::exception {
// This is at the end of the file instead of the beginning to work around a bug
// in some versions of MSVC.
-// TODO(acozzette): remove these using statements
-using std::istream;
-using std::ostream;
-using std::pair;
using std::string;
-using std::vector;
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/stubs/common_unittest.cc b/src/google/protobuf/stubs/common_unittest.cc
index f9e2cfd4..798a2a27 100644
--- a/src/google/protobuf/stubs/common_unittest.cc
+++ b/src/google/protobuf/stubs/common_unittest.cc
@@ -75,7 +75,7 @@ TEST(CommonTest, IntMinMaxConstants) {
EXPECT_EQ(0, kuint64max + 1);
}
-vector<string> captured_messages_;
+std::vector<string> captured_messages_;
void CaptureLog(LogLevel level, const char* filename, int line,
const string& message) {
diff --git a/src/google/protobuf/stubs/hash.h b/src/google/protobuf/stubs/hash.h
index 218cd948..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> {
@@ -408,8 +409,8 @@ struct hash<string> {
};
template <typename First, typename Second>
-struct hash<pair<First, Second> > {
- inline size_t operator()(const pair<First, Second>& key) const {
+struct hash<std::pair<First, Second> > {
+ inline size_t operator()(const std::pair<First, Second>& key) const {
size_t first_hash = hash<First>()(key.first);
size_t second_hash = hash<Second>()(key.second);
@@ -420,8 +421,8 @@ struct hash<pair<First, Second> > {
static const size_t bucket_size = 4;
static const size_t min_buckets = 8;
- inline bool operator()(const pair<First, Second>& a,
- const pair<First, Second>& b) const {
+ inline bool operator()(const std::pair<First, Second>& a,
+ const std::pair<First, Second>& b) const {
return a < b;
}
};
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 b59b8e48..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>
@@ -151,12 +151,13 @@ wstring normalize(wstring path) {
static const wstring dot(L".");
static const wstring dotdot(L"..");
+ const WCHAR* p = path.c_str();
std::vector<wstring> segments;
int segment_start = -1;
// Find the path segments in `path` (separated by "/").
for (int i = 0;; ++i) {
- if (!is_separator(path[i]) && path[i] != L'\0') {
+ if (!is_separator(p[i]) && p[i] != L'\0') {
// The current character does not end a segment, so start one unless it's
// already started.
if (segment_start < 0) {
@@ -165,7 +166,7 @@ wstring normalize(wstring path) {
} else if (segment_start >= 0 && i > segment_start) {
// The current character is "/" or "\0", so this ends a segment.
// Add that to `segments` if there's anything to add; handle "." and "..".
- wstring segment(path, segment_start, i - segment_start);
+ wstring segment(p, segment_start, i - segment_start);
segment_start = -1;
if (segment == dotdot) {
if (!segments.empty() &&
@@ -176,7 +177,7 @@ wstring normalize(wstring path) {
segments.push_back(segment);
}
}
- if (path[i] == L'\0') {
+ if (p[i] == L'\0') {
break;
}
}
@@ -199,7 +200,7 @@ wstring normalize(wstring path) {
result << segments[i];
}
// Preserve trailing separator if the input contained it.
- if (!path.empty() && is_separator(path[path.size() - 1])) {
+ if (!path.empty() && is_separator(p[path.size() - 1])) {
result << L'\\';
}
return result.str();
@@ -228,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);
}
@@ -370,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());
@@ -389,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 887f12a6..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();
//
@@ -708,7 +709,7 @@ void AppendKeysFromMap(const MapContainer& map_container,
// without the complexity of a SFINAE-based solution.)
template <class MapContainer, class KeyType>
void AppendKeysFromMap(const MapContainer& map_container,
- vector<KeyType>* key_container) {
+ std::vector<KeyType>* key_container) {
GOOGLE_CHECK(key_container != NULL);
// We now have the opportunity to call reserve(). Calling reserve() every
// time is a bad idea for some use cases: libstdc++'s implementation of
@@ -752,7 +753,7 @@ void AppendValuesFromMap(const MapContainer& map_container,
// without the complexity of a SFINAE-based solution.)
template <class MapContainer, class ValueType>
void AppendValuesFromMap(const MapContainer& map_container,
- vector<ValueType>* value_container) {
+ std::vector<ValueType>* value_container) {
GOOGLE_CHECK(value_container != NULL);
// See AppendKeysFromMap for why this is done.
if (value_container->empty()) {
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..b9b7d2e1 100644
--- a/src/google/protobuf/stubs/mutex.h
+++ b/src/google/protobuf/stubs/mutex.h
@@ -30,9 +30,7 @@
#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>
@@ -42,34 +40,26 @@ 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() { mu_.lock(); }
+ void Unlock() { 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:
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/port.h b/src/google/protobuf/stubs/port.h
index cecefdcb..6b52305f 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).
@@ -237,20 +258,6 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF);
#define GOOGLE_SAFE_CONCURRENT_WRITES_END()
#endif
-#if defined(__clang__) && defined(__has_cpp_attribute) \
- && !defined(GOOGLE_PROTOBUF_OS_APPLE)
-# if defined(GOOGLE_PROTOBUF_OS_NACL) || defined(EMSCRIPTEN) || \
- __has_cpp_attribute(clang::fallthrough)
-# define GOOGLE_FALLTHROUGH_INTENDED [[clang::fallthrough]]
-# endif
-#elif defined(__GNUC__) && __GNUC__ > 6
-# define GOOGLE_FALLTHROUGH_INTENDED [[gnu::fallthrough]]
-#endif
-
-#ifndef GOOGLE_FALLTHROUGH_INTENDED
-# define GOOGLE_FALLTHROUGH_INTENDED
-#endif
-
#define GOOGLE_GUARDED_BY(x)
#define GOOGLE_ATTRIBUTE_COLD
@@ -348,6 +355,13 @@ inline void GOOGLE_UNALIGNED_STORE64(void *p, uint64 v) {
}
#endif
+#if defined(GOOGLE_PROTOBUF_OS_NACL) \
+ || (defined(__ANDROID__) && defined(__clang__) \
+ && (__clang_major__ == 3 && __clang_minor__ == 8) \
+ && (__clang_patchlevel__ < 275480))
+# define GOOGLE_PROTOBUF_USE_PORTABLE_LOG2
+#endif
+
#if defined(_MSC_VER)
#define GOOGLE_THREAD_LOCAL __declspec(thread)
#else
@@ -366,7 +380,7 @@ 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__)
static inline uint16 bswap_16(uint16 x) {
return static_cast<uint16>(((x & 0xFF) << 8) | ((x & 0xFF00) >> 8));
@@ -401,25 +415,28 @@ 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
}
static uint32 Log2FloorNonZero64(uint64 n) {
- // arm-nacl-clang runs into an instruction-selection failure when it
- // encounters __builtin_clzll:
+ // Older versions of clang run into an instruction-selection failure when
+ // it encounters __builtin_clzll:
// https://bugs.chromium.org/p/nativeclient/issues/detail?id=4395
- // To work around this, when we build for NaCl we use the portable
+ // This includes arm-nacl-clang and clang in older Android NDK versions.
+ // To work around this, when we build with those we use the portable
// implementation instead.
-#if defined(__GNUC__) && !defined(GOOGLE_PROTOBUF_OS_NACL)
+#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/status.cc b/src/google/protobuf/stubs/status.cc
index dd1bd614..2bfbe0b4 100644
--- a/src/google/protobuf/stubs/status.cc
+++ b/src/google/protobuf/stubs/status.cc
@@ -124,7 +124,7 @@ string Status::ToString() const {
}
}
-ostream& operator<<(ostream& os, const Status& x) {
+std::ostream& operator<<(std::ostream& os, const Status& x) {
os << x.ToString();
return os;
}
diff --git a/src/google/protobuf/stubs/status.h b/src/google/protobuf/stubs/status.h
index 614ab994..c5d38f0b 100644
--- a/src/google/protobuf/stubs/status.h
+++ b/src/google/protobuf/stubs/status.h
@@ -106,7 +106,7 @@ class LIBPROTOBUF_EXPORT Status {
};
// Prints a human-readable representation of 'x' to 'os'.
-LIBPROTOBUF_EXPORT ostream& operator<<(ostream& os, const Status& x);
+LIBPROTOBUF_EXPORT std::ostream& operator<<(std::ostream& os, const Status& x);
#define EXPECT_OK(value) EXPECT_TRUE((value).ok())
diff --git a/src/google/protobuf/stubs/stringprintf.cc b/src/google/protobuf/stubs/stringprintf.cc
index 83fdfe45..d98b9b87 100644
--- a/src/google/protobuf/stubs/stringprintf.cc
+++ b/src/google/protobuf/stubs/stringprintf.cc
@@ -137,7 +137,7 @@ const int kStringPrintfVectorMaxArgs = 32;
// and we can fix the problem or protect against an attack.
static const char string_printf_empty_block[256] = { '\0' };
-string StringPrintfVector(const char* format, const vector<string>& v) {
+string StringPrintfVector(const char* format, const std::vector<string>& v) {
GOOGLE_CHECK_LE(v.size(), kStringPrintfVectorMaxArgs)
<< "StringPrintfVector currently only supports up to "
<< kStringPrintfVectorMaxArgs << " arguments. "
diff --git a/src/google/protobuf/stubs/stringprintf.h b/src/google/protobuf/stubs/stringprintf.h
index ab1ab558..7183ec6a 100644
--- a/src/google/protobuf/stubs/stringprintf.h
+++ b/src/google/protobuf/stubs/stringprintf.h
@@ -68,7 +68,7 @@ LIBPROTOBUF_EXPORT extern const int kStringPrintfVectorMaxArgs;
// You can use this version when all your arguments are strings, but
// you don't know how many arguments you'll have at compile time.
// StringPrintfVector will LOG(FATAL) if v.size() > kStringPrintfVectorMaxArgs
-LIBPROTOBUF_EXPORT extern string StringPrintfVector(const char* format, const vector<string>& v);
+LIBPROTOBUF_EXPORT extern string StringPrintfVector(const char* format, const std::vector<string>& v);
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/stubs/structurally_valid.cc b/src/google/protobuf/stubs/structurally_valid.cc
index d79a6ee4..b2239682 100644
--- a/src/google/protobuf/stubs/structurally_valid.cc
+++ b/src/google/protobuf/stubs/structurally_valid.cc
@@ -1,4 +1,33 @@
-// Copyright 2005-2008 Google Inc. All Rights Reserved.
+// 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: jrm@google.com (Jim Meehan)
#include <google/protobuf/stubs/common.h>
diff --git a/src/google/protobuf/stubs/structurally_valid_unittest.cc b/src/google/protobuf/stubs/structurally_valid_unittest.cc
index 90888885..eec07a87 100644
--- a/src/google/protobuf/stubs/structurally_valid_unittest.cc
+++ b/src/google/protobuf/stubs/structurally_valid_unittest.cc
@@ -1,3 +1,33 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
// Copyright 2008 Google Inc. All Rights Reserved.
// Author: xpeng@google.com (Peter Peng)
diff --git a/src/google/protobuf/stubs/strutil.cc b/src/google/protobuf/stubs/strutil.cc
index 1a4d71c8..552d416f 100644
--- a/src/google/protobuf/stubs/strutil.cc
+++ b/src/google/protobuf/stubs/strutil.cc
@@ -226,8 +226,8 @@ void SplitStringToIteratorUsing(const string& full,
void SplitStringUsing(const string& full,
const char* delim,
- vector<string>* result) {
- std::back_insert_iterator< vector<string> > it(*result);
+ std::vector<string>* result) {
+ std::back_insert_iterator< std::vector<string> > it(*result);
SplitStringToIteratorUsing(full, delim, it);
}
@@ -264,8 +264,8 @@ void SplitStringToIteratorAllowEmpty(const StringType& full,
}
void SplitStringAllowEmpty(const string& full, const char* delim,
- vector<string>* result) {
- std::back_insert_iterator<vector<string> > it(*result);
+ std::vector<string>* result) {
+ std::back_insert_iterator<std::vector<string> > it(*result);
SplitStringToIteratorAllowEmpty(full, delim, 0, it);
}
@@ -303,7 +303,7 @@ static void JoinStringsIterator(const ITERATOR& start,
}
}
-void JoinStrings(const vector<string>& components,
+void JoinStrings(const std::vector<string>& components,
const char* delim,
string * result) {
JoinStringsIterator(components.begin(), components.end(), delim, result);
@@ -332,7 +332,7 @@ int UnescapeCEscapeSequences(const char* source, char* dest) {
}
int UnescapeCEscapeSequences(const char* source, char* dest,
- vector<string> *errors) {
+ std::vector<string> *errors) {
GOOGLE_DCHECK(errors == NULL) << "Error reporting not implemented.";
char* d = dest;
@@ -468,8 +468,8 @@ int UnescapeCEscapeString(const string& src, string* dest) {
}
int UnescapeCEscapeString(const string& src, string* dest,
- vector<string> *errors) {
- scoped_array<char> unescaped(new char[src.size() + 1]);
+ std::vector<string> *errors) {
+ 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/strutil.h b/src/google/protobuf/stubs/strutil.h
index df28c94d..a839b8b3 100644
--- a/src/google/protobuf/stubs/strutil.h
+++ b/src/google/protobuf/stubs/strutil.h
@@ -213,7 +213,7 @@ LIBPROTOBUF_EXPORT string StringReplace(const string& s, const string& oldsub,
// over all of them.
// ----------------------------------------------------------------------
LIBPROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim,
- vector<string>* res);
+ std::vector<string>* res);
// Split a string using one or more byte delimiters, presented
// as a nul-terminated c string. Append the components to 'result'.
@@ -225,15 +225,15 @@ LIBPROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim,
// ----------------------------------------------------------------------
LIBPROTOBUF_EXPORT void SplitStringAllowEmpty(const string& full,
const char* delim,
- vector<string>* result);
+ std::vector<string>* result);
// ----------------------------------------------------------------------
// Split()
// Split a string using a character delimiter.
// ----------------------------------------------------------------------
-inline vector<string> Split(
+inline std::vector<string> Split(
const string& full, const char* delim, bool skip_empty = true) {
- vector<string> result;
+ std::vector<string> result;
if (skip_empty) {
SplitStringUsing(full, delim, &result);
} else {
@@ -250,10 +250,10 @@ inline vector<string> Split(
// another takes a pointer to the target string. In the latter case the
// target string is cleared and overwritten.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT void JoinStrings(const vector<string>& components,
+LIBPROTOBUF_EXPORT void JoinStrings(const std::vector<string>& components,
const char* delim, string* result);
-inline string JoinStrings(const vector<string>& components,
+inline string JoinStrings(const std::vector<string>& components,
const char* delim) {
string result;
JoinStrings(components, delim, &result);
@@ -285,15 +285,15 @@ inline string JoinStrings(const vector<string>& components,
//
// Errors: In the first form of the call, errors are reported with
// LOG(ERROR). The same is true for the second form of the call if
-// the pointer to the string vector is NULL; otherwise, error
-// messages are stored in the vector. In either case, the effect on
+// the pointer to the string std::vector is NULL; otherwise, error
+// messages are stored in the std::vector. In either case, the effect on
// the dest array is not defined, but rest of the source will be
// processed.
// ----------------------------------------------------------------------
LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest);
LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest,
- vector<string> *errors);
+ std::vector<string> *errors);
// ----------------------------------------------------------------------
// UnescapeCEscapeString()
@@ -312,7 +312,7 @@ LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest,
LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest);
LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest,
- vector<string> *errors);
+ std::vector<string> *errors);
LIBPROTOBUF_EXPORT string UnescapeCEscapeString(const string& src);
// ----------------------------------------------------------------------
diff --git a/src/google/protobuf/stubs/strutil_unittest.cc b/src/google/protobuf/stubs/strutil_unittest.cc
index 5d62fc4a..6bf0f598 100644
--- a/src/google/protobuf/stubs/strutil_unittest.cc
+++ b/src/google/protobuf/stubs/strutil_unittest.cc
@@ -782,7 +782,7 @@ TEST(Base64, EscapeAndUnescape) {
reinterpret_cast<const unsigned char*>(base64_strings[i].plaintext);
int plain_length = strlen(base64_strings[i].plaintext);
int cypher_length = strlen(base64_strings[i].cyphertext);
- vector<char> buffer(cypher_length+1);
+ std::vector<char> buffer(cypher_length+1);
int encode_length = WebSafeBase64Escape(unsigned_plaintext,
plain_length,
&buffer[0],
diff --git a/src/google/protobuf/stubs/time.cc b/src/google/protobuf/stubs/time.cc
index 49c0412c..6def637e 100644
--- a/src/google/protobuf/stubs/time.cc
+++ b/src/google/protobuf/stubs/time.cc
@@ -80,9 +80,9 @@ bool ValidateDateTime(const DateTime& time) {
return false;
}
if (time.month == 2 && IsLeapYear(time.year)) {
- return time.month <= kDaysInMonth[time.month] + 1;
+ return time.day <= kDaysInMonth[time.month] + 1;
} else {
- return time.month <= kDaysInMonth[time.month];
+ return time.day <= kDaysInMonth[time.month];
}
}
diff --git a/src/google/protobuf/stubs/time_test.cc b/src/google/protobuf/stubs/time_test.cc
index 59e9d1c7..53da9480 100644
--- a/src/google/protobuf/stubs/time_test.cc
+++ b/src/google/protobuf/stubs/time_test.cc
@@ -149,6 +149,59 @@ TEST(DateTimeTest, LeapYear) {
CreateTimestamp(2400, 3, 1) - CreateTimestamp(2400, 2, 29));
}
+TEST(DateTimeTest, WrongDays) {
+ int64 seconds;
+ DateTime time;
+ time.hour = 0;
+ time.minute = 0;
+ time.second = 0;
+ time.month = 2;
+
+ // Non-leap year.
+ time.year = 2015;
+ time.day = 29;
+ ASSERT_FALSE(DateTimeToSeconds(time, &seconds));
+
+ // Leap year.
+ time.year = 2016;
+ time.day = 29;
+ ASSERT_TRUE(DateTimeToSeconds(time, &seconds));
+ time.day = 30;
+ ASSERT_FALSE(DateTimeToSeconds(time, &seconds));
+
+ // Non-leap year.
+ time.year = 2100;
+ time.day = 29;
+ ASSERT_FALSE(DateTimeToSeconds(time, &seconds));
+
+ // Leap year.
+ time.year = 2400;
+ time.day = 29;
+ ASSERT_TRUE(DateTimeToSeconds(time, &seconds));
+ time.day = 30;
+ ASSERT_FALSE(DateTimeToSeconds(time, &seconds));
+
+ // Non-february
+ time.year = 2015;
+ time.month = 1;
+ time.day = 0;
+ ASSERT_FALSE(DateTimeToSeconds(time, &seconds));
+ time.day = 1;
+ ASSERT_TRUE(DateTimeToSeconds(time, &seconds));
+ time.day = 31;
+ ASSERT_TRUE(DateTimeToSeconds(time, &seconds));
+ time.day = 32;
+ ASSERT_FALSE(DateTimeToSeconds(time, &seconds));
+
+ // Bad month
+ time.year = 2015;
+ time.month = 0;
+ time.day = 1;
+ ASSERT_FALSE(DateTimeToSeconds(time, &seconds));
+ time.month = 13;
+ ASSERT_FALSE(DateTimeToSeconds(time, &seconds));
+}
+
TEST(DateTimeTest, StringFormat) {
DateTime start, end;
start.year = 1;
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 49c10ace..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 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/testing/googletest.cc b/src/google/protobuf/testing/googletest.cc
index b81d3994..8c89e5af 100644
--- a/src/google/protobuf/testing/googletest.cc
+++ b/src/google/protobuf/testing/googletest.cc
@@ -263,7 +263,7 @@ ScopedMemoryLog::~ScopedMemoryLog() {
active_log_ = NULL;
}
-const vector<string>& ScopedMemoryLog::GetMessages(LogLevel level) {
+const std::vector<string>& ScopedMemoryLog::GetMessages(LogLevel level) {
GOOGLE_CHECK(level == ERROR ||
level == WARNING);
return messages_[level];
diff --git a/src/google/protobuf/testing/googletest.h b/src/google/protobuf/testing/googletest.h
index 2db3bfee..81637486 100644
--- a/src/google/protobuf/testing/googletest.h
+++ b/src/google/protobuf/testing/googletest.h
@@ -83,10 +83,10 @@ class ScopedMemoryLog {
virtual ~ScopedMemoryLog();
// Fetches all messages with the given severity level.
- const vector<string>& GetMessages(LogLevel error);
+ const std::vector<string>& GetMessages(LogLevel error);
private:
- std::map<LogLevel, vector<string> > messages_;
+ std::map<LogLevel, std::vector<string> > messages_;
LogHandler* old_handler_;
static void HandleLog(LogLevel level, const char* filename, int line,
diff --git a/src/google/protobuf/text_format.cc b/src/google/protobuf/text_format.cc
index eed2a768..0965fd7a 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;
}
@@ -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;
@@ -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()) {
@@ -1639,6 +1675,13 @@ class FieldValuePrinterWrapper : public TextFormat::FastFieldValuePrinter {
TextFormat::BaseTextGenerator* generator) const {
generator->PrintString(delegate_->PrintEnum(val, name));
}
+ void PrintFieldName(const Message& message, int field_index, int field_count,
+ const Reflection* reflection,
+ const FieldDescriptor* field,
+ TextFormat::BaseTextGenerator* generator) const {
+ generator->PrintString(delegate_->PrintFieldName(
+ message, reflection, field));
+ }
void PrintFieldName(const Message& message, const Reflection* reflection,
const FieldDescriptor* field,
TextFormat::BaseTextGenerator* generator) const {
@@ -1659,7 +1702,7 @@ class FieldValuePrinterWrapper : public TextFormat::FastFieldValuePrinter {
}
private:
- google::protobuf::scoped_ptr<const TextFormat::FieldValuePrinter> delegate_;
+ std::unique_ptr<const TextFormat::FieldValuePrinter> delegate_;
};
// Our own specialization: for UTF8 escaped strings.
@@ -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..544c37e2 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,143 @@ 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());
+ }
+ }
+ 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 +1165,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 +1312,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 +1377,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 36e3bb36..8e6b5f23 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];
@@ -71,15 +68,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
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 ::google::protobuf::internal::once_flag once;
+ ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
@@ -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() {
@@ -177,9 +170,7 @@ void Timestamp::ArenaDtor(void* object) {
void Timestamp::RegisterArenaDtor(::google::protobuf::Arena* 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,13 +178,10 @@ 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();
}
-Timestamp* Timestamp::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<Timestamp>(arena);
-}
void Timestamp::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Timestamp)
@@ -213,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)) {
@@ -337,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;
}
@@ -415,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 {
@@ -427,5 +412,12 @@ void Timestamp::InternalSwap(Timestamp* other) {
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
+namespace google {
+namespace protobuf {
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Timestamp* Arena::CreateMaybeMessage< ::google::protobuf::Timestamp >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::Timestamp >(arena);
+}
+} // namespace protobuf
+} // namespace google
// @@protoc_insertion_point(global_scope)
diff --git a/src/google/protobuf/timestamp.pb.h b/src/google/protobuf/timestamp.pb.h
index 6c7136e2..f73e75b3 100644
--- a/src/google/protobuf/timestamp.pb.h
+++ b/src/google/protobuf/timestamp.pb.h
@@ -1,8 +1,8 @@
// 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>
@@ -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,6 +54,11 @@ LIBPROTOBUF_EXPORT extern TimestampDefaultTypeInternal _Timestamp_default_instan
} // namespace google
namespace google {
namespace protobuf {
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Timestamp* Arena::CreateMaybeMessage<::google::protobuf::Timestamp>(Arena*);
+} // namespace protobuf
+} // namespace google
+namespace google {
+namespace protobuf {
// ===================================================================
@@ -86,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();
@@ -100,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);
@@ -111,28 +113,33 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
// implements Message ----------------------------------------------
- inline Timestamp* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Timestamp* New() const final {
+ return CreateMaybeMessage<Timestamp>(NULL);
+ }
- Timestamp* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Timestamp* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Timestamp>(arena);
+ }
+ 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);
@@ -148,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 ----------------------------------------------------
@@ -175,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();
};
// ===================================================================
@@ -229,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/timestamp.proto b/src/google/protobuf/timestamp.proto
index 06750ab1..eafb3fa0 100644
--- a/src/google/protobuf/timestamp.proto
+++ b/src/google/protobuf/timestamp.proto
@@ -103,7 +103,9 @@ option objc_class_prefix = "GPB";
// {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.
@@ -114,8 +116,8 @@ option objc_class_prefix = "GPB";
// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
// can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
-// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--)
-// 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.
//
//
message Timestamp {
diff --git a/src/google/protobuf/type.pb.cc b/src/google/protobuf/type.pb.cc
index 92f6589c..130af52a 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];
@@ -237,15 +221,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
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 ::google::protobuf::internal::once_flag once;
+ ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
@@ -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 {
@@ -420,10 +403,6 @@ void Type::InitAsDefaultInstance() {
::google::protobuf::_Type_default_instance_._instance.get_mutable()->source_context_ = const_cast< ::google::protobuf::SourceContext*>(
::google::protobuf::SourceContext::internal_default_instance());
}
-void Type::_slow_mutable_source_context() {
- source_context_ = ::google::protobuf::Arena::Create< ::google::protobuf::SourceContext >(
- GetArenaNoVirtual());
-}
void Type::unsafe_arena_set_allocated_source_context(
::google::protobuf::SourceContext* source_context) {
if (GetArenaNoVirtual() == NULL) {
@@ -454,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)
}
@@ -466,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)
@@ -476,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) {
@@ -498,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() {
@@ -519,9 +495,7 @@ void Type::ArenaDtor(void* object) {
void Type::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -529,13 +503,10 @@ 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();
}
-Type* Type::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<Type>(arena);
-}
void Type::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Type)
@@ -561,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)) {
@@ -585,7 +556,8 @@ bool Type::MergePartialFromCodedStream(
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_fields()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_fields()));
} else {
goto handle_unusual;
}
@@ -613,7 +585,8 @@ bool Type::MergePartialFromCodedStream(
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_options()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_options()));
} else {
goto handle_unusual;
}
@@ -687,7 +660,9 @@ void Type::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->fields_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->fields(static_cast<int>(i)), output);
+ 2,
+ this->fields(static_cast<int>(i)),
+ output);
}
// repeated string oneofs = 3;
@@ -704,13 +679,15 @@ void Type::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 4, this->options(static_cast<int>(i)), output);
+ 4,
+ this->options(static_cast<int>(i)),
+ output);
}
// .google.protobuf.SourceContext source_context = 5;
if (this->has_source_context()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 5, *this->source_context_, output);
+ 5, this->_internal_source_context(), output);
}
// .google.protobuf.Syntax syntax = 6;
@@ -774,7 +751,7 @@ void Type::SerializeWithCachedSizes(
if (this->has_source_context()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 5, *this->source_context_, deterministic, target);
+ 5, this->_internal_source_context(), deterministic, target);
}
// .google.protobuf.Syntax syntax = 6;
@@ -841,7 +818,7 @@ size_t Type::ByteSizeLong() const {
if (this->has_source_context()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
- *this->source_context_);
+ *source_context_);
}
// .google.protobuf.Syntax syntax = 6;
@@ -851,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;
}
@@ -932,14 +907,14 @@ void Type::UnsafeArenaSwap(Type* other) {
}
void Type::InternalSwap(Type* other) {
using std::swap;
- fields_.InternalSwap(&other->fields_);
- oneofs_.InternalSwap(&other->oneofs_);
- options_.InternalSwap(&other->options_);
- name_.Swap(&other->name_);
+ CastToBase(&fields_)->InternalSwap(CastToBase(&other->fields_));
+ oneofs_.InternalSwap(CastToBase(&other->oneofs_));
+ CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
+ name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
swap(source_context_, other->source_context_);
swap(syntax_, other->syntax_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Type::GetMetadata() const {
@@ -967,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)
}
@@ -977,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)
@@ -985,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) {
@@ -1022,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() {
@@ -1045,9 +1017,7 @@ void Field::ArenaDtor(void* object) {
void Field::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -1055,13 +1025,10 @@ 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();
}
-Field* Field::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<Field>(arena);
-}
void Field::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Field)
@@ -1086,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)) {
@@ -1198,7 +1165,8 @@ bool Field::MergePartialFromCodedStream(
case 9: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(74u /* 74 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_options()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_options()));
} else {
goto handle_unusual;
}
@@ -1314,7 +1282,9 @@ void Field::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 9, this->options(static_cast<int>(i)), output);
+ 9,
+ this->options(static_cast<int>(i)),
+ output);
}
// string json_name = 10;
@@ -1518,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,18 +1583,21 @@ void Field::UnsafeArenaSwap(Field* other) {
}
void Field::InternalSwap(Field* other) {
using std::swap;
- options_.InternalSwap(&other->options_);
- name_.Swap(&other->name_);
- type_url_.Swap(&other->type_url_);
- json_name_.Swap(&other->json_name_);
- default_value_.Swap(&other->default_value_);
+ CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
+ 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 {
@@ -1641,10 +1612,6 @@ void Enum::InitAsDefaultInstance() {
::google::protobuf::_Enum_default_instance_._instance.get_mutable()->source_context_ = const_cast< ::google::protobuf::SourceContext*>(
::google::protobuf::SourceContext::internal_default_instance());
}
-void Enum::_slow_mutable_source_context() {
- source_context_ = ::google::protobuf::Arena::Create< ::google::protobuf::SourceContext >(
- GetArenaNoVirtual());
-}
void Enum::unsafe_arena_set_allocated_source_context(
::google::protobuf::SourceContext* source_context) {
if (GetArenaNoVirtual() == NULL) {
@@ -1674,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)
}
@@ -1685,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)
@@ -1694,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) {
@@ -1716,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() {
@@ -1737,9 +1701,7 @@ void Enum::ArenaDtor(void* object) {
void Enum::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -1747,13 +1709,10 @@ 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();
}
-Enum* Enum::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<Enum>(arena);
-}
void Enum::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Enum)
@@ -1778,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)) {
@@ -1802,7 +1761,8 @@ bool Enum::MergePartialFromCodedStream(
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_enumvalue()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_enumvalue()));
} else {
goto handle_unusual;
}
@@ -1813,7 +1773,8 @@ bool Enum::MergePartialFromCodedStream(
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_options()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_options()));
} else {
goto handle_unusual;
}
@@ -1887,20 +1848,24 @@ void Enum::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->enumvalue_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->enumvalue(static_cast<int>(i)), output);
+ 2,
+ this->enumvalue(static_cast<int>(i)),
+ output);
}
// repeated .google.protobuf.Option options = 3;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, this->options(static_cast<int>(i)), output);
+ 3,
+ this->options(static_cast<int>(i)),
+ output);
}
// .google.protobuf.SourceContext source_context = 4;
if (this->has_source_context()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 4, *this->source_context_, output);
+ 4, this->_internal_source_context(), output);
}
// .google.protobuf.Syntax syntax = 5;
@@ -1954,7 +1919,7 @@ void Enum::SerializeWithCachedSizes(
if (this->has_source_context()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 4, *this->source_context_, deterministic, target);
+ 4, this->_internal_source_context(), deterministic, target);
}
// .google.protobuf.Syntax syntax = 5;
@@ -2013,7 +1978,7 @@ size_t Enum::ByteSizeLong() const {
if (this->has_source_context()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
- *this->source_context_);
+ *source_context_);
}
// .google.protobuf.Syntax syntax = 5;
@@ -2023,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,13 +2066,13 @@ void Enum::UnsafeArenaSwap(Enum* other) {
}
void Enum::InternalSwap(Enum* other) {
using std::swap;
- enumvalue_.InternalSwap(&other->enumvalue_);
- options_.InternalSwap(&other->options_);
- name_.Swap(&other->name_);
+ CastToBase(&enumvalue_)->InternalSwap(CastToBase(&other->enumvalue_));
+ CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
+ name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
swap(source_context_, other->source_context_);
swap(syntax_, other->syntax_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Enum::GetMetadata() const {
@@ -2130,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)
}
@@ -2140,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)
@@ -2148,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) {
@@ -2163,7 +2124,6 @@ EnumValue::EnumValue(const EnumValue& from)
void EnumValue::SharedCtor() {
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
number_ = 0;
- _cached_size_ = 0;
}
EnumValue::~EnumValue() {
@@ -2183,9 +2143,7 @@ void EnumValue::ArenaDtor(void* object) {
void EnumValue::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -2193,13 +2151,10 @@ 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();
}
-EnumValue* EnumValue::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<EnumValue>(arena);
-}
void EnumValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.EnumValue)
@@ -2219,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)) {
@@ -2257,7 +2212,8 @@ bool EnumValue::MergePartialFromCodedStream(
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_options()));
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, add_options()));
} else {
goto handle_unusual;
}
@@ -2309,7 +2265,9 @@ void EnumValue::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, this->options(static_cast<int>(i)), output);
+ 3,
+ this->options(static_cast<int>(i)),
+ output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
@@ -2393,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;
}
@@ -2469,11 +2425,11 @@ void EnumValue::UnsafeArenaSwap(EnumValue* other) {
}
void EnumValue::InternalSwap(EnumValue* other) {
using std::swap;
- options_.InternalSwap(&other->options_);
- name_.Swap(&other->name_);
+ CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
+ name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
swap(number_, other->number_);
_internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata EnumValue::GetMetadata() const {
@@ -2488,10 +2444,6 @@ void Option::InitAsDefaultInstance() {
::google::protobuf::_Option_default_instance_._instance.get_mutable()->value_ = const_cast< ::google::protobuf::Any*>(
::google::protobuf::Any::internal_default_instance());
}
-void Option::_slow_mutable_value() {
- value_ = ::google::protobuf::Arena::Create< ::google::protobuf::Any >(
- GetArenaNoVirtual());
-}
void Option::unsafe_arena_set_allocated_value(
::google::protobuf::Any* value) {
if (GetArenaNoVirtual() == NULL) {
@@ -2518,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) {
@@ -2553,7 +2503,6 @@ Option::Option(const Option& from)
void Option::SharedCtor() {
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_ = NULL;
- _cached_size_ = 0;
}
Option::~Option() {
@@ -2574,9 +2523,7 @@ void Option::ArenaDtor(void* object) {
void Option::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -2584,13 +2531,10 @@ 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();
}
-Option* Option::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<Option>(arena);
-}
void Option::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Option)
@@ -2612,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)) {
@@ -2683,7 +2627,7 @@ void Option::SerializeWithCachedSizes(
// .google.protobuf.Any value = 2;
if (this->has_value()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, *this->value_, output);
+ 2, this->_internal_value(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
@@ -2715,7 +2659,7 @@ void Option::SerializeWithCachedSizes(
if (this->has_value()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 2, *this->value_, deterministic, target);
+ 2, this->_internal_value(), deterministic, target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
@@ -2746,13 +2690,11 @@ size_t Option::ByteSizeLong() const {
if (this->has_value()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
- *this->value_);
+ *value_);
}
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;
}
@@ -2825,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 {
@@ -2840,5 +2782,24 @@ void Option::InternalSwap(Option* other) {
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
+namespace google {
+namespace protobuf {
+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::CreateMaybeMessage< ::google::protobuf::Field >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::Field >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Enum* Arena::CreateMaybeMessage< ::google::protobuf::Enum >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::Enum >(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::CreateMaybeMessage< ::google::protobuf::Option >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::Option >(arena);
+}
+} // namespace protobuf
+} // namespace google
// @@protoc_insertion_point(global_scope)
diff --git a/src/google/protobuf/type.pb.h b/src/google/protobuf/type.pb.h
index 8ee74a12..69af6c2e 100644
--- a/src/google/protobuf/type.pb.h
+++ b/src/google/protobuf/type.pb.h
@@ -1,8 +1,8 @@
// 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>
@@ -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,6 +69,15 @@ LIBPROTOBUF_EXPORT extern TypeDefaultTypeInternal _Type_default_instance_;
} // namespace google
namespace google {
namespace protobuf {
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Enum* Arena::CreateMaybeMessage<::google::protobuf::Enum>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValue* Arena::CreateMaybeMessage<::google::protobuf::EnumValue>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Field* Arena::CreateMaybeMessage<::google::protobuf::Field>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Option* Arena::CreateMaybeMessage<::google::protobuf::Option>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Type* Arena::CreateMaybeMessage<::google::protobuf::Type>(Arena*);
+} // namespace protobuf
+} // namespace google
+namespace google {
+namespace protobuf {
enum Field_Kind {
Field_Kind_TYPE_UNKNOWN = 0,
@@ -195,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();
@@ -209,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);
@@ -220,28 +214,33 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
// implements Message ----------------------------------------------
- inline Type* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Type* New() const final {
+ return CreateMaybeMessage<Type>(NULL);
+ }
- Type* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Type* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Type>(arena);
+ }
+ 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);
@@ -257,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 ----------------------------------------------------
@@ -267,11 +266,11 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
int fields_size() const;
void clear_fields();
static const int kFieldsFieldNumber = 2;
- const ::google::protobuf::Field& fields(int index) const;
::google::protobuf::Field* mutable_fields(int index);
- ::google::protobuf::Field* add_fields();
::google::protobuf::RepeatedPtrField< ::google::protobuf::Field >*
mutable_fields();
+ const ::google::protobuf::Field& fields(int index) const;
+ ::google::protobuf::Field* add_fields();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Field >&
fields() const;
@@ -301,11 +300,11 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
int options_size() const;
void clear_options();
static const int kOptionsFieldNumber = 4;
- const ::google::protobuf::Option& options(int index) const;
::google::protobuf::Option* mutable_options(int index);
- ::google::protobuf::Option* add_options();
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
mutable_options();
+ const ::google::protobuf::Option& options(int index) const;
+ ::google::protobuf::Option* add_options();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
options() const;
@@ -337,7 +336,7 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
void clear_source_context();
static const int kSourceContextFieldNumber = 5;
private:
- void _slow_mutable_source_context();
+ const ::google::protobuf::SourceContext& _internal_source_context() const;
public:
const ::google::protobuf::SourceContext& source_context() const;
::google::protobuf::SourceContext* release_source_context();
@@ -366,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();
};
// -------------------------------------------------------------------
@@ -398,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();
@@ -412,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);
@@ -423,28 +421,33 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
// implements Message ----------------------------------------------
- inline Field* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Field* New() const final {
+ return CreateMaybeMessage<Field>(NULL);
+ }
- Field* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Field* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Field>(arena);
+ }
+ 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);
@@ -460,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 ----------------------------------------------------
@@ -560,11 +563,11 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
int options_size() const;
void clear_options();
static const int kOptionsFieldNumber = 9;
- const ::google::protobuf::Option& options(int index) const;
::google::protobuf::Option* mutable_options(int index);
- ::google::protobuf::Option* add_options();
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
mutable_options();
+ const ::google::protobuf::Option& options(int index) const;
+ ::google::protobuf::Option* add_options();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
options() const;
@@ -707,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();
};
// -------------------------------------------------------------------
@@ -739,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();
@@ -753,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);
@@ -764,28 +766,33 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
// implements Message ----------------------------------------------
- inline Enum* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Enum* New() const final {
+ return CreateMaybeMessage<Enum>(NULL);
+ }
- Enum* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Enum* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Enum>(arena);
+ }
+ 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);
@@ -801,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 ----------------------------------------------------
@@ -811,11 +818,11 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
int enumvalue_size() const;
void clear_enumvalue();
static const int kEnumvalueFieldNumber = 2;
- const ::google::protobuf::EnumValue& enumvalue(int index) const;
::google::protobuf::EnumValue* mutable_enumvalue(int index);
- ::google::protobuf::EnumValue* add_enumvalue();
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValue >*
mutable_enumvalue();
+ const ::google::protobuf::EnumValue& enumvalue(int index) const;
+ ::google::protobuf::EnumValue* add_enumvalue();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValue >&
enumvalue() const;
@@ -823,11 +830,11 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
int options_size() const;
void clear_options();
static const int kOptionsFieldNumber = 3;
- const ::google::protobuf::Option& options(int index) const;
::google::protobuf::Option* mutable_options(int index);
- ::google::protobuf::Option* add_options();
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
mutable_options();
+ const ::google::protobuf::Option& options(int index) const;
+ ::google::protobuf::Option* add_options();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
options() const;
@@ -859,7 +866,7 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
void clear_source_context();
static const int kSourceContextFieldNumber = 4;
private:
- void _slow_mutable_source_context();
+ const ::google::protobuf::SourceContext& _internal_source_context() const;
public:
const ::google::protobuf::SourceContext& source_context() const;
::google::protobuf::SourceContext* release_source_context();
@@ -887,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();
};
// -------------------------------------------------------------------
@@ -919,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();
@@ -933,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);
@@ -944,28 +950,33 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
// implements Message ----------------------------------------------
- inline EnumValue* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline EnumValue* New() const final {
+ return CreateMaybeMessage<EnumValue>(NULL);
+ }
- EnumValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ EnumValue* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<EnumValue>(arena);
+ }
+ 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);
@@ -981,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 ----------------------------------------------------
@@ -991,11 +1002,11 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
int options_size() const;
void clear_options();
static const int kOptionsFieldNumber = 3;
- const ::google::protobuf::Option& options(int index) const;
::google::protobuf::Option* mutable_options(int index);
- ::google::protobuf::Option* add_options();
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
mutable_options();
+ const ::google::protobuf::Option& options(int index) const;
+ ::google::protobuf::Option* add_options();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
options() const;
@@ -1038,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();
};
// -------------------------------------------------------------------
@@ -1070,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();
@@ -1084,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);
@@ -1095,28 +1105,33 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
// implements Message ----------------------------------------------
- inline Option* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Option* New() const final {
+ return CreateMaybeMessage<Option>(NULL);
+ }
- Option* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Option* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Option>(arena);
+ }
+ 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);
@@ -1132,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 ----------------------------------------------------
@@ -1166,7 +1181,7 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
void clear_value();
static const int kValueFieldNumber = 2;
private:
- void _slow_mutable_value();
+ const ::google::protobuf::Any& _internal_value() const;
public:
const ::google::protobuf::Any& value() const;
::google::protobuf::Any* release_value();
@@ -1185,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();
};
// ===================================================================
@@ -1282,23 +1296,23 @@ inline int Type::fields_size() const {
inline void Type::clear_fields() {
fields_.Clear();
}
-inline const ::google::protobuf::Field& Type::fields(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Type.fields)
- return fields_.Get(index);
-}
inline ::google::protobuf::Field* Type::mutable_fields(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.Type.fields)
return fields_.Mutable(index);
}
-inline ::google::protobuf::Field* Type::add_fields() {
- // @@protoc_insertion_point(field_add:google.protobuf.Type.fields)
- return fields_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Field >*
Type::mutable_fields() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.Type.fields)
return &fields_;
}
+inline const ::google::protobuf::Field& Type::fields(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.Type.fields)
+ return fields_.Get(index);
+}
+inline ::google::protobuf::Field* Type::add_fields() {
+ // @@protoc_insertion_point(field_add:google.protobuf.Type.fields)
+ return fields_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Field >&
Type::fields() const {
// @@protoc_insertion_point(field_list:google.protobuf.Type.fields)
@@ -1381,23 +1395,23 @@ inline int Type::options_size() const {
inline void Type::clear_options() {
options_.Clear();
}
-inline const ::google::protobuf::Option& Type::options(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Type.options)
- return options_.Get(index);
-}
inline ::google::protobuf::Option* Type::mutable_options(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.Type.options)
return options_.Mutable(index);
}
-inline ::google::protobuf::Option* Type::add_options() {
- // @@protoc_insertion_point(field_add:google.protobuf.Type.options)
- return options_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
Type::mutable_options() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.Type.options)
return &options_;
}
+inline const ::google::protobuf::Option& Type::options(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.Type.options)
+ return options_.Get(index);
+}
+inline ::google::protobuf::Option* Type::add_options() {
+ // @@protoc_insertion_point(field_add:google.protobuf.Type.options)
+ return options_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
Type::options() const {
// @@protoc_insertion_point(field_list:google.protobuf.Type.options)
@@ -1408,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)
@@ -1419,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;
@@ -1434,7 +1451,8 @@ inline ::google::protobuf::SourceContext* Type::unsafe_arena_release_source_cont
inline ::google::protobuf::SourceContext* Type::mutable_source_context() {
if (source_context_ == NULL) {
- _slow_mutable_source_context();
+ auto* p = CreateMaybeMessage<::google::protobuf::SourceContext>(GetArenaNoVirtual());
+ source_context_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Type.source_context)
return source_context_;
@@ -1703,23 +1721,23 @@ inline int Field::options_size() const {
inline void Field::clear_options() {
options_.Clear();
}
-inline const ::google::protobuf::Option& Field::options(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Field.options)
- return options_.Get(index);
-}
inline ::google::protobuf::Option* Field::mutable_options(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.Field.options)
return options_.Mutable(index);
}
-inline ::google::protobuf::Option* Field::add_options() {
- // @@protoc_insertion_point(field_add:google.protobuf.Field.options)
- return options_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
Field::mutable_options() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.Field.options)
return &options_;
}
+inline const ::google::protobuf::Option& Field::options(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.Field.options)
+ return options_.Get(index);
+}
+inline ::google::protobuf::Option* Field::add_options() {
+ // @@protoc_insertion_point(field_add:google.protobuf.Field.options)
+ return options_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
Field::options() const {
// @@protoc_insertion_point(field_list:google.protobuf.Field.options)
@@ -1962,23 +1980,23 @@ inline int Enum::enumvalue_size() const {
inline void Enum::clear_enumvalue() {
enumvalue_.Clear();
}
-inline const ::google::protobuf::EnumValue& Enum::enumvalue(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Enum.enumvalue)
- return enumvalue_.Get(index);
-}
inline ::google::protobuf::EnumValue* Enum::mutable_enumvalue(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.Enum.enumvalue)
return enumvalue_.Mutable(index);
}
-inline ::google::protobuf::EnumValue* Enum::add_enumvalue() {
- // @@protoc_insertion_point(field_add:google.protobuf.Enum.enumvalue)
- return enumvalue_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValue >*
Enum::mutable_enumvalue() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.Enum.enumvalue)
return &enumvalue_;
}
+inline const ::google::protobuf::EnumValue& Enum::enumvalue(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.Enum.enumvalue)
+ return enumvalue_.Get(index);
+}
+inline ::google::protobuf::EnumValue* Enum::add_enumvalue() {
+ // @@protoc_insertion_point(field_add:google.protobuf.Enum.enumvalue)
+ return enumvalue_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValue >&
Enum::enumvalue() const {
// @@protoc_insertion_point(field_list:google.protobuf.Enum.enumvalue)
@@ -1992,23 +2010,23 @@ inline int Enum::options_size() const {
inline void Enum::clear_options() {
options_.Clear();
}
-inline const ::google::protobuf::Option& Enum::options(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Enum.options)
- return options_.Get(index);
-}
inline ::google::protobuf::Option* Enum::mutable_options(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.Enum.options)
return options_.Mutable(index);
}
-inline ::google::protobuf::Option* Enum::add_options() {
- // @@protoc_insertion_point(field_add:google.protobuf.Enum.options)
- return options_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
Enum::mutable_options() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.Enum.options)
return &options_;
}
+inline const ::google::protobuf::Option& Enum::options(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.Enum.options)
+ return options_.Get(index);
+}
+inline ::google::protobuf::Option* Enum::add_options() {
+ // @@protoc_insertion_point(field_add:google.protobuf.Enum.options)
+ return options_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
Enum::options() const {
// @@protoc_insertion_point(field_list:google.protobuf.Enum.options)
@@ -2019,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)
@@ -2030,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;
@@ -2045,7 +2066,8 @@ inline ::google::protobuf::SourceContext* Enum::unsafe_arena_release_source_cont
inline ::google::protobuf::SourceContext* Enum::mutable_source_context() {
if (source_context_ == NULL) {
- _slow_mutable_source_context();
+ auto* p = CreateMaybeMessage<::google::protobuf::SourceContext>(GetArenaNoVirtual());
+ source_context_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Enum.source_context)
return source_context_;
@@ -2183,23 +2205,23 @@ inline int EnumValue::options_size() const {
inline void EnumValue::clear_options() {
options_.Clear();
}
-inline const ::google::protobuf::Option& EnumValue::options(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumValue.options)
- return options_.Get(index);
-}
inline ::google::protobuf::Option* EnumValue::mutable_options(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumValue.options)
return options_.Mutable(index);
}
-inline ::google::protobuf::Option* EnumValue::add_options() {
- // @@protoc_insertion_point(field_add:google.protobuf.EnumValue.options)
- return options_.Add();
-}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
EnumValue::mutable_options() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumValue.options)
return &options_;
}
+inline const ::google::protobuf::Option& EnumValue::options(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.EnumValue.options)
+ return options_.Get(index);
+}
+inline ::google::protobuf::Option* EnumValue::add_options() {
+ // @@protoc_insertion_point(field_add:google.protobuf.EnumValue.options)
+ return options_.Add();
+}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
EnumValue::options() const {
// @@protoc_insertion_point(field_list:google.protobuf.EnumValue.options)
@@ -2289,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)
@@ -2300,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;
@@ -2315,7 +2340,8 @@ inline ::google::protobuf::Any* Option::unsafe_arena_release_value() {
inline ::google::protobuf::Any* Option::mutable_value() {
if (value_ == NULL) {
- _slow_mutable_value();
+ auto* p = CreateMaybeMessage<::google::protobuf::Any>(GetArenaNoVirtual());
+ value_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Option.value)
return value_;
@@ -2359,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();
@@ -2380,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 45a0edad..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";
@@ -189,6 +191,9 @@ message NestedTestAllTypes {
message TestDeprecatedFields {
optional int32 deprecated_int32 = 1 [deprecated=true];
+ oneof oneof_fields {
+ int32 deprecated_int32_in_oneof = 2 [deprecated=true];
+ }
}
message TestDeprecatedMessage {
@@ -330,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
@@ -339,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
@@ -551,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"];
@@ -943,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_import_proto3.proto b/src/google/protobuf/unittest_import_proto3.proto
deleted file mode 100644
index 59673eaf..00000000
--- a/src/google/protobuf/unittest_import_proto3.proto
+++ /dev/null
@@ -1,68 +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)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-//
-// A proto file which is imported by unittest_proto3.proto to test importing.
-
-syntax = "proto3";
-
-// We don't put this in a package within proto2 because we need to make sure
-// that the generated code doesn't depend on being in the proto2 namespace.
-// In test_util.h we do
-// "using namespace unittest_import = protobuf_unittest_import".
-package protobuf_unittest_import;
-
-option optimize_for = SPEED;
-option cc_enable_arenas = true;
-
-// Exercise the java_package option.
-option java_package = "com.google.protobuf.test";
-option csharp_namespace = "Google.Protobuf.TestProtos";
-
-// Do not set a java_outer_classname here to verify that Proto2 works without
-// one.
-
-// Test public import
-import public "google/protobuf/unittest_import_public_proto3.proto";
-
-message ImportMessage {
- int32 d = 1;
-}
-
-enum ImportEnum {
- IMPORT_ENUM_UNSPECIFIED = 0;
- IMPORT_FOO = 7;
- IMPORT_BAR = 8;
- IMPORT_BAZ = 9;
-}
-
diff --git a/src/google/protobuf/unittest_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/unittest_lite_imports_nonlite.proto b/src/google/protobuf/unittest_lite_imports_nonlite.proto
index 132d6a82..8a470160 100644
--- a/src/google/protobuf/unittest_lite_imports_nonlite.proto
+++ b/src/google/protobuf/unittest_lite_imports_nonlite.proto
@@ -41,4 +41,7 @@ option optimize_for = LITE_RUNTIME;
message TestLiteImportsNonlite {
optional TestAllTypes message = 1;
+
+ // Verifies that transitive required fields generates valid code.
+ optional TestRequired message_with_required = 2;
}
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/delimited_message_util.cc b/src/google/protobuf/util/delimited_message_util.cc
index 16378782..3ba930e7 100644
--- a/src/google/protobuf/util/delimited_message_util.cc
+++ b/src/google/protobuf/util/delimited_message_util.cc
@@ -12,7 +12,7 @@ bool SerializeDelimitedToFileDescriptor(const MessageLite& message, int file_des
return SerializeDelimitedToZeroCopyStream(message, &output);
}
-bool SerializeDelimitedToOstream(const MessageLite& message, ostream* output) {
+bool SerializeDelimitedToOstream(const MessageLite& message, std::ostream* output) {
{
io::OstreamOutputStream zero_copy_output(output);
if (!SerializeDelimitedToZeroCopyStream(message, &zero_copy_output)) return false;
diff --git a/src/google/protobuf/util/delimited_message_util.h b/src/google/protobuf/util/delimited_message_util.h
index 302d4781..e8a7204a 100644
--- a/src/google/protobuf/util/delimited_message_util.h
+++ b/src/google/protobuf/util/delimited_message_util.h
@@ -32,7 +32,7 @@ namespace util {
// underlying source, so instead you must keep using the same stream object.
bool LIBPROTOBUF_EXPORT SerializeDelimitedToFileDescriptor(const MessageLite& message, int file_descriptor);
-bool LIBPROTOBUF_EXPORT SerializeDelimitedToOstream(const MessageLite& message, ostream* output);
+bool LIBPROTOBUF_EXPORT SerializeDelimitedToOstream(const MessageLite& message, std::ostream* output);
// Read a single size-delimited message from the given stream. Delimited
// format allows a single file or stream to contain multiple messages,
diff --git a/src/google/protobuf/util/field_comparator.cc b/src/google/protobuf/util/field_comparator.cc
index a1a56ee6..86ddf06a 100644
--- a/src/google/protobuf/util/field_comparator.cc
+++ b/src/google/protobuf/util/field_comparator.cc
@@ -36,6 +36,7 @@
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
+#include <google/protobuf/util/message_differencer.h>
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/mathlimits.h>
#include <google/protobuf/stubs/mathutil.h>
@@ -130,6 +131,15 @@ FieldComparator::ComparisonResult DefaultFieldComparator::Compare(
}
}
+bool DefaultFieldComparator::Compare(
+ MessageDifferencer* differencer,
+ const Message& message1,
+ const Message& message2,
+ const google::protobuf::util::FieldContext* field_context) {
+ return differencer->Compare(
+ message1, message2, field_context->parent_fields());
+}
+
void DefaultFieldComparator::SetDefaultFractionAndMargin(double fraction,
double margin) {
default_tolerance_ = Tolerance(fraction, margin);
diff --git a/src/google/protobuf/util/field_comparator.h b/src/google/protobuf/util/field_comparator.h
index 26a7ba4d..27ef4c77 100644
--- a/src/google/protobuf/util/field_comparator.h
+++ b/src/google/protobuf/util/field_comparator.h
@@ -35,6 +35,7 @@
#include <map>
#include <string>
+#include <vector>
#include <google/protobuf/stubs/common.h>
@@ -48,6 +49,7 @@ class FieldDescriptor;
namespace util {
class FieldContext;
+class MessageDifferencer;
// Base class specifying the interface for comparing protocol buffer fields.
// Regular users should consider using or subclassing DefaultFieldComparator
@@ -153,6 +155,15 @@ class LIBPROTOBUF_EXPORT DefaultFieldComparator : public FieldComparator {
// REQUIRES: float_comparison_ == APPROXIMATE
void SetDefaultFractionAndMargin(double fraction, double margin);
+ protected:
+ // Compare using the provided message_differencer. For example, a subclass can
+ // use this method to compare some field in a certain way using the same
+ // message_differencer instance and the field context.
+ bool Compare(MessageDifferencer* differencer,
+ const google::protobuf::Message& message1,
+ const google::protobuf::Message& message2,
+ const google::protobuf::util::FieldContext* field_context);
+
private:
// Defines the tolerance for floating point comparison (fraction and margin).
struct Tolerance {
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 01642c6f..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;
@@ -94,6 +94,13 @@ class LIBPROTOBUF_EXPORT FieldMaskUtil {
// Creates a FieldMask with all fields of type T. This FieldMask only
// contains fields of T but not any sub-message fields.
template <typename T>
+ static FieldMask GetFieldMaskForAllFields() {
+ FieldMask out;
+ InternalGetFieldMaskForAllFields(T::descriptor(), &out);
+ return out;
+ }
+ template <typename T>
+ PROTOBUF_RUNTIME_DEPRECATED("Use *out = GetFieldMaskForAllFields() instead")
static void GetFieldMaskForAllFields(FieldMask* out) {
InternalGetFieldMaskForAllFields(T::descriptor(), out);
}
@@ -122,6 +129,8 @@ class LIBPROTOBUF_EXPORT FieldMaskUtil {
// Returns true if path is covered by the given FieldMask. Note that path
// "foo.bar" covers all paths like "foo.bar.baz", "foo.bar.quz.x", etc.
+ // Also note that parent paths are not covered by explicit child path, i.e.
+ // "foo.bar" does NOT cover "foo", even if "bar" is the only child.
static bool IsPathInFieldMask(StringPiece path, const FieldMask& mask);
class MergeOptions;
diff --git a/src/google/protobuf/util/field_mask_util_test.cc b/src/google/protobuf/util/field_mask_util_test.cc
index 7939f733..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) {
@@ -206,12 +206,12 @@ TEST(FieldMaskUtilTest, TestIsValidFieldMask) {
TEST(FieldMaskUtilTest, TestGetFieldMaskForAllFields) {
FieldMask mask;
- FieldMaskUtil::GetFieldMaskForAllFields<TestAllTypes::NestedMessage>(&mask);
+ mask = FieldMaskUtil::GetFieldMaskForAllFields<TestAllTypes::NestedMessage>();
EXPECT_EQ(1, mask.paths_size());
EXPECT_TRUE(FieldMaskUtil::IsPathInFieldMask("bb", mask));
- FieldMaskUtil::GetFieldMaskForAllFields<TestAllTypes>(&mask);
- EXPECT_EQ(76, mask.paths_size());
+ mask = FieldMaskUtil::GetFieldMaskForAllFields<TestAllTypes>();
+ EXPECT_EQ(75, mask.paths_size());
EXPECT_TRUE(FieldMaskUtil::IsPathInFieldMask("optional_int32", mask));
EXPECT_TRUE(FieldMaskUtil::IsPathInFieldMask("optional_int64", mask));
EXPECT_TRUE(FieldMaskUtil::IsPathInFieldMask("optional_uint32", mask));
@@ -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..6e71f9c8 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,
@@ -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..a19bd3f7 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>
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_escaping.h b/src/google/protobuf/util/internal/json_escaping.h
index 9b8b2afd..5495c57f 100644
--- a/src/google/protobuf/util/internal/json_escaping.h
+++ b/src/google/protobuf/util/internal/json_escaping.h
@@ -28,8 +28,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#ifndef NET_PROTO2_UTIL_CONVERTER_STRINGS_JSON_ESCAPING_H_
-#define NET_PROTO2_UTIL_CONVERTER_STRINGS_JSON_ESCAPING_H_
+#ifndef GOOGLE_PROTOBUF_UTIL_INTERNAL__JSON_ESCAPING_H__
+#define GOOGLE_PROTOBUF_UTIL_INTERNAL__JSON_ESCAPING_H__
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/bytestream.h>
@@ -86,6 +86,6 @@ class JsonEscaping {
} // namespace converter
} // namespace util
} // namespace protobuf
-} // namespace google
-#endif // NET_PROTO2_UTIL_CONVERTER_STRINGS_JSON_ESCAPING_H_
+} // namespace google
+#endif // GOOGLE_PROTOBUF_UTIL_INTERNAL__JSON_ESCAPING_H__
diff --git a/src/google/protobuf/util/internal/json_objectwriter.cc b/src/google/protobuf/util/internal/json_objectwriter.cc
index 6e4edd88..a431177a 100644
--- a/src/google/protobuf/util/internal/json_objectwriter.cc
+++ b/src/google/protobuf/util/internal/json_objectwriter.cc
@@ -57,7 +57,7 @@ JsonObjectWriter::~JsonObjectWriter() {
JsonObjectWriter* JsonObjectWriter::StartObject(StringPiece name) {
WritePrefix(name);
WriteChar('{');
- Push();
+ PushObject();
return this;
}
@@ -71,7 +71,7 @@ JsonObjectWriter* JsonObjectWriter::EndObject() {
JsonObjectWriter* JsonObjectWriter::StartList(StringPiece name) {
WritePrefix(name);
WriteChar('[');
- Push();
+ PushArray();
return this;
}
@@ -172,8 +172,7 @@ void JsonObjectWriter::WritePrefix(StringPiece name) {
bool not_first = !element()->is_first();
if (not_first) WriteChar(',');
if (not_first || !element()->is_root()) NewLine();
- bool empty_key_ok = GetAndResetEmptyKeyOk();
- if (!name.empty() || empty_key_ok) {
+ if (!name.empty() || element()->is_json_object()) {
WriteChar('"');
if (!name.empty()) {
ArrayByteSource source(name);
@@ -184,12 +183,6 @@ void JsonObjectWriter::WritePrefix(StringPiece name) {
}
}
-bool JsonObjectWriter::GetAndResetEmptyKeyOk() {
- bool retval = empty_name_ok_for_next_key_;
- empty_name_ok_for_next_key_ = false;
- return retval;
-}
-
} // namespace converter
} // namespace util
} // namespace protobuf
diff --git a/src/google/protobuf/util/internal/json_objectwriter.h b/src/google/protobuf/util/internal/json_objectwriter.h
index 31edc292..81644dab 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,12 +86,11 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
public:
JsonObjectWriter(StringPiece indent_string,
google::protobuf::io::CodedOutputStream* out)
- : element_(new Element(NULL)),
+ : element_(new Element(/*parent=*/nullptr, /*is_json_object=*/false)),
stream_(out),
sink_(out),
indent_string_(indent_string.ToString()),
- use_websafe_base64_for_bytes_(false),
- empty_name_ok_for_next_key_(false) {}
+ use_websafe_base64_for_bytes_(false) {}
virtual ~JsonObjectWriter();
// ObjectWriter methods.
@@ -118,17 +114,13 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
use_websafe_base64_for_bytes_ = value;
}
- // Whether empty strings should be rendered for the next JSON key. This
- // setting is only valid until the next key is rendered, after which it gets
- // reset to false.
- virtual void empty_name_ok_for_next_key() {
- empty_name_ok_for_next_key_ = true;
- }
-
protected:
class LIBPROTOBUF_EXPORT Element : public BaseElement {
public:
- explicit Element(Element* parent) : BaseElement(parent), is_first_(true) {}
+ Element(Element* parent, bool is_json_object)
+ : BaseElement(parent),
+ is_first_(true),
+ is_json_object_(is_json_object) {}
// Called before each field of the Element is to be processed.
// Returns true if this is the first call (processing the first field).
@@ -140,8 +132,13 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
return false;
}
+ // Whether we are currently renderring inside a JSON object (i.e., between
+ // StartObject() and EndObject()).
+ bool is_json_object() const { return is_json_object_; }
+
private:
bool is_first_;
+ bool is_json_object_;
GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(Element);
};
@@ -175,8 +172,15 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
return this;
}
- // Pushes a new element to the stack.
- void Push() { element_.reset(new Element(element_.release())); }
+ // Pushes a new JSON array element to the stack.
+ void PushArray() {
+ element_.reset(new Element(element_.release(), /*is_json_object=*/false));
+ }
+
+ // Pushes a new JSON object element to the stack.
+ void PushObject() {
+ element_.reset(new Element(element_.release(), /*is_json_object=*/true));
+ }
// Pops an element off of the stack and deletes the popped element.
void Pop() {
@@ -204,11 +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)); }
- // Returns the current value of empty_name_ok_for_next_key_ and resets it to
- // false.
- bool GetAndResetEmptyKeyOk();
-
- google::protobuf::scoped_ptr<Element> element_;
+ std::unique_ptr<Element> element_;
google::protobuf::io::CodedOutputStream* stream_;
ByteSinkWrapper sink_;
const string indent_string_;
@@ -217,11 +217,6 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
// to regular base64 encoding.
bool use_websafe_base64_for_bytes_;
- // Whether empty strings should be rendered for the next JSON key. This
- // setting is only valid until the next key is rendered, after which it gets
- // reset to false.
- bool empty_name_ok_for_next_key_;
-
GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(JsonObjectWriter);
};
diff --git a/src/google/protobuf/util/internal/json_objectwriter_test.cc b/src/google/protobuf/util/internal/json_objectwriter_test.cc
index bbd9d78a..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_;
@@ -95,6 +95,12 @@ TEST_F(JsonObjectWriterTest, EmptyList) {
output_.substr(0, out_stream_->ByteCount()));
}
+TEST_F(JsonObjectWriterTest, EmptyObjectKey) {
+ ow_ = new JsonObjectWriter("", out_stream_);
+ ow_->StartObject("")->RenderString("", "value")->EndObject();
+ EXPECT_EQ("{\"\":\"value\"}", output_.substr(0, out_stream_->ByteCount()));
+}
+
TEST_F(JsonObjectWriterTest, ObjectInObject) {
ow_ = new JsonObjectWriter("", out_stream_);
ow_->StartObject("")
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_writer.h b/src/google/protobuf/util/internal/object_writer.h
index b6fbd19b..5781aa1e 100644
--- a/src/google/protobuf/util/internal/object_writer.h
+++ b/src/google/protobuf/util/internal/object_writer.h
@@ -119,13 +119,6 @@ class LIBPROTOBUF_EXPORT ObjectWriter {
return use_strict_base64_decoding_;
}
- // Whether empty strings should be rendered for the next name for Start/Render
- // calls. This setting is only valid until the next key is rendered, after
- // which it gets reset.
- // It is up to the derived classes to interpret this and render accordingly.
- // Default implementation ignores this setting.
- virtual void empty_name_ok_for_next_key() {}
-
protected:
ObjectWriter() : use_strict_base64_decoding_(true) {}
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..28496963 100644
--- a/src/google/protobuf/util/internal/proto_writer.h
+++ b/src/google/protobuf/util/internal/proto_writer.h
@@ -81,32 +81,32 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
virtual ~ProtoWriter();
// ObjectWriter methods.
- 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()));
}
@@ -114,7 +114,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
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(); }
@@ -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_;
}
@@ -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 02360a1a..56e6db12 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,14 +294,12 @@ 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.");
}
ASSIGN_OR_RETURN(map_key, MapKeyDefaultValueAsString(*key_field));
- // Key is empty, force it to render as empty (for string values).
- ow->empty_name_ok_for_next_key();
}
RETURN_IF_ERROR(RenderField(field, map_key, ow));
} else {
@@ -527,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) {
@@ -545,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));
@@ -573,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;
}
@@ -595,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
@@ -669,7 +667,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;
}
@@ -756,7 +754,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()));
@@ -765,7 +763,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));
@@ -875,14 +873,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());
}
@@ -1004,10 +1003,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();
}
}
@@ -1051,8 +1050,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
@@ -1090,7 +1089,7 @@ const google::protobuf::Field* FindFieldByNumber(
return &type.fields(i);
}
}
- return NULL;
+ return nullptr;
}
// TODO(skarvaje): Replace FieldDescriptor by implementing IsTypePackable()
@@ -1111,7 +1110,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_test.cc b/src/google/protobuf/util/internal/protostream_objectsource_test.cc
index 36bb1ba9..df790728 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>
@@ -122,7 +119,7 @@ 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);
@@ -490,7 +487,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 +497,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);
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter.cc b/src/google/protobuf/util/internal/protostream_objectwriter.cc
index 97f96819..2edfd075 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,
@@ -541,14 +541,14 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartObject(
// 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..c33a4639 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter.h
+++ b/src/google/protobuf/util/internal/protostream_objectwriter.h
@@ -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_;
@@ -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..7f0df567 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_;
};
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..5630cc78 100644
--- a/src/google/protobuf/util/internal/testdata/books.proto
+++ b/src/google/protobuf/util/internal/testdata/books.proto
@@ -65,6 +65,7 @@ message Book {
KIDS = 2;
ACTION_AND_ADVENTURE = 3;
arts_and_photography = 4;
+ I18N_Tech = 5;
}
optional Type type = 11;
diff --git a/src/google/protobuf/util/internal/type_info.cc b/src/google/protobuf/util/internal/type_info.cc
index 85d0d5c9..3847b179 100644
--- a/src/google/protobuf/util/internal/type_info.cc
+++ b/src/google/protobuf/util/internal/type_info.cc
@@ -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 =
@@ -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());
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 11780ee8..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) {
@@ -353,8 +360,6 @@ bool IsMap(const google::protobuf::Field& field,
google::protobuf::Field_Cardinality_CARDINALITY_REPEATED &&
(GetBoolOptionOrDefault(type.options(), "map_entry", false) ||
GetBoolOptionOrDefault(type.options(),
- "google.protobuf.MessageOptions.map_entry", false) ||
- GetBoolOptionOrDefault(type.options(),
"google.protobuf.MessageOptions.map_entry",
false));
}
@@ -362,9 +367,6 @@ bool IsMap(const google::protobuf::Field& field,
bool IsMessageSetWireFormat(const google::protobuf::Type& type) {
return GetBoolOptionOrDefault(type.options(), "message_set_wire_format",
false) ||
- GetBoolOptionOrDefault(type.options(),
- "google.protobuf.MessageOptions.message_set_wire_format",
- false) ||
GetBoolOptionOrDefault(
type.options(),
"google.protobuf.MessageOptions.message_set_wire_format", false);
@@ -403,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 ce3569ce..f81a7a30 100644
--- a/src/google/protobuf/util/json_util.cc
+++ b/src/google/protobuf/util/json_util.cc
@@ -50,7 +50,9 @@ namespace util {
namespace internal {
ZeroCopyStreamByteSink::~ZeroCopyStreamByteSink() {
- stream_->BackUp(buffer_size_);
+ if (buffer_size_ > 0) {
+ stream_->BackUp(buffer_size_);
+ }
}
void ZeroCopyStreamByteSink::Append(const char* bytes, size_t len) {
@@ -95,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);
@@ -123,22 +127,22 @@ class StatusErrorListener : public converter::ErrorListener {
virtual void InvalidName(const converter::LocationTrackerInterface& loc,
StringPiece unknown_name, StringPiece message) {
status_ = util::Status(util::error::INVALID_ARGUMENT,
- loc.ToString() + ": " + message.ToString());
+ loc.ToString() + ": " + string(message));
}
virtual void InvalidValue(const converter::LocationTrackerInterface& loc,
StringPiece type_name, StringPiece value) {
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) {
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 dee3ddba..b1c69813 100644
--- a/src/google/protobuf/util/json_util.h
+++ b/src/google/protobuf/util/json_util.h
@@ -56,10 +56,10 @@ struct JsonPrintOptions {
// Whether to add spaces, line breaks and indentation to make the JSON output
// easy to read.
bool add_whitespace;
- // Whether to always print primitive fields. By default primitive fields with
- // default values will be omitted in JSON joutput. For example, an int32 field
- // set to 0 will be omitted. Set this flag to true will override the default
- // behavior and print primitive fields regardless of their values.
+ // Whether to always print primitive fields. By default proto3 primitive
+ // fields with default values will be omitted in JSON output. For example, an
+ // int32 field set to 0 will be omitted. Set this flag to true will override
+ // the default behavior and print primitive fields regardless of their values.
bool always_print_primitive_fields;
// Whether to always print enums as ints. By default they are rendered as
// strings.
diff --git a/src/google/protobuf/util/json_util_test.cc b/src/google/protobuf/util/json_util_test.cc
index 25c7e96c..ed9092df 100644
--- a/src/google/protobuf/util/json_util_test.cc
+++ b/src/google/protobuf/util/json_util_test.cc
@@ -34,6 +34,7 @@
#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>
@@ -47,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";
@@ -81,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) {
@@ -216,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.
@@ -312,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()));
@@ -332,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 {
@@ -457,6 +540,25 @@ TEST(ZeroCopyStreamByteSinkTest, TestAllInputOutputPatterns) {
}
}
+TEST_F(JsonUtilTest, TestWrongJsonInput) {
+ 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";
+ TypeResolver* resolver = NewTypeResolverForDescriptorPool(
+ "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(),
+ util::error::INVALID_ARGUMENT);
+}
+
} // namespace
} // namespace util
} // namespace protobuf
diff --git a/src/google/protobuf/util/message_differencer.cc b/src/google/protobuf/util/message_differencer.cc
index e964e041..9842f64c 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>
@@ -363,9 +360,6 @@ void MessageDifferencer::TreatAsMapUsingKeyComparator(
const MapKeyComparator* key_comparator) {
GOOGLE_CHECK(field->is_repeated()) << "Field must be repeated: "
<< field->full_name();
- GOOGLE_CHECK_EQ(FieldDescriptor::CPPTYPE_MESSAGE, field->cpp_type())
- << "Field has to be message type. Field name is: "
- << field->full_name();
GOOGLE_CHECK(set_fields_.find(field) == set_fields_.end())
<< "Cannot treat this repeated field as both Map and Set for "
<< "comparison.";
@@ -493,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()) {
@@ -1071,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;
@@ -1344,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_;
@@ -1462,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,
@@ -1751,6 +1761,13 @@ void MessageDifferencer::StreamReporter::ReportUnknownFieldIgnored(
printer_->Print("\n"); // Print for newlines.
}
+MessageDifferencer::MapKeyComparator*
+MessageDifferencer::CreateMultipleFieldsMapKeyComparator(
+ const std::vector<std::vector<const FieldDescriptor*> >& key_field_paths) {
+ return new MultipleFieldsMapKeyComparator(this, key_field_paths);
+}
+
+
} // namespace util
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/util/message_differencer.h b/src/google/protobuf/util/message_differencer.h
index b7d4de00..bbcf8498 100644
--- a/src/google/protobuf/util/message_differencer.h
+++ b/src/google/protobuf/util/message_differencer.h
@@ -64,6 +64,7 @@ class Printer;
namespace util {
+class DefaultFieldComparator;
class FieldContext; // declared below MessageDifferencer
// A basic differencer that can be used to determine
@@ -174,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
@@ -372,7 +371,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// repeated fields have different numbers of elements, the
// unpaired elements are reported using ReportAdded() or
// ReportDeleted().
- AS_SET, // Treat all the repeated fields as sets by default.
+ AS_SET, // Treat all the repeated fields as sets.
// See TreatAsSet(), as below.
};
@@ -386,6 +385,11 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// the only differences between the compared messages is that some fields
// have been moved, then the comparison returns true.
//
+ // Note that despite the name of this method, this is really
+ // comparison as multisets: if one side of the comparison has a duplicate
+ // in the repeated field but the other side doesn't, this will count as
+ // a mismatch.
+ //
// If the scope of comparison is set to PARTIAL, then in addition to what's
// above, extra values added to repeated fields of the second message will
// not cause the comparison to fail.
@@ -470,6 +474,10 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
const FieldDescriptor* field,
const MapKeyComparator* key_comparator);
+ // Initiates and returns a new instance of MultipleFieldsMapKeyComparator.
+ MapKeyComparator* CreateMultipleFieldsMapKeyComparator(
+ const std::vector<std::vector<const FieldDescriptor*> >& key_field_paths);
+
// Add a custom ignore criteria that is evaluated in addition to the
// ignored fields added with IgnoreField.
// Takes ownership of ignore_criteria.
@@ -660,6 +668,8 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
};
private:
+ friend class DefaultFieldComparator;
+
// A MapKeyComparator to be used in TreatAsMapUsingKeyComparator.
// Implementation of this class needs to do field value comparison which
// relies on some private methods of MessageDifferencer. That's why this
@@ -811,7 +821,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);
@@ -852,7 +862,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
--- 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..a69ed58c 100644
--- a/src/google/protobuf/util/type_resolver_util.cc
+++ b/src/google/protobuf/util/type_resolver_util.cc
@@ -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_lite.cc b/src/google/protobuf/wire_format_lite.cc
index cd343b74..1d8cda5a 100644
--- a/src/google/protobuf/wire_format_lite.cc
+++ b/src/google/protobuf/wire_format_lite.cc
@@ -34,9 +34,6 @@
#include <google/protobuf/wire_format_lite_inl.h>
-#ifdef __SSE_4_1__
-#include <immintrin.h>
-#endif
#include <stack>
#include <string>
#include <vector>
@@ -635,12 +632,12 @@ bool WireFormatLite::VerifyUtf8String(const char* data,
return true;
}
-#ifdef __SSE_4_1__
-template<typename T, bool ZigZag, bool SignExtended>
-static size_t VarintSize(
- const T* data, const int n,
- const internal::enable_if<sizeof(T) == 4>::type* = NULL) {
+// this code is deliberately written such that clang makes it into really
+// efficient SSE code.
+template<bool ZigZag, bool SignExtended, typename T>
+static size_t VarintSize(const T* data, const int n) {
#if __cplusplus >= 201103L
+ static_assert(sizeof(T) == 4, "This routine only works for 32 bit integers");
// is_unsigned<T> => !ZigZag
static_assert((std::is_unsigned<T>::value ^ ZigZag) ||
std::is_signed<T>::value,
@@ -649,101 +646,83 @@ static size_t VarintSize(
static_assert((std::is_unsigned<T>::value ^ SignExtended) ||
std::is_signed<T>::value,
"Cannot SignExtended unsigned types");
+ static_assert(!(SignExtended && ZigZag),
+ "Cannot SignExtended and ZigZag on the same type");
#endif
-
- union vus32 {
- uint32 u[4];
- int32 s[4];
- __m128i v;
- };
-
- static const vus32 ones = {{1, 1, 1, 1}};
-
- // CodedOutputStream::VarintSize32SignExtended returns 10 for negative
- // numbers. We can apply the UInt32Size algorithm, and simultaneously logical
- // shift the MSB into the LSB to determine if it is negative.
- static const vus32 fives = {{5, 5, 5, 5}};
-
- // sum is the vectorized-output of calling CodedOutputStream::VarintSize32 on
- // the processed elements.
- //
- // msb_sum is the count of set most-significant bits. When computing the
- // vectorized CodedOutputStream::VarintSize32SignExtended, negative values
- // have the most significant bit set. VarintSize32SignExtended returns 10 and
- // VarintSize32 returns 5. msb_sum allows us to compute:
- // VarintSize32SignExtended = msb_sum * 5 + VarintSize32
- vus32 sum, v, msb_sum;
- sum.v = _mm_setzero_si128();
- msb_sum.v = _mm_setzero_si128();
-
- int rounded = n & ~(3);
- int i;
- for (i = 0; i < rounded; i += 4) {
- v.v = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&data[i]));
-
+ uint32 sum = n;
+ uint32 msb_sum = 0;
+ for (int i = 0; i < n; i++) {
+ uint32 x = data[i];
if (ZigZag) {
- // Note: the right-shift must be arithmetic
- v.v = _mm_xor_si128(_mm_slli_epi32(v.v, 1), _mm_srai_epi32(v.v, 31));
- }
-
- sum.v = _mm_add_epi32(sum.v, ones.v);
- if (SignExtended) {
- msb_sum.v = _mm_add_epi32(msb_sum.v, _mm_srli_epi32(v.v, 31));
- }
-
- v.v = _mm_srli_epi32(v.v, 7);
-
- for (int j = 0; j < 4; j++) {
- __m128i min = _mm_min_epi32(v.v, ones.v);
-
- sum.v = _mm_add_epi32(sum.v, min);
- v.v = _mm_srli_epi32(v.v, 7);
+ x = WireFormatLite::ZigZagEncode32(x);
+ } else if (SignExtended) {
+ msb_sum += x >> 31;
}
+ // clang is so smart that it produces optimal SSE sequence unrolling
+ // the loop 8 ints at a time. With a sequence of 4
+ // cmpres = cmpgt x, sizeclass ( -1 or 0)
+ // sum = sum - cmpres
+ if (x > 0x7F) sum++;
+ if (x > 0x3FFF) sum++;
+ if (x > 0x1FFFFF) sum++;
+ if (x > 0xFFFFFFF) sum++;
}
+ if (SignExtended) sum += msb_sum * 5;
+ return sum;
+}
- if (SignExtended) {
- vus32 extensions;
- extensions.v = _mm_mullo_epi32(msb_sum.v, fives.v);
-
- sum.v = _mm_add_epi32(sum.v, extensions.v);
- }
-
- // TODO(ckennelly): Can we avoid the sign conversion?
- size_t out = _mm_cvtsi128_si32(
- _mm_hadd_epi32(_mm_hadd_epi32(sum.v, ones.v), ones.v));
-
- // Finish tail.
- for (; i < n; i++) {
+template<bool ZigZag, typename T>
+static size_t VarintSize64(const T* data, const int n) {
+#if __cplusplus >= 201103L
+ static_assert(sizeof(T) == 8, "This routine only works for 64 bit integers");
+ // is_unsigned<T> => !ZigZag
+ static_assert(!ZigZag || !std::is_unsigned<T>::value,
+ "Cannot ZigZag encode unsigned types");
+#endif
+ uint64 sum = n;
+ for (int i = 0; i < n; i++) {
+ uint64 x = data[i];
if (ZigZag) {
- out += WireFormatLite::SInt32Size(data[i]);
- } else if (SignExtended) {
- out += WireFormatLite::Int32Size(data[i]);
- } else {
- out += WireFormatLite::UInt32Size(data[i]);
+ x = WireFormatLite::ZigZagEncode64(x);
}
+ // First step is a binary search, we can't branch in sse so we use the
+ // result of the compare to adjust sum and appropriately. This code is
+ // written to make clang recognize the vectorization.
+ uint64 tmp = x >= (static_cast<uint64>(1) << 35) ? -1 : 0;
+ sum += 5 & tmp;
+ x >>= 35 & tmp;
+ if (x > 0x7F) sum++;
+ if (x > 0x3FFF) sum++;
+ if (x > 0x1FFFFF) sum++;
+ if (x > 0xFFFFFFF) sum++;
}
-
- return out;
+ return sum;
}
+// GCC does not recognize the vectorization opportunity
+// and other platforms are untested, in those cases using the optimized
+// varint size routine for each element is faster.
+// Hence we enable it only for clang
+#if defined(__SSE__) && defined(__clang__)
size_t WireFormatLite::Int32Size(const RepeatedField<int32>& value) {
- return VarintSize<int32, false, true>(value.data(), value.size());
+ return VarintSize<false, true>(value.data(), value.size());
}
size_t WireFormatLite::UInt32Size(const RepeatedField<uint32>& value) {
- return VarintSize<uint32, false, false>(value.data(), value.size());
+ return VarintSize<false, false>(value.data(), value.size());
}
size_t WireFormatLite::SInt32Size(const RepeatedField<int32>& value) {
- return VarintSize<int32, true, true>(value.data(), value.size());
+ return VarintSize<true, false>(value.data(), value.size());
}
size_t WireFormatLite::EnumSize(const RepeatedField<int>& value) {
// On ILP64, sizeof(int) == 8, which would require a different template.
- return VarintSize<int, false, true>(value.data(), value.size());
+ return VarintSize<false, true>(value.data(), value.size());
}
-#else // !__SSE_4_1__
+#else // !(defined(__SSE4_1__) && defined(__clang__))
+
size_t WireFormatLite::Int32Size(const RepeatedField<int32>& value) {
size_t out = 0;
const int n = value.size();
@@ -779,6 +758,56 @@ size_t WireFormatLite::EnumSize(const RepeatedField<int>& value) {
}
return out;
}
+
+#endif
+
+// Micro benchmarks show that the SSE improved loop only starts beating
+// the normal loop on Haswell platforms and then only for >32 ints. We
+// disable this for now. Some specialized users might find it worthwhile to
+// enable this.
+#define USE_SSE_FOR_64_BIT_INTEGER_ARRAYS 0
+#if USE_SSE_FOR_64_BIT_INTEGER_ARRAYS
+size_t WireFormatLite::Int64Size (const RepeatedField< int64>& value) {
+ return VarintSize64<false>(value.data(), value.size());
+}
+
+size_t WireFormatLite::UInt64Size(const RepeatedField<uint64>& value) {
+ return VarintSize64<false>(value.data(), value.size());
+}
+
+size_t WireFormatLite::SInt64Size(const RepeatedField< int64>& value) {
+ return VarintSize64<true>(value.data(), value.size());
+}
+
+#else
+
+size_t WireFormatLite::Int64Size (const RepeatedField< int64>& value) {
+ size_t out = 0;
+ const int n = value.size();
+ for (int i = 0; i < n; i++) {
+ out += Int64Size(value.Get(i));
+ }
+ return out;
+}
+
+size_t WireFormatLite::UInt64Size(const RepeatedField<uint64>& value) {
+ size_t out = 0;
+ const int n = value.size();
+ for (int i = 0; i < n; i++) {
+ out += UInt64Size(value.Get(i));
+ }
+ return out;
+}
+
+size_t WireFormatLite::SInt64Size(const RepeatedField< int64>& value) {
+ size_t out = 0;
+ const int n = value.size();
+ for (int i = 0; i < n; i++) {
+ out += SInt64Size(value.Get(i));
+ }
+ return out;
+}
+
#endif
} // namespace internal
diff --git a/src/google/protobuf/wire_format_lite.h b/src/google/protobuf/wire_format_lite.h
index 361920b8..77eaa9a6 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);
@@ -674,13 +671,13 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
static inline size_t SInt64Size ( int64 value);
static inline size_t EnumSize ( int value);
- static size_t Int32Size (const RepeatedField< int32>& value);
- static inline size_t Int64Size (const RepeatedField< int64>& value);
- static size_t UInt32Size(const RepeatedField<uint32>& value);
- static inline size_t UInt64Size(const RepeatedField<uint64>& value);
- static size_t SInt32Size(const RepeatedField< int32>& value);
- static inline size_t SInt64Size(const RepeatedField< int64>& value);
- static size_t EnumSize (const RepeatedField< int>& value);
+ static size_t Int32Size (const RepeatedField< int32>& value);
+ static size_t Int64Size (const RepeatedField< int64>& value);
+ static size_t UInt32Size(const RepeatedField<uint32>& value);
+ static size_t UInt64Size(const RepeatedField<uint64>& value);
+ static size_t SInt32Size(const RepeatedField< int32>& value);
+ static size_t SInt64Size(const RepeatedField< int64>& value);
+ static size_t EnumSize (const RepeatedField< int>& value);
// These types always have the same size.
static const size_t kFixed32Size = 4;
@@ -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
diff --git a/src/google/protobuf/wire_format_lite_inl.h b/src/google/protobuf/wire_format_lite_inl.h
index b264bd7e..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());
}
@@ -1043,33 +989,6 @@ inline size_t WireFormatLite::LengthDelimitedSize(size_t length) {
static_cast<uint32>(length));
}
-size_t WireFormatLite::Int64Size (const RepeatedField< int64>& value) {
- size_t out = 0;
- const int n = value.size();
- for (int i = 0; i < n; i++) {
- out += Int64Size(value.Get(i));
- }
- return out;
-}
-
-size_t WireFormatLite::UInt64Size(const RepeatedField<uint64>& value) {
- size_t out = 0;
- const int n = value.size();
- for (int i = 0; i < n; i++) {
- out += UInt64Size(value.Get(i));
- }
- return out;
-}
-
-size_t WireFormatLite::SInt64Size(const RepeatedField< int64>& value) {
- size_t out = 0;
- const int n = value.size();
- for (int i = 0; i < n; i++) {
- out += SInt64Size(value.Get(i));
- }
- return out;
-}
-
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/wire_format_unittest.cc b/src/google/protobuf/wire_format_unittest.cc
index cafe9a48..736a1282 100644
--- a/src/google/protobuf/wire_format_unittest.cc
+++ b/src/google/protobuf/wire_format_unittest.cc
@@ -1436,6 +1436,7 @@ TEST(RepeatedVarint, Enum) {
EXPECT_EQ(expected, WireFormatLite::EnumSize(v));
}
+
} // namespace
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/wrappers.pb.cc b/src/google/protobuf/wrappers.pb.cc
index 00e01256..ffd905f5 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];
@@ -342,15 +291,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
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 ::google::protobuf::internal::once_flag once;
+ ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
@@ -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() {
@@ -449,9 +394,7 @@ void DoubleValue::ArenaDtor(void* object) {
void DoubleValue::RegisterArenaDtor(::google::protobuf::Arena* 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,13 +402,10 @@ 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();
}
-DoubleValue* DoubleValue::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<DoubleValue>(arena);
-}
void DoubleValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.DoubleValue)
@@ -483,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)) {
@@ -574,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;
}
@@ -648,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 {
@@ -667,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)
@@ -692,7 +627,6 @@ FloatValue::FloatValue(const FloatValue& from)
void FloatValue::SharedCtor() {
value_ = 0;
- _cached_size_ = 0;
}
FloatValue::~FloatValue() {
@@ -711,9 +645,7 @@ void FloatValue::ArenaDtor(void* object) {
void FloatValue::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -721,13 +653,10 @@ 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();
}
-FloatValue* FloatValue::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<FloatValue>(arena);
-}
void FloatValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FloatValue)
@@ -745,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)) {
@@ -836,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;
}
@@ -910,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 {
@@ -929,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)
@@ -954,7 +878,6 @@ Int64Value::Int64Value(const Int64Value& from)
void Int64Value::SharedCtor() {
value_ = GOOGLE_LONGLONG(0);
- _cached_size_ = 0;
}
Int64Value::~Int64Value() {
@@ -973,9 +896,7 @@ void Int64Value::ArenaDtor(void* object) {
void Int64Value::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -983,13 +904,10 @@ 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();
}
-Int64Value* Int64Value::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<Int64Value>(arena);
-}
void Int64Value::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Int64Value)
@@ -1007,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)) {
@@ -1100,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;
}
@@ -1174,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 {
@@ -1193,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)
@@ -1218,7 +1131,6 @@ UInt64Value::UInt64Value(const UInt64Value& from)
void UInt64Value::SharedCtor() {
value_ = GOOGLE_ULONGLONG(0);
- _cached_size_ = 0;
}
UInt64Value::~UInt64Value() {
@@ -1237,9 +1149,7 @@ void UInt64Value::ArenaDtor(void* object) {
void UInt64Value::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -1247,13 +1157,10 @@ 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();
}
-UInt64Value* UInt64Value::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<UInt64Value>(arena);
-}
void UInt64Value::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.UInt64Value)
@@ -1271,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)) {
@@ -1364,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;
}
@@ -1438,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 {
@@ -1457,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)
@@ -1482,7 +1384,6 @@ Int32Value::Int32Value(const Int32Value& from)
void Int32Value::SharedCtor() {
value_ = 0;
- _cached_size_ = 0;
}
Int32Value::~Int32Value() {
@@ -1501,9 +1402,7 @@ void Int32Value::ArenaDtor(void* object) {
void Int32Value::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -1511,13 +1410,10 @@ 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();
}
-Int32Value* Int32Value::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<Int32Value>(arena);
-}
void Int32Value::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Int32Value)
@@ -1535,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)) {
@@ -1628,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;
}
@@ -1702,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 {
@@ -1721,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)
@@ -1746,7 +1637,6 @@ UInt32Value::UInt32Value(const UInt32Value& from)
void UInt32Value::SharedCtor() {
value_ = 0u;
- _cached_size_ = 0;
}
UInt32Value::~UInt32Value() {
@@ -1765,9 +1655,7 @@ void UInt32Value::ArenaDtor(void* object) {
void UInt32Value::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -1775,13 +1663,10 @@ 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();
}
-UInt32Value* UInt32Value::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<UInt32Value>(arena);
-}
void UInt32Value::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.UInt32Value)
@@ -1799,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)) {
@@ -1892,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;
}
@@ -1966,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 {
@@ -1985,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)
@@ -2010,7 +1890,6 @@ BoolValue::BoolValue(const BoolValue& from)
void BoolValue::SharedCtor() {
value_ = false;
- _cached_size_ = 0;
}
BoolValue::~BoolValue() {
@@ -2029,9 +1908,7 @@ void BoolValue::ArenaDtor(void* object) {
void BoolValue::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -2039,13 +1916,10 @@ 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();
}
-BoolValue* BoolValue::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<BoolValue>(arena);
-}
void BoolValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.BoolValue)
@@ -2063,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)) {
@@ -2154,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;
}
@@ -2228,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 {
@@ -2247,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) {
@@ -2276,7 +2145,6 @@ StringValue::StringValue(const StringValue& from)
void StringValue::SharedCtor() {
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- _cached_size_ = 0;
}
StringValue::~StringValue() {
@@ -2296,9 +2164,7 @@ void StringValue::ArenaDtor(void* object) {
void StringValue::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -2306,13 +2172,10 @@ 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();
}
-StringValue* StringValue::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<StringValue>(arena);
-}
void StringValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.StringValue)
@@ -2330,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)) {
@@ -2436,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;
}
@@ -2508,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 {
@@ -2529,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) {
@@ -2558,7 +2417,6 @@ BytesValue::BytesValue(const BytesValue& from)
void BytesValue::SharedCtor() {
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- _cached_size_ = 0;
}
BytesValue::~BytesValue() {
@@ -2578,9 +2436,7 @@ void BytesValue::ArenaDtor(void* object) {
void BytesValue::RegisterArenaDtor(::google::protobuf::Arena* 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();
@@ -2588,13 +2444,10 @@ 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();
}
-BytesValue* BytesValue::New(::google::protobuf::Arena* arena) const {
- return ::google::protobuf::Arena::CreateMessage<BytesValue>(arena);
-}
void BytesValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.BytesValue)
@@ -2612,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)) {
@@ -2706,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;
}
@@ -2778,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 {
@@ -2792,5 +2643,36 @@ void BytesValue::InternalSwap(BytesValue* other) {
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
+namespace google {
+namespace protobuf {
+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::CreateMaybeMessage< ::google::protobuf::FloatValue >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::FloatValue >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Int64Value* Arena::CreateMaybeMessage< ::google::protobuf::Int64Value >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::Int64Value >(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::CreateMaybeMessage< ::google::protobuf::Int32Value >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::Int32Value >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UInt32Value* Arena::CreateMaybeMessage< ::google::protobuf::UInt32Value >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::UInt32Value >(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::CreateMaybeMessage< ::google::protobuf::StringValue >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::StringValue >(arena);
+}
+template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::BytesValue* Arena::CreateMaybeMessage< ::google::protobuf::BytesValue >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::BytesValue >(arena);
+}
+} // namespace protobuf
+} // namespace google
// @@protoc_insertion_point(global_scope)
diff --git a/src/google/protobuf/wrappers.pb.h b/src/google/protobuf/wrappers.pb.h
index a2f10c8b..9f51a062 100644
--- a/src/google/protobuf/wrappers.pb.h
+++ b/src/google/protobuf/wrappers.pb.h
@@ -1,8 +1,8 @@
// 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>
@@ -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,6 +78,19 @@ LIBPROTOBUF_EXPORT extern UInt64ValueDefaultTypeInternal _UInt64Value_default_in
} // namespace google
namespace google {
namespace protobuf {
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::BoolValue* Arena::CreateMaybeMessage<::google::protobuf::BoolValue>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::BytesValue* Arena::CreateMaybeMessage<::google::protobuf::BytesValue>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::DoubleValue* Arena::CreateMaybeMessage<::google::protobuf::DoubleValue>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::FloatValue* Arena::CreateMaybeMessage<::google::protobuf::FloatValue>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Int32Value* Arena::CreateMaybeMessage<::google::protobuf::Int32Value>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::Int64Value* Arena::CreateMaybeMessage<::google::protobuf::Int64Value>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::StringValue* Arena::CreateMaybeMessage<::google::protobuf::StringValue>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::UInt32Value* Arena::CreateMaybeMessage<::google::protobuf::UInt32Value>(Arena*);
+template<> LIBPROTOBUF_EXPORT ::google::protobuf::UInt64Value* Arena::CreateMaybeMessage<::google::protobuf::UInt64Value>(Arena*);
+} // namespace protobuf
+} // namespace google
+namespace google {
+namespace protobuf {
// ===================================================================
@@ -134,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();
@@ -148,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);
@@ -159,28 +145,33 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
// implements Message ----------------------------------------------
- inline DoubleValue* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline DoubleValue* New() const final {
+ return CreateMaybeMessage<DoubleValue>(NULL);
+ }
- DoubleValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ DoubleValue* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<DoubleValue>(arena);
+ }
+ 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);
@@ -196,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 ----------------------------------------------------
@@ -216,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();
};
// -------------------------------------------------------------------
@@ -248,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();
@@ -262,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);
@@ -273,28 +263,33 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
// implements Message ----------------------------------------------
- inline FloatValue* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline FloatValue* New() const final {
+ return CreateMaybeMessage<FloatValue>(NULL);
+ }
- FloatValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ FloatValue* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<FloatValue>(arena);
+ }
+ 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);
@@ -310,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 ----------------------------------------------------
@@ -330,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();
};
// -------------------------------------------------------------------
@@ -362,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();
@@ -376,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);
@@ -387,28 +381,33 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
// implements Message ----------------------------------------------
- inline Int64Value* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Int64Value* New() const final {
+ return CreateMaybeMessage<Int64Value>(NULL);
+ }
- Int64Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Int64Value* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Int64Value>(arena);
+ }
+ 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);
@@ -424,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 ----------------------------------------------------
@@ -444,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();
};
// -------------------------------------------------------------------
@@ -476,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();
@@ -490,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);
@@ -501,28 +499,33 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
// implements Message ----------------------------------------------
- inline UInt64Value* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline UInt64Value* New() const final {
+ return CreateMaybeMessage<UInt64Value>(NULL);
+ }
- UInt64Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ UInt64Value* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<UInt64Value>(arena);
+ }
+ 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);
@@ -538,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 ----------------------------------------------------
@@ -558,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();
};
// -------------------------------------------------------------------
@@ -590,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();
@@ -604,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);
@@ -615,28 +617,33 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
// implements Message ----------------------------------------------
- inline Int32Value* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline Int32Value* New() const final {
+ return CreateMaybeMessage<Int32Value>(NULL);
+ }
- Int32Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ Int32Value* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<Int32Value>(arena);
+ }
+ 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);
@@ -652,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 ----------------------------------------------------
@@ -672,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();
};
// -------------------------------------------------------------------
@@ -704,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();
@@ -718,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);
@@ -729,28 +735,33 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
// implements Message ----------------------------------------------
- inline UInt32Value* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline UInt32Value* New() const final {
+ return CreateMaybeMessage<UInt32Value>(NULL);
+ }
- UInt32Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ UInt32Value* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<UInt32Value>(arena);
+ }
+ 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);
@@ -766,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 ----------------------------------------------------
@@ -786,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();
};
// -------------------------------------------------------------------
@@ -818,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();
@@ -832,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);
@@ -843,28 +853,33 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
// implements Message ----------------------------------------------
- inline BoolValue* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline BoolValue* New() const final {
+ return CreateMaybeMessage<BoolValue>(NULL);
+ }
- BoolValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ BoolValue* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<BoolValue>(arena);
+ }
+ 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);
@@ -880,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 ----------------------------------------------------
@@ -900,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();
};
// -------------------------------------------------------------------
@@ -932,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();
@@ -946,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);
@@ -957,28 +971,33 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
// implements Message ----------------------------------------------
- inline StringValue* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline StringValue* New() const final {
+ return CreateMaybeMessage<StringValue>(NULL);
+ }
- StringValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ StringValue* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<StringValue>(arena);
+ }
+ 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);
@@ -994,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 ----------------------------------------------------
@@ -1031,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();
};
// -------------------------------------------------------------------
@@ -1063,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();
@@ -1077,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);
@@ -1088,28 +1106,33 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
// implements Message ----------------------------------------------
- inline BytesValue* New() const PROTOBUF_FINAL { return New(NULL); }
+ inline BytesValue* New() const final {
+ return CreateMaybeMessage<BytesValue>(NULL);
+ }
- BytesValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
- void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
- void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ BytesValue* New(::google::protobuf::Arena* arena) const final {
+ return CreateMaybeMessage<BytesValue>(arena);
+ }
+ 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);
@@ -1125,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 ----------------------------------------------------
@@ -1162,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();
};
// ===================================================================
@@ -1484,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 e2bc01c9..5fec74c0 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
@@ -44,10 +47,7 @@ build_cpp() {
# appears to be missing it: https://github.com/travis-ci/travis-ci/issues/6996
if [[ $(type cmake 2>/dev/null) ]]; then
# Verify benchmarking code can build successfully.
- git submodule init
- git submodule update
- cd third_party/benchmark && cmake -DCMAKE_BUILD_TYPE=Release && make && cd ../..
- cd benchmarks && make && ./generate-datasets && cd ..
+ cd benchmarks && make cpp-benchmark && cd ..
else
echo ""
echo "WARNING: Skipping validation of the bench marking code, cmake isn't installed."
@@ -56,6 +56,8 @@ build_cpp() {
}
build_cpp_distcheck() {
+ # Initialize any submodules.
+ git submodule update --init --recursive
./autogen.sh
./configure
make dist
@@ -87,9 +89,7 @@ build_cpp_distcheck() {
}
build_csharp() {
- # Just for the conformance tests. We don't currently
- # need to really build protoc, but it's simplest to keep with the
- # conventions of the other builds.
+ # Required for conformance tests and to regenerate protos.
internal_build_cpp
NUGET=/usr/local/bin/nuget.exe
@@ -104,6 +104,10 @@ build_csharp() {
(cd dotnettmp; dotnet new > /dev/null)
rm -rf dotnettmp
+ # 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 ..
@@ -224,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
diff --git a/third_party/benchmark b/third_party/benchmark
-Subproject 360e66c1c4777c99402cf8cd535aa510fee1657
+Subproject 5b7683f49e1e9223cf9927b24f6fd3d6bd82e3f
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